-
Introducing ServiceandIntentService
-
In this chapter, we will focus on the IntentService class, a special-purpose subclass of Servicethat makes it very easy to implement a task queue to process work on a single background thread.
-
-
Building responsive apps with IntentService
-
When work is submitted to an IntentService, it is queued for processing by a HandlerThread, and processed in order of submission.
If the user exits the app before the queued work is completely processed, the IntentService will continue working in the background. When the IntentService has no more work in its queue, it will stop itself to avoid consuming unnecessary resources.
public class MyIntentService extends IntentService { public MyIntentService() {
super("thread-name");、、
//naming the thread makes debugging and profiling much easier
protected void onHandleIntent(Intent intent) { // executes on the background HandlerThread.
}}
-
-
Returning results with PendingIntent
private void triggerIntentService(int primeToFind) {
PendingIntent pending = createPendingResult( REQUEST_CODE, new Intent(), 0);
Intent intent = new Intent(this, PrimesIntentService.class);intent.putExtra(PrimesIntentService.PARAM, primeToFind);intent.putExtra(
PrimesIntentService.PENDING_RESULT, pending);
startService(intent); }
To handle the result that will be returned when this Pending Intent is invoked, we need to implement onActivityResult in the Activity, and check for the result code:
protected void onActivityResult(int req, int res, Intent data) { if (req == REQUEST_CODE &&
res == PrimesIntentService.RESULT_CODE) { BigInteger result = (BigInteger)
data.getSerializableExtra(PrimesIntentService.RESULT); // ... update UI with the result
}
super.onActivityResult(requestCode, resultCode, data); }
-
Posting results as system notifications
private void notifyUser(int primeToFind, String result) { String msg = String.format(
"The %sth prime is %s", primeToFind, result); NotificationCompat.Builder builder =
new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.prime_notification_icon) .setContentTitle(getString(R.string.primes_app)) .setContentText(msg);
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(primeToFind, builder.build()); }
Here we're using NotificationCompat.Builder to build a notification that includesan icon, a title (just the name of our application), and a message containing the resultof the calculation.
To post a notification containing the result of our calculation, we just need to update onHandleIntent to invoke thenotifyUsermethod:
protected void onHandleIntent(Intent intent) { int n = intent.getIntExtra(PARAM, -1);
BigInteger prime = calculateNthPrime(n);
notifyUser(n, prime.toString());
}
-
Applications of IntentService
1.long-running task
A usecase that IntentService is ideally suited for is uploading data to remoteservers. An IntentService is a perfect fit because:
-
The upload usually must complete, even if the user leaves the application
-
A single upload at a time usually makes best use ofthe available connection,since bandwidth is often asymmetric (there is much smaller bandwidth forupload than download)
-
A single upload at a time gives us a better chance of completing each individual upload before losing our data connection
-
-
Reporting progress from IntentService
To report progress from an IntentService, we can use the same mechanisms thatwe use to send results—for example, sending PendingIntents containing progressinformation, or posting system notifications with progress updates.
We can also use some techniques that we'll cover in the next chapter: sendingmessages via Messenger, or broadcasting intents to registered receivers.
a use case that the Android development team anticipated and therefore made easy forus with the setProgress method of NotificationCompat.Builder:
Builder setProgress(int max, int progress, boolean indeterminate);
Asynchronous Android读书笔记五Queuing Work with IntentService
最新推荐文章于 2022-05-05 10:14:29 发布