android - 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)单击通知上的播放选项时,将启动服务(如接收器上的预期)但通知消失。
奇怪的是,如果我使用断点进行调试,那么通知不会在服务重启时消失(点击通知播放选项),但当我只是在模拟器上运行应用程序时它会消失(没有调试)。
有人可以帮我解决这个问题吗?
解决方案
推荐阅读
- python - 为什么你分配的初始值 p0 会在很大程度上影响拟合结果
- c# - C#:在文本框中查询多列
- oracle - 使用虚拟列的 Oracle 自动 LIST 分区不允许子表上的 REFERENCE 分区
- node.js - 如何在显示数据之前处理需要令牌的nodejs中的多个传入请求
- typescript - 泛型函数类型别名
- android - 本地数据持久化后如何处理 API 中的更新数据?
- ag-grid - ag-grid 主题自定义问题和 resolve-url-loader 失败
- java - 是否可以在另一个 JFrame 上显示一个类的图表?
- qt - 在另一个线程的槽中未接收到从线程发送带有 size_t 变量的信号
- r - 为什么 lm() 没有在 R 中显示一些输出?