首页 > 解决方案 > Android前台通知消失

问题描述

我有一个问题,我的应用程序在哪里运行前台服务。前台服务通知将有一个播放或暂停选项,单击将启动或停止相应的服务(通知是其中的一部分)。在停止选项上单击服务将停止并在播放选项上重新启动单击通知。

在 MyService.java 中生成通知

RemoteViews remoteViews = new RemoteViews(getPackageName(),
            R.layout.loyout_notification);
remoteViews.setTextViewText(R.id.notification_title, NOTIFOCATION_CONTENT_TITLE);

    if (MYMUtility.myServiceRunning(MyService.class, this)) {
        remoteViews.setImageViewResource(R.id.notification_play_or_stop, R.drawable.ic_stop);
    } else {
         remoteViews.setImageViewResource(R.id.notification_play_or_stop, R.drawable.ic_play);
    }

    Intent notificationBroadcastIntent = new Intent(this, MyService.class);
    PendingIntent playIntent = PendingIntent.getBroadcast(this, 0, notificationBroadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    remoteViews.setOnClickPendingIntent(R.id.notification_play_or_stop, playIntent);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID).setOngoing(true)
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentTitle(NOTIFOCATION_CONTENT_TITLE)
            .setPriority(NotificationManager.IMPORTANCE_MIN)
            .setCategory(Notification.CATEGORY_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

    notificationBuilder.setContentIntent(contentIntent);
    notificationBuilder.setContent(remoteViews);
    Notification notification = notificationBuilder.build();

    startForeground(FOREGROUND_ID_FOR_NOTIFICATION, notification);

在 Myservice 被销毁时,通知仍将保留

@Override
public void onDestroy() {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        stopForeground(Service.STOP_FOREGROUND_DETACH);
    } else {
        stopForeground(false);
    }
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.build();
mNotificationManager.notify(FOREGROUND_ID_FOR_NOTIFICATION, notification);
    stopSelf();

    super.onDestroy();

}

广播接收器如下

public void onReceive(Context context, Intent intent) {
    if (MYMUtility.isMyServiceRunning(Myservice.class, context)) {
        context.stopService(new Intent(context, Myservice.class));
    } else {
        context.startService(new Intent(context, Myservice.class));
    }
}

我目前面临的问题是在通知上启动和停止服务。

A)当应用程序启动时,服务启动。因此单击通知上的停止选项将停止服务而不关闭通知。

B)单击通知上的播放选项时,将启动服务(如接收器上的预期)但通知消失

奇怪的是,如果我使用断点进行调试,那么通知不会在服务重启时消失(点击通知播放选项),但当我只是在模拟器上运行应用程序时它会消失(没有调试)。

有人可以帮我解决这个问题吗?

标签: androidandroid-serviceandroid-notifications

解决方案


推荐阅读