Android版本8.1,startForeground的错误通知

时间:2018-10-18 06:46:31

标签: java android firebase push-notification

我已经花了几天时间来解决这个问题。我的应用程序崩溃了,Android版本为8.1。在Android 8.0版中,它运行正常。

我遵循了下面提到的解决方案链接,并尝试了该链接中提供的许多解决方案,但我的应用程序未打开。

startForeground fail after upgrade to Android 8.1

我在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));
        }

帮助我解决此问题。

2 个答案:

答案 0 :(得分:1)

您可以将其用于Oreo及更高版本

如果您使用服务类,则可以输入此代码

public class BlablaService extends Service 

    @Override
    public void onCreate(){
        super.onCreate();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
            startMyOwnForeground();
        else
            startForeground(1, new Notification());
    }

    private void startMyOwnForeground(){
        String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
        String channelName = "My Background Service";
        NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        Notification notification = notificationBuilder.setOngoing(true)
                .setSmallIcon(R.drawable.icon_1)
                .setContentTitle("App is running in background")
                .setPriority(NotificationManager.IMPORTANCE_MIN)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();
        startForeground(2, notification);
    } 

当然不要忘记您的AndroidManifest.xml的ForeGroundService权限

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

答案 1 :(得分:0)

将您的逻辑放入onMessageReceived :选中Firebase quickstart sample.

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());
}