android通知栏被进程杀死,Android 应用被杀后Notification不取消问题及应用深杀和浅杀时Service生命周期情况...

项目中有如下需求:后台service进行导入操作,要更新Notification。当运行系统清理使应用被杀时,Notification无法取消,仍然在通知栏显示。为解决这个问题进行了如下探索:

首先想到利用service的startForeground()来更新通知栏,这样当应用被杀掉时候Notification可以一起被去掉。但针对项目的需求:service可以同时导入多个文件,并且会对应显示多个通知。这种情况下用service.startForeground()更新通知栏时候,当应用被杀时候之后cancel掉最后一次调用startForeground对应id的Notification,而其他通知仍然不能被取消。

继续探索用其他方式取消通知栏:在进程被杀掉的时候,会调用service的哪些生命周期函数呢?service的onDestroy()方法只有在调用Context的stopService()或Service的stopSelf()后才会被调用,在应用被杀时候Service的onDestroy()不会被执行。

我们发现service的 onTaskRemoved()方法,该方法何时被调用呢?方法的注释说明是这么写的:

/**

* This is called if the service is currently running and the user has

* removed a task that comes from the service's application. If you have

* set {@linkandroid.content.pm.ServiceInfo#FLAG_STOP_WITH_TASK ServiceInfo.FLAG_STOP_WITH_TASK}

* then you will not receive this callback; instead, the service will simply

* be stopped.

*

*@paramrootIntentThe original root Intent that was used to launch

* the task that is being removed.

*/

public voidonTaskRemoved(Intent rootIntent) {

}

注释表明onTaskRemoved()方法在当用户移除应用的一个Task栈时被调用。也就是当用户在最近任务界面把该应用的一个task划掉时&#

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现Android Service常驻后台且应用杀死后仍能发送通知消息,可以按照以下步骤进行: 1. 在Service中通过startForeground()方法将Service设置为前台Service,同通知中显示一个通知。 2. 在Service中使用AlarmManager定发送通知消息,即使应用杀死也能够执行定任务,代码示例如下: ``` AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(this, NotificationService.class); PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 60 * 1000, pendingIntent); ``` 3. 创建一个NotificationService,用于接收AlarmManager发送的通知消息,代码示例如下: ``` public class NotificationService extends Service { private static final int NOTIFICATION_ID = 1; @Override public int onStartCommand(Intent intent, int flags, int startId) { showNotification(); return super.onStartCommand(intent, flags, startId); } private void showNotification() { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification.Builder(this) .setContentTitle("这是通知标题") .setContentText("这是通知内容") .setSmallIcon(R.mipmap.ic_launcher) .setAutoCancel(true) .build(); notificationManager.notify(NOTIFICATION_ID, notification); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } } ``` 需要注意的是,AlarmManager定发送通知消息的间间隔应该根据实际需求进行调整。同,如果不再需要Service常驻后台,应该通过stopForeground(true)方法将其设置为普通Service,并且应该取消之前设置的定任务,以免浪费系统资源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值