首页 > 解决方案 > 务实地启用我的后台服务通知

问题描述

我有 android 应用程序,我必须使用 android o 及更高版本的服务在后台运行我知道后台服务被系统杀死,所以我正在使用startForground适当的通知,但有时这些通知不会出现,这可能是因为移动设置

所以如果我们从

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

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

标签: androidbackground-service

解决方案


从Android O,

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

您可以在此处查看最新的 firebase 实施。

在清单中需要添加

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

推荐阅读