1、广播。在前台运行的应用如果使用Context.registerReceiver()注册请求接收通知,则仍可以在主线程中侦听CONNECTIVITY_CHANGE。
publicstaticfinalintMY_BACKGROUND_JOB=0;...publicstaticvoidscheduleJob(Contextcontext){JobSchedulerjs=(JobScheduler)context.getSystemService(Context.JOB_SCHEDULER_SERVICE);JobInfojob=newJobInfo.Builder(MY_BACKGROUND_JOB,newComponentName(context,MyJobService.class)).setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED).setRequiresCharging(true).build();js.schedule(job);}
满足条件时,启动JobService.;
使用GMSCore服务时, Android 5.0 (API level 21)以下用户, 使用GcmNetworkManager指定类型Task.NETWORK_STATE_UNMETERE
ConnectivityManager API提供了更加健全的方法,当指定的网络条件满足时,会发生一个回调。
NetworkRequest对象依据NetworkCapabilities定义回调参数。你可以使用NetworkRequest.Builder类创建NetworkRequest对象。使用registerNetworkCallback()把NetworkRequest对象传递给系统。当网络条件满足时,app会接收一个回调 执ConnectivityManager.NetworkCallback 中的onAvailable()方法。
app会持续接受回调,直到app退出或者调用 unregisterNetworkCallback().方法。
Android 7.0中扩展了JobInfo和JobParameters.
JobInfo.TriggerContentUri()
JobInfo.Builder.addTriggerContentUri()
publicstaticfinalintMY_BACKGROUND_JOB=0;...publicstaticvoidscheduleJob(Contextcontext){JobSchedulerjs=(JobScheduler)context.getSystemService(Context.JOB_SCHEDULER_SERVICE);JobInfo.Builderbuilder=newJobInfo.Builder(MY_BACKGROUND_JOB,newComponentName(context,MediaContentJob.class));builder.addTriggerContentUri(newJobInfo.TriggerContentUri(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS));js.schedule(builder.build());} 当条件发生时,
MediaContentJob.onStartJob();When the system reports a change in the specified content URI(s), your app receives a callback and aobject is passed to themethod inMediaContentJob
The following sample code overrides the
@OverridepublicbooleanonStartJob(JobParametersparams){StringBuildersb=newStringBuilder();sb.append("Media content has changed:\n");if(params.getTriggeredContentAuthorities()!=null){sb.append("Authorities: ");booleanfirst=true;for(Stringauth:params.getTriggeredContentAuthorities()){if(first){first=false;}else{sb.append(", ");}sb.append(auth);}if(params.getTriggeredContentUris()!=null){for(Uriuri:params.getTriggeredContentUris()){sb.append("\n");sb.append(uri);}}}else{sb.append("(No content)");}Log.i(TAG,sb.toString());returntrue;}
优化你的app在低内存设备或者低内存条件下运行,可以改善性能和用户体验。删除掉后台的service以及静态隐性注册广播接收者能够使你的app在这些设备上更好的运行。Android 7.0 (API level 24) 正在逐渐减少这些问题。推荐优化你的app完全不要使用这些后台进程。
Android 7.0 (API level 24) 有一些额外的 Android Debug Bridge (ADB) 命令,你可以使用这些命令在不使用后台进程情况下测试app的行为。 模拟隐性的广播和后台服务不可用,使用下面的命令:
1
1$ adb shell cmd appops set RUN_IN_BACKGROUND ignore
为了使隐性的广播和后台服务再次可用,使用下面的命令:
$ adb shell cmd appops set RUN_IN_BACKGROUND allow