IntentService 与ResultReceiver

简介:

from://http://lyzhanghai.iteye.com/blog/947504

在google的I/O大会中关于“Writing zippy Android apps”,有讲过用IntentService的问题,但是因为API文档中对IntentService描述不是很详细,所以很少人使用IntentService。

android.app.IntentService
“IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself
when it runs out of work. This 'work queue processor' pattern is commonly used to offload tasks
from an application's main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as
appropriate. All requests are handled on a single worker thread -- they may take as
long as necessary (and will not block the application's main loop), but only one request will be processed at a time.”

有很多种模式可以运用在RESTful Client(想要了解更多的RESTful Client的模式可以参见I/O大会Developing Android REST client applications,但是苦于没有具体demo可以参见),如果不是特别特别复杂的RESTful Web Service, 我们可以使用ResultReceiver 和 IntentService。
举个例子,你想从web service取一些数据:
1.    调用startService。
2.    service中开始操作处理,并且通过消息告诉activity处理已经开始。
3.    activity处理消息并且显示进度条
4.    service完成处理并且返回给activity需要的数据。
5.    activity处理数据。
6.    service通过消息告诉activity处理完成,并且kill掉自己。
7.    activity取得消息并且结束掉进度条。

activity代码:

Java代码  复制代码  收藏代码
  1. public class HomeActivity extends Activity implements ResultReceiver {   
  2.     public void onCreate(Bundle savedInstanceState) {   
  3.         ...   
  4.         final Intent intent = new Intent(Intent.ACTION_SYNC, null, this, QueryService.class);   
  5.         intent.putExtra("receiver", this);   
  6.         intent.putExtra("command", "query");   
  7.         startService(intent);   
  8.     }   
  9.   
  10.     public void onReceiveResult(int resultCode, Bundle resultData) {   
  11.         switch (resultCode) {   
  12.         case RUNNING:   
  13.             //show progress   
  14.             break;   
  15.         case FINISHED:   
  16.             List results = resultData.getParcelableList("results");   
  17.             // do something interesting   
  18.             // hide progress   
  19.             break;   
  20.         case ERROR:   
  21.             // handle the error;   
  22.             break;   
  23.     }   
  24. }  
public class HomeActivity extends Activity implements ResultReceiver {
    public void onCreate(Bundle savedInstanceState) {
        ...
        final Intent intent = new Intent(Intent.ACTION_SYNC, null, this, QueryService.class);
        intent.putExtra("receiver", this);
        intent.putExtra("command", "query");
        startService(intent);
    }

    public void onReceiveResult(int resultCode, Bundle resultData) {
        switch (resultCode) {
        case RUNNING:
            //show progress
            break;
        case FINISHED:
            List results = resultData.getParcelableList("results");
            // do something interesting
            // hide progress
            break;
        case ERROR:
            // handle the error;
            break;
    }
}

 service代码:

Java代码  复制代码  收藏代码
  1. public class QueryService extends IntentService {   
  2.     protected void onHandleIntent(Intent intent) {   
  3.         final ResultReceiver receiver = intent.getParcelableExtra("receiver");   
  4.         String command = intent.getStringExtra("command");   
  5.         Bundle b = new Bundle();   
  6.         if(command.equals("query") {   
  7.             receiver.send(STATUS_RUNNING, Bundle.EMPTY);   
  8.             try {   
  9.                 // get some data or something             
  10.                 b.putParcelableArrayList("results", results);   
  11.                 receiver.send(STATUS_FINISHED, b)   
  12.             } catch(Exception e) {   
  13.                 b.putString(Intent.EXTRA_TEXT, e.toString());   
  14.                 receiver.send(STATUS_ERROR, b);   
  15.             }       
  16.         }   
  17.         this.stopSelf();   
  18.     }   
  19. }  


本文转自wanqi博客园博客,原文链接:http://www.cnblogs.com/wanqieddy/p/3860388.html,如需转载请自行联系原作者


相关文章
|
29天前
|
存储 编译器 C语言
【C++ 模板编程 实用手段】深入理解 C++ 中的 packaged_task、invoke_result_t、bind、result_of 和 Lambda
【C++ 模板编程 实用手段】深入理解 C++ 中的 packaged_task、invoke_result_t、bind、result_of 和 Lambda
33 0
|
10月前
NullPointerException:method 'android.content.BroadcastReceiver.onReceive' on a null object reference
NullPointerException:method 'android.content.BroadcastReceiver.onReceive' on a null object reference
|
前端开发
springboot05、封装返回结果集{state:““msg:““result:null}
springboot05、封装返回结果集{state:““msg:““result:null}
119 0
springboot05、封装返回结果集{state:““msg:““result:null}
|
JavaScript 开发者
res.setHeader 方法和 res.writeHead 方法|学习笔记
快速学习 res.setHeader 方法和 res.writeHead 方法
517 0
|
SQL 存储 Java
ResultSet/ResultSetMetaData相关和用法
ResultSet/ResultSetMetaData相关和用法
|
存储 API
深入理解Activity Result API:ActivityResultContract的实现原理
AndroidX从Activity:1.2.0-alpha02 和 Fragment:1.3.0-alpha02 起追加了Result API,使用ActivityResultContract替代st
581 0
|
SQL Java 关系型数据库