Bg Jobs

2017/08/28

Best Practices for Background Jobs

1 Background Operations

  1. Perform tasks at bg
  2. Case: a photo-ablum app optimizes its storage by compressing its photos beyond user interactivity.

1.1 Scheduled Jobs

  1. Scheduled Jobs
  2. Specify many circumstances
  3. For example, refresh cached data, specify job to run when sufficient power (no low battery) and an unmetered network (no waste data allotment). Start the job at the appropriate time.

1.2 Services

  1. Fg service is noticeable by the user.
  2. Bg service is not noticed by the user but do something silently and for a brief duration.

1.3 Broadcasts

  1. It’s dangerous that serveral apps respond to the same broadcast.(API26+ reason)
  2. Register explicit or implicit broadcasts.

1.4 Alarms

  1. AlarmManager to start apps at a specific time.
  2. Perform an operation at a specified interval, or under particular conditions to use a scheduled job.

2 Running in a Background Service

  1. UI performance and responsiveness by sending work to a service.
  2. UI Thread operations.
  3. Off-load operations onto a separate thread that runs in the bg. IntentService

2.1 Creating a Background Service

  1. Create an IntentService.
  2. The IntentService provides a structure for (long-)running an operation on other bg thread.
  3. IntentService isn’t affected by most UI lifecycle events, so it continues to run in circumstances that would shut down an AsyncTask.
  4. A few limitations:
    • It can’t interact directly with UI. Send the results to an Activity.
    • Work requests run sequentially (one by one).
    • Can’t be interrupted.
  5. Overide onHandleIntent(), and define IntentService in manifest file.

2.2.1 Create an IntentService

  1. Create an named RSSPullService class that extends IntentService.
  2. Overide onHandleIntent() and handle data.

2.2.2 Define the IntentService in the Manifest

  1. <service android:name=".RSSPullService" android:exported="false" />
  2. <service> doesn’t contain an intent filter. 只能有唯一组件访问这个Service。

2.2 Sending Work Requests to the Background Service

  1. Send work requests to an IntentService.

2.2.1 Create and Send a Work Request to an IntentService

  1. Create an explicit Intent

     intent = new Intent(getActivity(), RSSPullService.class);
     intent.setData(Uri.parse(dataUrl));
    

2 Call getActivity.startService(intent);

2.3 Reporting Work Status

  1. Use an Intent and a LocalBrocastManager to communicate a work request status to the Activity that sent the request.
  2. The status of a work request.

2.3.1 Report Status From an IntentService

  1. Create an Intent that contains the status in ites extended data(action or URI).
  2. Send the Intent by calling LocalBroadcastManager.sendBroadcast().

      public static final String BROADCAST_ACTION = "com.example.android.threadsample.BROADCAST";
     // Defines the key for the status "extra" in an Intent
     public static final String EXTENDED_DATA_STATUS = "com.example.android.threadsample.STATUS";
     Intent localIntent = new Intent(BROADCAST_ACTION);
     localIntent.putExtra(EXTENDED_DATA_STATUS, status);
    	
     LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
    

2.3.2 Receive Status Broadcasts from an IntentService

  1. Create DownloadStateReceiver class that extends BroadcastReceiver.
  2. Implement the onReceive method to handle intents.
  3. Define the BroadcastReceiver and define filters for it match specific actions, categories and data.

     //Activity or Fragment
     IntentFilter statusIntentFilter = new IntentFilter(BROADCAST_ACTION);
     statusIntentFilter.addDataScheme("http");
    
  4. Register BroadcastReceiver and IntentFilter with the system.

     //Activity or Fragment
     DownloadStateReceiver receiver = new DownloadStateReceiver();
     LocalBroadcastManager.getInstance(this).registerReceiver(receiver, statusIntentFilter);
    	
    
  5. A single BroadcastReceiver handles many types of broadcast Intent object with action.
  6. Use a Notification to notify the user event happened in the bg while app was not visible.

3 Managing Device Awake State

  1. Repeat alarms and wake locks to run bg.
  2. Apps such as games or movie apps need keep the screen turned on.
  3. Apps need not the screen on but require the CPU to keep running until a critical operations finishes.

3.1 Keeping the Device Awake

  1. Keep the screen or CPU awake as needed, while minimizing the impact on battery life.
  2. Avoid draining the battery, an Android device that is left idle quickly falls asleep.
  3. Use the most lightweight approach possible to handle the cases.

3.1.1 Keep the Screen On

  1. getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); in an activity(only an activity, never in a service or other app compontent). Switch the screen to turn off.
  2. The advantage of the approach is that no require special permission, and the platform, no release unused res, unlike wake loacks.
  3. Other way: android:keepScreenOn="true"
  4. ClearFlags();

3.1.2 Keep the CPU On

  1. PowerManager system service feature called wake locks.
  2. Creating and holding wake locks can have a dramatic impact on device’s battery life.
  3. A bg service grabs a wake lock to keep the CPU running to do work while the screen is off.
  4. <uses-permission android:name="android.permission.WAKE_LOCK" />
  5. WakefullBroadcastReceiver or other way :

     PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
     WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");
     wakeLock.acquire();
    	
     //release
     wakeLock.release();
    
  6. Using WakefulBroadcastReceiver
    1. Use the receiver in conjunction with a service that manages the life cycle of a bg task.
    2. A special type of PARTIAL_WAKE_LOCK
    3. Create MyWakefullReceiver that extends WakefulBroadcastReceiver, and startWakefulService().
    4. MyIntentService extends IntentService, call MyWakefulReceiver.completeWakefulIntent() to release the wake lock.
    5. <receiver android:name=".MyWakefulReceiver" />

3.2 Scheduling Repeating Alarms

  1. Repeat alarms to schedule operations(发生在app生命周期之外).

3.2.1 Understand the Trade-offs

3.2.2 Set a Repeating Alarm

3.2.3 Cancel an Alarm

```
if (alarmMgr != null) {
	alarmMgr.cancel()
}
```

3.2.4 Start an Alarm When the Device Boots

  1. All alarms are canceled when a device shuts down.
  2. <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
  3. Implement a BroadcastReceiver to receiver the broadcast
  4. Add the receiver to manifest file with an intent filter that filters on the ACTION_BOOT_COMPLETED action.

文内导航