programing

NotificationCompat.Android O에서 Builder가 더 이상 사용되지 않음

itmemos 2023. 8. 5. 09:55
반응형

NotificationCompat.Android O에서 Builder가 더 이상 사용되지 않음

내 프로젝트를 Android O로 업그레이드한 후

buildToolsVersion "26.0.1"

Android Studio의 Lint는 다음 알림 작성기 방법에 대해 사용되지 않는 경고를 표시합니다.

new NotificationCompat.Builder(context)

문제는 Android Developers가 Android O에서 알림을 지원하도록 Notification Channel을 설명하는 문서를 업데이트하고, 동일한 경고가 포함된 스니펫을 제공한다는 점입니다.

Notification notification = new Notification.Builder(MainActivity.this)
        .setContentTitle("New Message")
        .setContentText("You've received new messages.")
        .setSmallIcon(R.drawable.ic_notify_status)
        .setChannelId(CHANNEL_ID)
        .build();  

알림 개요

내 질문:빌드 알림을 위한 다른 솔루션이 있으며, 여전히 안드로이드 O를 지원합니까?

제가 찾은 해결책은 Notification에서 채널 ID를 매개 변수로 전달하는 것입니다.작성자 생성자.하지만 이 솔루션은 정확히 재사용할 수 없습니다.

new Notification.Builder(MainActivity.this, "channel_id")

설명서에 작성자 방법이 언급되어 있습니다.NotificationCompat.Builder(Context context)더 이상 사용되지 않습니다.그리고 우리는 다음을 가진 생성자를 사용해야 합니다.channelId매개변수:

NotificationCompat.Builder(Context context, String channelId)

NotificationCompat.Builder 설명서:

이 생성자는 API 수준 26.0.0-beta1에서 더 이상 사용되지 않습니다.NotificationCompat을 사용합니다.대신 작성자(컨텍스트, 문자열)를 입력합니다.게시된 모든 알림은 알림 채널 ID를 지정해야 합니다.

알림.Builder 설명서:

이 생성자는 API 수준 26에서 더 이상 사용되지 않습니다. 알림을 사용하십시오.대신 작성자(컨텍스트, 문자열)를 입력합니다.게시된 모든 알림은 알림 채널 ID를 지정해야 합니다.

빌더 설정자를 재사용하려면 다음을 사용하여 빌더를 생성할 수 있습니다.channelId해당 작성기를 도우미 메소드로 전달하고 해당 메소드에서 원하는 설정을 설정합니다.

enter image description here

아래는 하위 호환성을 갖춘 API LEVEL 26+ 기준의 모든 안드로이드 버전에 대한 작동 코드입니다.

 NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext(), "M_CH_ID");

        notificationBuilder.setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_launcher)
                .setTicker("Hearty365")
                .setPriority(Notification.PRIORITY_MAX) // this is deprecated in API 26 but you can still use for below 26. check below update for 26 API
                .setContentTitle("Default notification")
                .setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
                .setContentInfo("Info");

NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notificationBuilder.build());

최대 우선순위를 설정하기 위한 API 26의 UPDATE

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);

        // Configure the notification channel.
        notificationChannel.setDescription("Channel description");
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
        notificationChannel.enableVibration(true);
        notificationManager.createNotificationChannel(notificationChannel);
    }


    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);

    notificationBuilder.setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.ic_launcher)
            .setTicker("Hearty365")
       //     .setPriority(Notification.PRIORITY_MAX)
            .setContentTitle("Default notification")
            .setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
            .setContentInfo("Info");

    notificationManager.notify(/*notification id*/1, notificationBuilder.build());

2-arg 생성자를 호출합니다.Android O와의 호환성은 support-v4로 문의하십시오.NotificationCompat.Builder(Context context, String channelId)Android N 이전 버전에서 실행할 경우channelId무시됩니다.Android O에서 실행할 때도 다음을 생성합니다.NotificationChannel마찬가지로channelId.

오래된 샘플 코드:통지와 같은 여러 JavaDoc 페이지의 샘플 코드입니다.작성자 호출new Notification.Builder(mContext)최신 버전이 아닙니다.

사용되지 않는 생성자: Notification.Builder(Context context) v4 NotificationCompat.Builder(Context context)을 위해 추천되지 않습니다.Notification[Compat].Builder(Context context, String channelId)(알림 참조).빌더(안드로이드.콘텐츠).컨텍스트) 및 v4 NotificationCompat.작성기(콘텍스트 컨텍스트).

사용되지 않는 클래스: 전체 v7 NotificationCompat.Builder사용되지 않습니다.v7 NotificationCompat을 참조하십시오.작성자.)이전 버전, v7NotificationCompat.Builder를 지원하기 위해 필요했습니다.NotificationCompat.MediaStyle Android O는 v4가 NotificationCompat.MediaStyle미디어 호환 라이브러리의android.support.v4.media꾸러미필요하면 저것을 사용하세요.MediaStyle.

API 14+: 26.0.0 이상의 Support Library에서는 support-v4 및 support-v7 패키지가 모두 최소 API 레벨 14를 지원합니다.v# 이름은 과거 이름입니다.

최신 지원 라이브러리 버전을 참조하십시오.

대신인을 에.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O하듯이, 더 방법이 - 은답대시듯이사하많있방, 약간더간법습다니이한단이다▁as▁-많있니습방▁there법.

에추니다합에 다음 합니다.applicationAndroid 문서에서 Firebase Cloud Messaging Client설정에 설명된 AndroidManifest.xml 파일의 섹션:

    <meta-data
        android:name="com.google.firebase.messaging.default_notification_channel_id" 
        android:value="@string/default_notification_channel_id" />

그런 다음 values/strings.xml 파일에 채널 이름이 있는 행을 추가합니다.

<string name="default_notification_channel_id">default</string>

그런 다음 새 버전의 NotificationCompat을 사용할 수 있습니다.2개의 매개 변수를 가진 빌더 생성자(1개의 매개 변수를 가진 이전 생성자가 Android Oreo에서 더 이상 사용되지 않으므로):

private void sendNotification(String title, String body) {
    Intent i = new Intent(this, MainActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pi = PendingIntent.getActivity(this,
            0 /* Request code */,
            i,
            PendingIntent.FLAG_ONE_SHOT);

    Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, 
        getString(R.string.default_notification_channel_id))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(title)
            .setContentText(body)
            .setAutoCancel(true)
            .setSound(sound)
            .setContentIntent(pi);

    NotificationManager manager = 
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    manager.notify(0, builder.build());
}

Android Oreo에서 작동하며 Oreo보다 적은 샘플 코드입니다.

  NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationCompat.Builder builder = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                int importance = NotificationManager.IMPORTANCE_DEFAULT;
                NotificationChannel notificationChannel = new NotificationChannel("ID", "Name", importance);
                notificationManager.createNotificationChannel(notificationChannel);
                builder = new NotificationCompat.Builder(getApplicationContext(), notificationChannel.getId());
            } else {
                builder = new NotificationCompat.Builder(getApplicationContext());
            }

            builder = builder
                    .setSmallIcon(R.drawable.ic_notification_icon)
                    .setColor(ContextCompat.getColor(context, R.color.color))
                    .setContentTitle(context.getString(R.string.getTitel))
                    .setTicker(context.getString(R.string.text))
                    .setContentText(message)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true);
            notificationManager.notify(requestCode, builder.build());

간단한 샘플

    public void showNotification (String from, String notification, Intent intent) {
        PendingIntent pendingIntent = PendingIntent.getActivity(
                context,
                Notification_ID,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT
        );


        String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);

            // Configure the notification channel.
            notificationChannel.setDescription("Channel description");
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
            notificationChannel.enableVibration(true);
            notificationManager.createNotificationChannel(notificationChannel);
        }


        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
        Notification mNotification = builder
                .setContentTitle(from)
                .setContentText(notification)

//                .setTicker("Hearty365")
//                .setContentInfo("Info")
                //     .setPriority(Notification.PRIORITY_MAX)

                .setContentIntent(pendingIntent)

                .setAutoCancel(true)
//                .setDefaults(Notification.DEFAULT_ALL)
//                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
                .build();

        notificationManager.notify(/*notification id*/Notification_ID, mNotification);

    }
Notification notification = new Notification.Builder(MainActivity.this)
        .setContentTitle("New Message")
        .setContentText("You've received new messages.")
        .setSmallIcon(R.drawable.ic_notify_status)
        .setChannelId(CHANNEL_ID)
        .build();  

올바른 코드는 다음과 같습니다.

Notification.Builder notification=new Notification.Builder(this)

종속성 26.0.1 및 28.0.0과 같은 새로 업데이트된 종속성을 사용합니다.

일부 사용자는 다음과 같은 형식으로 이 코드를 사용합니다.

Notification notification=new NotificationCompat.Builder(this)//this is also wrong code.

따라서 논리적으로는 어떤 메소드를 선언하거나 초기화할 것인지에 따라 오른쪽에 있는 동일한 메소드가 할당에 사용됩니다.=의 왼쪽에서 어떤 방법을 사용할 경우 =의 오른쪽에서도 동일한 방법이 새 할당에 사용됩니다.

이 코드를 사용해 보십시오...틀림없이 효과가 있을 것입니다.

  1. Notification_Channel_ID를 사용하여 Notification 채널을 선언해야 합니다.
  2. 해당 채널 ID로 알림을 빌드합니다.예를들면,

...
 public static final String NOTIFICATION_CHANNEL_ID = MyLocationService.class.getSimpleName();
...
...
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
                NOTIFICATION_CHANNEL_ID+"_name",
                NotificationManager.IMPORTANCE_HIGH);

NotificationManager notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

notifManager.createNotificationChannel(channel);


NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                .setContentTitle(getString(R.string.app_name))
                .setContentText(getString(R.string.notification_text))
                .setOngoing(true)
                .setContentIntent(broadcastIntent)
                .setSmallIcon(R.drawable.ic_tracker)
                .setPriority(PRIORITY_HIGH)
                .setCategory(Notification.CATEGORY_SERVICE);

        startForeground(1, builder.build());
...

이 생성자는 API 수준 26.1.0에서 더 이상 사용되지 않습니다. use NotificationCompat.대신 작성자(컨텍스트, 문자열)를 입력합니다.게시된 모든 알림은 알림 채널 ID를 지정해야 합니다.

안드로이드 api 레벨 < 26 또는 api 레벨 > = 26에 대한 알림을 표시할 수 있는 코드를 구축합니다.

  private void showNotifcation(String title, String body) {
        //Este método muestra notificaciones compatibles con Android Api Level < 26 o >=26
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //Mostrar notificacion en Android Api level >=26
            final String CHANNEL_ID = "HEADS_UP_NOTIFICATIONS";
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "MyNotification",
                    NotificationManager.IMPORTANCE_HIGH);

            getSystemService(NotificationManager.class).createNotificationChannel(channel);
            Notification.Builder notification = new Notification.Builder(this, CHANNEL_ID)
                    .setContentTitle(title)
                    .setContentText(body)
                    .setSmallIcon(R.drawable.ic_launcher_background)
                    .setAutoCancel(true);
            NotificationManagerCompat.from(this).notify(1, notification.build());

        }else{
            //Mostrar notificación para Android Api Level Menor a 26
            String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                    .setContentTitle(title)
                    .setContentText(body)
                    .setSmallIcon(R.drawable.ic_launcher_background)
                    .setAutoCancel(true);

            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(/*notification id*/1, notificationBuilder.build());

        }

    }

건배!

언급URL : https://stackoverflow.com/questions/45462666/notificationcompat-builder-deprecated-in-android-o

반응형