实用地启用我的后台服务通知

时间:2018-11-19 11:41:53

标签: android background-service

我有一个android应用程序,必须使用android o及以上版本的服务在后台运行,我知道后台服务已被系统杀死,因此我将 startForground 与正确的通知,但有时这些通知没有出现,可能是由于移动设置

所以,如果我们来自

  

设置->应用程序->我的应用程序名称->通知->我的后台服务和   服务

因此,我的问题是我该如何实用地启动或检查这些“我的后台服务和服务”。

1 个答案:

答案 0 :(得分:0)

从Android O,

我们需要为每个在后台到达的通知设置频道ID。

  

You can check latest firebase implementation here.

清单中需要添加

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

在您的消息服务类中,

 @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
     sendNotification(remoteMessage.getNotification().getBody());//Considering you have message in your body.
    }

private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, MainActivity.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());
    }