Android Intent Service Usage
16lz
2021-01-23
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.MyIntentServiceActivityimport 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.运行结果
总结:
我们只有一个按钮和两个label,在开始工作前,label分别为to be start和to be end,点击start后,调用三次intentservice,label会显示代码运行在click事件里面的事件,我们发现还不到一秒,但是在后台的intent service 的log里面我们看到,intent service 执行的事件从12秒到了42秒,所以,intent service 是后台线程执行的。
更多相关文章
- Android浏览器显示大分辨率图片的问题 分享
- Android for opencv(1)android使用opencv基本操作:读写 图片,操作像
- android按键焦点事件分析(应用开发篇)
- Android彻底组件化—代码和资源隔离
- android 自定义组件 :对VelocityTracker的研究
- Android层次化安全架构及核心组件概览
- android:组件化方案
- Android浏览器显示大分辨率图片的问题