ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Android8.0+ 没有后台Service了,怎么办?

2020-11-26 19:30:14  阅读:263  来源: 互联网

标签:NotificationManager service Service Android8.0 后台 new Android onCreate public


今天用传统方式,直接在Android 10上直接调用startService方法启动service服务,没有多久就报ANR。如果手机熄灭的状态下,打调试包,控制台会报以下错误:
Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com.wong.testphone/.socket.MinaService }: app is in background uid UidRecord{9cd1107 u0a341 TPSL idle change:idle|cached procs:1 seq(0,0,0)}
 
Android 8.0+ 对特定函数做出了以下变更:

如果针对Android 8.0+的应用不允许创建后台服务,如果使用 startService() 函数,则引发 IllegalStateException异常。解决的办法是使用新的Context.startForegroundService() 函数将启动一个前台服务,并且service必须在创建服务后的五秒内调用该服务的 startForeground() 函数,否则将会报错。

解决示例:

Step 1:使用startForegroundService启动服务

public class MainActivity extends AppCompatActivity {
@Override
    public void onCreate() {
        super.onCreate();
        Intent intent = new Intent(getApplicationContext(), MinaService.class);
        if (Build.VERSION.SDK_INT >= 26) {
            startForegroundService(intent);
        } else {
            // Pre-O behavior.
            startService(intent);
        }
    }
...
}

Step 2:在service中5秒内必须调用startForeground

public class MinaService extends Service {

    private ConnectionThread thread;

    @Override
    public void onCreate() {
        super.onCreate();
        //全局context 避免内存泄漏,不多说
        thread = new ConnectionThread("mina", getApplicationContext());
        if (Build.VERSION.SDK_INT >= 26) {
        	NotificationChannel channel = new NotificationChannel(CHANNEL_ID,CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
        	NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        	manager.createNotificationChannel(channel);
	        Notification notification = new Notification.Builder(getApplicationContext(),CHANNEL_ID).build();
    	    startForeground(1, notification);
        }

    }
    ...
}

标签:NotificationManager,service,Service,Android8.0,后台,new,Android,onCreate,public
来源: https://blog.csdn.net/weixin_40763897/article/details/110201016

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有