android 四大组件之Service(4)IntentService
2016-06-24 19:17
267 查看
IntentService : 自带线程,处理请求,但每次值处理一个线程。主要实现一个方法 onHandleIntent(); Service类的子类,它使用了工作(worker)线程来处理所有的启动请求,每次请求都会启动一个线程 如果服务不需要同时处理多个请求的话,这是最佳的选择。 所有你要做的工作就是实现onHandleIntent() 即可,它会接收每个启动请求的intent,然后就可在后台完成工作。
因为大多数started服务都不需要同时处理多个请求(这实际上是一个危险的多线程情况), 所以最佳方式也许就是用IntentService类来实现你的服务。 IntentService将执行以下步骤: 创建一个缺省的工作(worker)线程,它独立于应用程序主线程来执行所有 发送到onStartCommand()的intent。 创建一个工作队列,每次向你的onHandleIntent()传入一个intent, 这样你就永远不必担心多线程问题了。 在处理完所有的启动请求后,终止服务,因此你就永远不需调用stopSelf()了。 提供缺省的onBind()实现代码,它返回null。 提供缺省的onStartCommand()实现代码,它把intent送入工作队列, 稍后会再传给你的onHandleIntent()实现代码。 以上所有步骤将汇成一个结果:你要做的全部工作就是实现onHandleIntent()的代码, 来完成客户端提交的任务。(当然你还需要为服务提供一小段构造方法。)
第一步创建一个IntentService的子类,实现onHandleIntent() 方法 public class HelloIntentService extends IntentService{ private static final String image_path = "http://pic.xxhh.com/cons/20160513/8ce093d306da08fa.jpg"; public HelloIntentService() { super("HelloService"); } /** * IntentService从缺省的工作线程中调用本方法,并从启动服务的Intent作为参数, * 本方法返回后,IntentService将适时的终止这个服务。 */ @Override protected void onHandleIntent(Intent intent) { Log.i("tag", "onHandleIntent"); HttpClient httpClient = new DefaultHttpClient(); HttpGet httpPost = new HttpGet(image_path); try { HttpResponse response = httpClient.execute(httpPost); if( response.getStatusLine().getStatusCode() == 200) { byte[] result = EntityUtils.toByteArray(response.getEntity()); boolean flag = SDKTools.saveToSDK("ab.jpg", result); if(flag) Log.i("tag", "下载成功。。。"); } else { Log.i("tag", "下载失败==>"+response.getStatusLine().getStatusCode()); } }catch(Exception e) { e.printStackTrace(); } } } 第二步在清单文件中注册服务: <service android:name="com.example.intentservicetest.HelloIntentService">
第三部在activity中启动服务,她是继承服务,启动方式一样
public class MainActivity extends Activity { Button btn1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn1 = (Button)findViewById(R.id.button1); btn1.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(MainActivity.this, HelloIntentService.class); startService(intent); } }); } }
相关文章推荐
- AndroidStudio-Git-回滚
- Xamarin.Android set cornerRadius by code
- Android-更新系统图库碰到的问题
- Android setContentView 加载布局源码解析
- Android补间动画(Tween Animation)的使用总结
- Android之RecyclerView的使用总结
- Android测试提升效率批处理脚本(三)
- android 更换时区时间同步
- Android开发BroadcastReceiver中的Action使用说明
- 3.1、Android Studio在虚拟机中运行应用
- 3.1、Android Studio在虚拟机中运行应用
- genymotion模拟器无法启动:VirtualBox cannot start the virtual device
- Android Error retrieving parent for item: No resource found that matches the given name '...'
- android 中TextView设置部分文字背景色和文字颜色
- Android ViewPager与SwipeBackLayout的业务需求解决
- 将 Google Analytics(分析)添加到 Android 应用中
- Swipebacklayout侧滑关闭Activity
- Android系统中Bitmap是否有调用recycle方法的必要性
- android内存优化大汇总
- android 6.24通知