繁体   English   中英

Android 前台服务通知未显示

[英]Android foreground service notification not showing

我正在尝试启动前台服务。 我收到服务确实启动的通知,但通知总是被抑制。 我仔细检查了该应用程序是否允许在我设备上的应用程序信息中显示通知。 这是我的代码:

private void showNotification() {
    Intent notificationIntent = new Intent(this, MainActivity.class);
    notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
            | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
            notificationIntent, 0);

    Bitmap icon = BitmapFactory.decodeResource(getResources(),
            R.mipmap.ic_launcher);

    Notification notification = new NotificationCompat.Builder(getApplicationContext())
            .setContentTitle("Revel Is Running")
            .setTicker("Revel Is Running")
            .setContentText("Click to stop")
            .setSmallIcon(R.mipmap.ic_launcher)
            //.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
            .setContentIntent(pendingIntent)
            .setOngoing(true).build();
    startForeground(Constants.FOREGROUND_SERVICE,
            notification);
    Log.e(TAG,"notification shown");

}

这是我看到的唯一相关错误: 06-20 12:26:43.635 895-930/? E/NotificationService: Suppressing notification from the package by user request. 06-20 12:26:43.635 895-930/? E/NotificationService: Suppressing notification from the package by user request.

这是因为Android O bg服务的限制。

所以,现在你需要调用startForeground()仅适用于被启动与服务startForegroundService()和服务已启动后调用它前5秒。

这是指南 - https://developer.android.com/about/versions/oreo/background#services

像这样:

//Start service:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  startForegroundService(new Intent(this, YourService.class));
} else {
  startService(new Intent(this, YourService.class));
}

然后创建并显示通知(使用前面假设的频道):

private void createAndShowForegroundNotification(Service yourService, int notificationId) {

    final NotificationCompat.Builder builder = getNotificationBuilder(yourService,
         "com.example.your_app.notification.CHANNEL_ID_FOREGROUND", // Channel id
    NotificationManagerCompat.IMPORTANCE_LOW); //Low importance prevent visual appearance for this notification channel on top 
    builder.setOngoing(true)
    .setSmallIcon(R.drawable.small_icon)
    .setContentTitle(yourService.getString(R.string.title))
    .setContentText(yourService.getString(R.string.content));

    Notification notification = builder.build();

    yourService.startForeground(notificationId, notification);

    if (notificationId != lastShownNotificationId) {
          // Cancel previous notification
          final NotificationManager nm = (NotificationManager) yourService.getSystemService(Activity.NOTIFICATION_SERVICE);
          nm.cancel(lastShownNotificationId);
    }
    lastShownNotificationId = notificationId;
}

public static NotificationCompat.Builder getNotificationBuilder(Context context, String channelId, int importance) {
    NotificationCompat.Builder builder;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        prepareChannel(context, channelId, importance);
        builder = new NotificationCompat.Builder(context, channelId);
    } else {
        builder = new NotificationCompat.Builder(context);
    }
    return builder;
}

@TargetApi(26)
private static void prepareChannel(Context context, String id, int importance) {
    final String appName = context.getString(R.string.app_name);
    String description = context.getString(R.string.notifications_channel_description);
    final NotificationManager nm = (NotificationManager) context.getSystemService(Activity.NOTIFICATION_SERVICE);

    if(nm != null) {
        NotificationChannel nChannel = nm.getNotificationChannel(id);

        if (nChannel == null) {
            nChannel = new NotificationChannel(id, appName, importance);
            nChannel.setDescription(description);
            nm.createNotificationChannel(nChannel);
        }
    }
}

请记住,即使您使用不同的频道ID,您的前景通知也会与其他通知具有相同的状态,因此它可能会与其他人一起隐藏。 使用不同的组来避免它。

问题是我使用的是Android O,它需要更多信息。 这是android O的成功代码。

    mNotifyManager = (NotificationManager) mActivity.getSystemService(Context.NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) createChannel(mNotifyManager);
    mBuilder = new NotificationCompat.Builder(mActivity, "YOUR_TEXT_HERE").setSmallIcon(android.R.drawable.stat_sys_download).setColor
            (ContextCompat.getColor(mActivity, R.color.colorNotification)).setContentTitle(YOUR_TITLE_HERE).setContentText(YOUR_DESCRIPTION_HERE);
    mNotifyManager.notify(mFile.getId().hashCode(), mBuilder.build());

@TargetApi(26)
private void createChannel(NotificationManager notificationManager) {
    String name = "FileDownload";
    String description = "Notifications for download status";
    int importance = NotificationManager.IMPORTANCE_DEFAULT;

    NotificationChannel mChannel = new NotificationChannel(name, name, importance);
    mChannel.setDescription(description);
    mChannel.enableLights(true);
    mChannel.setLightColor(Color.BLUE);
    notificationManager.createNotificationChannel(mChannel);
}

如果以上都不起作用,您应该检查您的通知ID是否为0 ...惊喜!! 它不能是0。

非常感谢@Luka Kama的这篇文章

startForeground(0, notification); // Doesn't work...

startForeground(1, notification); // Works!!!

如果你的目标是Android 9(Pie)api等级28且高于你应该在清单文件中给予FOREGROUND_SERVICE权限。请看这个链接: https//developer.android.com/about/versions/pie/android-9.0-migration#博鳌亚洲论坛

我不相信。 就我而言,在将“android:name=".App"”添加到 AndroidManifest.xml 后,通知开始显示。 例子:

    <application
    android:name=".App"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"

对我来说,一切都设置正确(还为清单添加了FOREGROUND_SERVICE权限),但我只需要卸载应用程序并重新安装它。

对于Android API 级别 33+ ,您需要请求POST_NOTIFICATIONS 运行时权限 虽然这不会阻止前台服务运行,但仍然必须像我们对< API 33所做的那样进行通知:

注意:应用无需请求 POST_NOTIFICATIONS 权限即可启动前台服务。 但是,应用程序在启动前台服务时必须包含通知,就像它们在 Android 的早期版本中所做的那样。

Android 文档中查看更多信息。

就我而言,它是由我使用IntentService引起的。

简而言之,如果你想要一个前台服务,那么继承Service

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM