Asynchronous Android读书笔记五Queuing Work with IntentService

  • Introducing ServiceandIntentService

    1. 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

    1. 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 

    2. a single worker thread is sufficient to handle the workload 

    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. 

    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);
    

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值