本文共 2453 字,大约阅读时间需要 8 分钟。
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"); } @Override protected 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; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.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(){ @Override public void onClick(View view) { // TODO Auto-generated method stub Intent intent = new Intent(MyIntentServiceActivity.this,MyIntentService.class); txtStr.setText("str"); startService(intent); startService(intent); startService(intent); txtEnd.setText("end"); } }); }}3.布局文件(intentservice.xml)
4.Manitest.xml
5.运行结果
总结:
我们只有一个按钮和两个label,在开始工作前,label分别为to be start和to be end,点击start后,调用三次intentservice,label会显示代码运行在click事件里面的事件,我们发现还不到一秒,但是在后台的intent service 的log里面我们看到,intent service 执行的事件从12秒到了42秒,所以,intent service 是后台线程执行的。