Android 中的 Service(Local Server 和 Remote Service)与 Activity 都是 Android 的基础组件,而且二者是同级组件。在 Service 中运行耗时操作时,会阻塞 Activity 的运行,超过5秒钟则会引发ANR错误,那么在 Android 中有没有类似 Task 的执行异步任务的机制呢?答案是肯定的,Android 中的 IntentService 就是负责这种异步任务的,今天写了一个关于 Intent Service 的Demo。

1.MyIntentService

import android.app.IntentService;import android.content.Intent;import android.util.Log;public class MyIntentService extends IntentService {final static String TAG = "MyIntentService";public MyIntentService() {super("com.wicresoft.MyIntentService");Log.i(TAG,"MyIntentService is constructed");}@Overrideprotected void onHandleIntent(Intent arg0) {Log.i(TAG,"begin onHandleIntent() in MyIntentService");try {Thread.sleep(10*1000);} catch (InterruptedException e) {e.printStackTrace();}Log.i(TAG,"end onHandleIntent() in MyIntentService");}public void onDestroy(){super.onDestroy();Log.i(TAG,"MyIntentService is destroy");}}
2.MyIntentServiceActivity

import com.example.myandroid_002.R;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MyIntentServiceActivity extends Activity {private Button btn;private TextView txtStr;private TextView txtEnd;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);this.setContentView(R.layout.intentservice);btn = (Button)this.findViewById(R.id.btnIntent);txtStr = (TextView)this.findViewById(R.id.start);txtEnd = (TextView)this.findViewById(R.id.end);btn.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View view) {// TODO Auto-generated method stubIntent intent = new Intent(MyIntentServiceActivity.this,MyIntentService.class);txtStr.setText("str");startService(intent);startService(intent);startService(intent);txtEnd.setText("end");}});}}
3.布局文件(intentservice.xml)

<?xml version="1.0" encoding="utf-8"?>        
4.Manitest.xml

                                                                                          
5.运行结果

Android Intent Service Usage_第1张图片

Android Intent Service Usage_第2张图片
Android Intent Service Usage_第3张图片

总结:

我们只有一个按钮和两个label,在开始工作前,label分别为to be start和to be end,点击start后,调用三次intentservice,label会显示代码运行在click事件里面的事件,我们发现还不到一秒,但是在后台的intent service 的log里面我们看到,intent service 执行的事件从12秒到了42秒,所以,intent service 是后台线程执行的。

更多相关文章

  1. Android浏览器显示大分辨率图片的问题 分享
  2. Android for opencv(1)android使用opencv基本操作:读写 图片,操作像
  3. android按键焦点事件分析(应用开发篇)
  4. Android彻底组件化—代码和资源隔离
  5. android 自定义组件 :对VelocityTracker的研究
  6. Android层次化安全架构及核心组件概览
  7. android:组件化方案
  8. Android浏览器显示大分辨率图片的问题

随机推荐

  1. Android(安卓)PNG渐变背景图片失真问题
  2. Android(安卓)AIDL服务学习笔记
  3. 教你瘦身zxing(android)
  4. 转:大厂Android面试题
  5. android新建工程报找不到android:preserv
  6. Android中的Layout_weight详解
  7. 如何移植ROS程序到Android
  8. Android第三章 (UI)
  9. 福利来了!带你“爱上Android”
  10. Android(安卓)SDK下载慢的最给力解决办法