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