Android在手机的通知栏里会出现“XXX正在运行,触摸即可了解详情或停止应用”的消息如何处理

手机上莫名显示我们的app,“XXX正在运行,触摸即可了解详情或停止应用”,我去,这不是让用户知道我们在后台偷偷运行了,什么情况?排查后发现是如下代码导致:

startForeground(111, new Notification());

其实就是调用startForeground导致的,解决方法就是再开一个service将这个通知取消掉

stopForeground(true);
                    
                    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                    manager.cancel(111);
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
要实现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,并且应该取消之前设置的定时任务,以免浪费系统资源。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进击的代码家

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值