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

今天用传统方式,直接在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);
        }

    }
    ...
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值