Android 8.1,startForeground出现错误通知

3

我花了几天的时间来解决这个问题。我的应用程序在Android 8.1版本崩溃,但在Android 8.0版本中完美运行。

我按照下面提供的链接尝试了许多解决方案,但我的应用程序仍无法打开。

Android 8.1 升级后 startForeground 失败

我在 FirebaseMessageService 类中检查了 Android 版本并为 Oreo 版本创建了通道,但是每次都显示以下错误:

 android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x40 color=0x00000000 vis=PRIVATE)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:171)
        at android.app.ActivityThread.main(ActivityThread.java:6649)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)

以下是我的代码,请帮我纠正这个问题。
    public class MyFirebaseMessagingService extends FirebaseMessagingService
    {
        private NotificationManager notifManager;
        Context mContext;
        Random random = new Random();
        int m = random.nextInt(9999 - 1000) + 1000;

        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) 
        {
           sendNotification();
        }



   public void sendNotification()
   {
   Intent intent = new Intent(this, Home.class);
   intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
   PendingIntent pendingIntent = PendingIntent.getActivity(this, m /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);

   String channelId = getString(R.string.default_notification_channel_id);
   Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
   NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
                   .setSmallIcon(R.drawable.app_icon)
                   .setContentTitle("Logipace")
                   .setStyle(new NotificationCompat.BigTextStyle()
                           .bigText(message))
                   .setContentText(message)
                   .setAutoCancel(true)
                   .setSound(defaultSoundUri)
                   .setContentIntent(pendingIntent);
   notificationBuilder.setDefaults(Notification.DEFAULT_SOUND);

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

    // Since android Oreo notification channel is needed.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
    {
        NotificationChannel channel = new NotificationChannel(channelId, "LOGIPACE", NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(channel);
    }

    notificationManager.notify(m /* ID of notification */, notificationBuilder.build());

    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(intent);
}
    }

以下是我在Activity类的onCreate()方法中使用的代码。
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            // Create channel to show notifications.
            String channelId  = getString(R.string.default_notification_channel_id);
            String channelName = getString(R.string.default_notification_channel_name);
            NotificationManager notificationManager =
                    getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(new NotificationChannel(channelId,
                    channelName, NotificationManager.IMPORTANCE_LOW));
        }

帮我解决这个问题。


可能是Android 8.1升级后startForeground失败的重复问题。 - Khaled Lela
我解决了我的问题,我在我的位置跟踪类中使用了startForegroundService()方法。否则上面的代码完全正常运行。 - Dnveeraj
你能发送 'R.string.default_notification_channel_id' 的值吗? - Thamarai T
1个回答

0

将您的逻辑放在onMessageReceived:检查Firebase快速入门示例。

public void onMessageReceived(RemoteMessage remoteMessage) {
    // Handle data payload of FCM messages.
    Log.d(TAG, "From: " + remoteMessage.getFrom());
    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        Map<String, String> params = remoteMessage.getData();
        JSONObject object = new JSONObject(params);
        if (/* Check if data needs to be processed by long running job */ true) {
            // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
            scheduleJob();
        } else {
            // Handle message within 10 seconds
            final String msg = object.getString("msg");
            sendNotification(msg);
            handleNow();
        }

    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }
}

private void sendNotification(String messageBody) {
    Intent intent = new Intent(this, Home.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    String channelId = getString(R.string.default_notification_channel_id);
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(R.drawable.ic_stat_ic_notification)
                    .setContentTitle(getString(R.string.fcm_message))
                    .setContentText(messageBody)
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);

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

    // Since android Oreo notification channel is needed.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(channel);
    }
    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

我创建了自己的频道,同时我正在检查版本。代码与我看到的 @Khaled Lela 相同。 - Dnveeraj
我在我的问题中提到了同样的链接,我参考此链接以获得解决方案。 - Dnveeraj
Android O及以上版本创建NotificationChannel,否则使用builder即可,在此情况下无需使用startForground()。请查看并反馈。 - Khaled Lela
好的,我会移除startForeground(),我也看到了你上面编辑过的答案,我会应用它并告诉你。 - Dnveeraj
我测试了相同的代码,它在我的设备上可以运行,请更新你的问题并提供logcat崩溃日志。 - Khaled Lela
显示剩余8条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接