我最近将我的所有服务都替换为前台服务和JobIntentService,因为在oreo及以上版本中有一些后台执行限制(https://developer.android.com/about/versions/oreo/background).根据文档,JobIntentService的行为类似于Android 7及以下版本的Intent Service,其作用类似于Android 8及以上版本的JobScheduler.我注意到Google提供的新JobIntentService存在问题.
Android 8及以上版本:
在Android 8及更高版本中连续发生崩溃.这里有一张提到同样问题的门票https://issuetracker.google.com/issues/63622293,我添加了一些极客建议的临时修复程序.
Android 7及以下版本: JobIntentService就像Intent Service一样,一旦完成工作就不会停止.
我在服务中实现了JobIntentService,只要用户执行某些操作就会触发该服务.
码
public class SampleJobIntentService extends FixedJobIntentService {
public static void postData(Context context, String data) {
Intent intent = new Intent(context, SampleJobIntentService.class);
intent.setAction(INITIAL_ACTION);
intent.putExtra(SAMPLE_ID, data);
SampleJobIntentService.enqueueWork(context,intent);
}
public static void enqueueWork(Context context, Intent work) {
SampleJobIntentService.enqueueWork(context, SampleJobIntentService.class, JOB_ID, work);
@Override
protected void onHandleWork(@NonNull Intent intent) {
if (intent != null) {
SampleRequest sampleRequest = requests.get(intent.getAction());
if (sampleRequest != null) {
try {
// perform …Run Code Online (Sandbox Code Playgroud)