后台优化(Background optimizations)

Background processes can be memory- and battery-intensive. For example, an implicit broadcast may start many background processes that have registered to listen for it, even if those processes may not do much work. This can have a substantial impact on both device performance and user experience.

翻译:后台任务对内存和电池比较敏感.例如,隐式广播可能开启大量后台任务。这回对系统性能和用户体验造成巨大影响

 

To alleviate this issue, Android 7.0 (API level 24) applies the following restrictions:

为了减轻这个问题, Andorid 7.0加了如下限制

CONNECTIVITY_ACTION  这个广播在Android 7.0以后只能动态监听

  • Apps cannot send or receive ACTION_NEW_PICTURE or ACTION_NEW_VIDEO broadcasts. This optimization affects all apps, not only those targeting Android 7.0 (API level 24).

应用不能在发送或者接受ACTION_NEW_PICTURE   ACTION_NEW_VIDEO  这两个广播 。这个影响所有应用,而不只是targeting Andoroid 7.0

 

If your app uses any of these intents, you should remove dependencies on them as soon as possible so that you can properly target devices running Android 7.0 or higher.

如果用上面几个intent的,取消之。

The Android framework provides several solutions to mitigate the need for these implicit broadcasts.

AndroidFrameWork有替代方案

For example, JobScheduler and the new WorkManager provide robust mechanisms to schedule network operations when specified conditions, such as a connection to an unmetered network, are met.

例如 JobScheduler 以及 WorkManager 提供了稳健的机制。。。。

You can now also use JobScheduler to react to changes to content providers. 

JobScheduler 也可以对content provider有反应

JobInfo objects encapsulate the parameters that JobScheduler uses to schedule your job. When the conditions of the job are met, the system executes this job on your app's JobService.

JobInfo 集齐了 JobScheduler需要的参数。 当条件满足的时候,系统在你的JobService里面执行任务

 

In this document, we will learn how to use alternative methods, such as JobScheduler, to adapt your app to these new restrictions.

这边文档教你如何使用替代方案

 

User-initiated restrictions 

用户发起的限制

Beginning in Android 9 (API level 28), if an app exhibits some of the bad behaviors described in Android vitals, the system prompts the user to restrict that app's access to system resources.

android 9.0后,如果用户作恶,系统会提醒用户限制app

 

If the system notices that an app is consuming excessive resources, it notifies the user, and gives the user the option of restricting the app's actions. Behaviors that can trigger the notice include

如果系统发现app消耗过多资源,他会系统用户,给用户限制app行为的选项,如下行为会触发提醒

 

  • Excessive wake locks: 1 partial wake lock held for an hour when screen is off

过多的wake locks (一个wake lock超过一个小时)

  • Excessive background services: If app targets API levels lower than 26 and has excessive background services

过多的后台任务(target低于26)

 

The precise restrictions imposed are determined by the device manufacturer. For example, on AOSP builds, restricted apps cannot run jobs, trigger alarms, or use the network, except when the app is in the foreground. (For the criteria used to determine if an app is in the foreground, see Background Service Limitations.) The specific restrictions are listed inPower management restrictions.

具体限制取决于设备生产商,例如 AOSP builds 里,被限制的app不能run job是不能trigger alarms 不能联网,除非在前台。

详情见上。。。。。

 

Restrictions on receiving network activity broadcasts

Apps targeting Android 7.0 (API level 24) do not receive CONNECTIVITY_ACTION broadcasts if they register to receive them in their manifest, and processes that depend on this broadcast will not start. This could pose a problem for apps that want to listen for network changes or perform bulk network activities when the device connects to an unmetered network. Several solutions to get around this restriction already exist in the Android framework, but choosing the right one depends on what you want your app to accomplish.

Note: A BroadcastReceiver registered with Context.registerReceiver() continues to receive these broadcasts while the app is running.

andorid 7.0后不再接受CONNECTIVITY_ACTION broadcasts(清单文件注册)。

但是Andoriod Framework里面已经有了解决方案。用哪个取决于你的需求。

注意,动态注册的广播接收器任然能接受这个广播

 

Schedule network jobs on unmetered connections 

在unmetered connection上做网络任务

When using the JobInfo.Builder class to build your JobInfo object, apply the setRequiredNetworkType() method and pass JobInfo.NETWORK_TYPE_UNMETERED as a job parameter. The following code sample schedules a service to run when the device connects to an unmetered network and is charging:

翻译:使用JobInfo.Builder 类来build JobInfo时,使用 setRequiredNetworkType方法并且传入JobInfo.NETWORK_TYPE_UNMETERED 作为参数,下文示例schedule了一个service (在充电,并且连到了一个非计费网络)

public static final int MY_BACKGROUND_JOB = 0;
...
public static void scheduleJob(Context context) {
  JobScheduler js =
      (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
  JobInfo job = new JobInfo.Builder(
    MY_BACKGROUND_JOB,
    new ComponentName(context, MyJobService.class))
      .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
      .setRequiresCharging(true)
      .build();
  js.schedule(job);
}

When the conditions for your job are met, your app receives a callback to run the onStartJob() method in the specified JobService.class. To see more examples of JobScheduler implementation, see the JobScheduler sample app.

条件满足,则回调到 onStartJob. 参考JobScheduler sample app.

 

A new alternative to JobScheduler is WorkManager, an API that allows you to schedule background tasks that need guaranteed completion, regardless of whether the app process is around or not. WorkManager chooses the appropriate way to run the work (either directly on a thread in your app process as well as using JobScheduler, FirebaseJobDispatcher, or AlarmManager) based on such factors as the device API level. Additionally, WorkManager does not require Play services and provides several advanced features, such as chaining tasks together or checking a task's status. To learn more, see WorkManager.

翻译:JobSchedular的可选方案是WorkManager。WorkManger选择合适的方式来run the work (根据比如API leve 这些因素等来选). 另外,WorkManger 不需要 Play service 并且提供了一些高级功能。 参考:WorkManager

 

Monitor network connectivity while the app is running 

在app运行的时候监控网络连接

Apps that are running can still listen for CONNECTIVITY_CHANGE with a registered BroadcastReceiver. However, the ConnectivityManager API provides a more robust method to request a callback only when specified network conditions are met.

CONNECTIVITY_CHANGE  在动态注册的BroadcastReciver这里还能用,然而 ConnectivityManager API 提供了更加robust 的方案。

 

NetworkRequest objects define the parameters of the network callback in terms of NetworkCapabilities. You create NetworkRequest objects with the NetworkRequest.Builder class. registerNetworkCallback() then passes the NetworkRequest object to the system. When the network conditions are met, the app receives a callback to execute theonAvailable() method defined in its ConnectivityManager.NetworkCallback class.

The app continues to receive callbacks until either the app exits or it calls unregisterNetworkCallback().

翻译:NetworkRequest 对象定义了网络能力的参数,用NetworkRequest.Builder类创建一个NetworkRequest对象,注册对象给系统,当网络环境变化时,在onAvailable方法会收到一个回调

app持续接收回调直到unregisterNetworkCallback()或者app退出。

 

Restrictions on receiving image and video broadcasts 

接收图片和视频变化的广播

 

In Android 7.0 (API level 24), apps are not able to send or receive ACTION_NEW_PICTURE or ACTION_NEW_VIDEObroadcasts. This restriction helps alleviate the performance and user experience impacts when several apps must wake up in order to process a new image or video. Android 7.0 (API level 24) extends JobInfo and JobParameters to provide an alternative solution.

Android 7.0 app不能发送和接收 ACTION_NEW_PICTURE or ACTION_NEW_VIDEObroadcasts。这能提升用户体验。

Android 7.0 继承 JobInfo 以及JobParameter 来提供可选解决方案。

 

Trigger jobs on content URI changes 

在content URI 变化时trigger jobs

To trigger jobs on content URI changes, Android 7.0 (API level 24) extends the JobInfo API with the following methods:

android 7.0 扩展了JobInfo 的如下方法

JobInfo.TriggerContentUri()

Encapsulates parameters required to trigger a job on content URI changes.

contenetUri change 时候的封装参数

 

JobInfo.Builder.addTriggerContentUri()

Passes a TriggerContentUri object to JobInfo. A ContentObserver monitors the encapsulated content URI. If there are multiple TriggerContentUri objects associated with a job, the system provides a callback even if it reports a change in only one of the content URIs.

翻译:传递一个 TriggerContentUri 对象给JobInfo .一个ContentObserver 监控着封装内容URI,如果有多个TriggerContentUri对象。则即便只有一个Content URI 变化,系统仍然提供回调

 

Add the TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS flag to trigger the job if any descendants of the given URI change. This flag corresponds to the notifyForDescendants parameter passed to registerContentObserver().

 

Note: TriggerContentUri() cannot be used in combination with setPeriodic() or setPersisted(). To continually monitor for content changes, schedule a new JobInfo before the app’s JobService finishes handling the most recent callback.

注意: TriggerContentUri() 不能和setPeriodic 以及 setPersisted一块使用。

 

The following sample code schedules a job to trigger when the system reports a change to the content URI, MEDIA_URI:

举例:

public static final int MY_BACKGROUND_JOB = 0;
...
public static void scheduleJob(Context context) {
  JobScheduler js =
          (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
  JobInfo.Builder builder = new JobInfo.Builder(
          MY_BACKGROUND_JOB,
          new ComponentName(context, MediaContentJob.class));
  builder.addTriggerContentUri(
          new JobInfo.TriggerContentUri(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
          JobInfo.TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS));
  js.schedule(builder.build());
}

When the system reports a change in the specified content URI(s), your app receives a callback and a JobParametersobject is passed to the onStartJob() method in MediaContentJob.class.

翻译:the specified content URI(s)变化的时候,你的app就会收到JobParameter对象。

 

Determine which content authorities triggered a job 

确定触发job的内容权限

Android 7.0 (API level 24) also extends JobParameters to allow your app to receive useful information about what content authorities and URIs triggered the job:

Android 7.0也扩张了JobParameters来允许你的app接收用户信息

 

Uri[] getTriggeredContentUris()

Returns an array of URIs that have triggered the job. This will be null if either no URIs have triggered the job (for example, the job was triggered due to a deadline or some other reason), or the number of changed URIs is greater than 50.

String[] getTriggeredContentAuthorities()

Returns a string array of content authorities that have triggered the job. If the returned array is not null, use getTriggeredContentUris() to retrieve the details of which URIs have changed.

The following sample code overrides the JobService.onStartJob() method and records the content authorities and URIs that have triggered the job:

 

@Override
public boolean onStartJob(JobParameters params) {
  StringBuilder sb = new StringBuilder();
  sb.append("Media content has changed:\n");
  if (params.getTriggeredContentAuthorities() != null) {
      sb.append("Authorities: ");
      boolean first = true;
      for (String auth :
          params.getTriggeredContentAuthorities()) {
          if (first) {
              first = false;
          } else {
             sb.append(", ");
          }
           sb.append(auth);
      }
      if (params.getTriggeredContentUris() != null) {
          for (Uri uri : params.getTriggeredContentUris()) {
              sb.append("\n");
              sb.append(uri);
          }
      }
  } else {
      sb.append("(No content)");
  }
  Log.i(TAG, sb.toString());
  return true;
}

Further optimize your app 

进一步优化

Optimizing your apps to run on low-memory devices, or in low-memory conditions, can improve performance and user experience. Removing dependencies on background services and manifest-registered implicit broadcast receivers can help your app run better on such devices. Although Android 7.0 (API level 24) takes steps to reduce some of these issues, it is recommended that you optimize your app to run without the use of these background processes entirely.

翻译:最好完全不依赖后台任务

 

Android 7.0 (API level 24) introduces some additional Android Debug Bridge (ADB) commands that you can use to test app behavior with those background processes disabled:

Andorid 7.0 ADB 提供了更多命令

  • To simulate conditions where implicit broadcasts and background services are unavailable, enter the following command:

翻译:模拟隐式广播和后台任务unavailable

$ adb shell cmd appops set <package_name> RUN_IN_BACKGROUND ignore
  • To re-enable implicit broadcasts and background services, enter the following command:

翻译:使上面的重新enable

$ adb shell cmd appops set <package_name> RUN_IN_BACKGROUND allow

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值