当前位置:   article > 正文

Android 锁屏后Service服务保活(支持9.0)_android service锁屏运行

android service锁屏运行

最近遇到个问题:
后台Service启动正常启动后,锁屏状态下大概80秒左右Service就被暂停了(并没有被杀死),唤醒屏幕后就继续执行。网上搜了很多办法不好用知道看到一篇文章Service和Notification 给我提供了解决思路和解决办法。

解决思路:
Service启动时创建一条通知,与其绑定,这样锁屏或者后台Service都不会被暂停或杀死。

代码如下:
在Service的onCreate中创建NotificationChannel 并且与服务绑定。

	private NotificationManager notificationManager;
    private String notificationId = "serviceid";
    private String notificationName = "servicename";
    
	@Override
    public void onCreate() {
        super.onCreate();
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        //创建NotificationChannel
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            NotificationChannel channel = new NotificationChannel(notificationId, notificationName, NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
        }
        startForeground(1,getNotification());
    }

	private Notification getNotification() {
        Notification.Builder builder = new Notification.Builder(this)
                .setSmallIcon(R.mipmap.log)
                .setContentTitle("title")
                .setContentText("text");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId(notificationId);
        }
        Notification notification = builder.build();
        return notification;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

亲测有效!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/273022
推荐阅读
相关标签
  

闽ICP备14008679号