android学习笔记(13) intent Services多线程初步

来源:互联网 发布:聚合数据 编辑:程序博客网 时间:2024/04/29 23:04

IntentService是Service类的子类,用来处理异步请求,客户端通过startService(intent)方法传递请求给IntentService,IntentService通过worher thread处理每个Intent对象,执行完所有工作后自动停止Service.

IntentService执行如下操作:
*创建一个与应用程序线程分开的worker thread 用来处理所有通过学习onstartcommand()传递过来的Intent请求
*创建一个work queue,一次只传递一个intent到onHandleIntent()方法中,从而不用担心多线程带来的问题
*当处理完所有请求后自动停止服务,而不需要我们自己调用stopSelf()方法.
*默认实现了onBind()方法,返回值为null
*默认实现了onStartCommand()方法,这个方法将会把我们的intent放到work queue中,然后在onHandleIntent()中执行.
:
写构造方法

复写onHandleIntent()方法

源码对一般的多线程服务和intent service多线程对比:

MainActivity.java:

package com.example1.servicedemo;import org.apache.commons.logging.Log;import android.net.sip.SipAudioCall.Listener;import android.os.Bundle;import android.app.Activity;import android.content.Intent;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity {protected static final String TAG = "MainActivity";private Button btnButton;private Button btnButton2;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        btnButton = (Button)findViewById(R.id.btnstartnormalservice);        btnButton2 = (Button)findViewById(R.id.btnstartintentservice);        btnButton.setOnClickListener(listener);        btnButton2.setOnClickListener(listener);    }private OnClickListener listener = new OnClickListener() {@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.btnstartnormalservice:Intent intent = new Intent(MainActivity.this,ExampleService.class);Log.i(TAG,"主线程ID:"+Thread.currentThread().getId());//输出当前线程IDstartService(intent);break;case R.id.btnstartintentservice:Intent intent2 = new Intent(MainActivity.this,ExampleIntentService.class);Log.i(TAG,"主线程ID:"+Thread.currentThread().getId());//输出当前线程IDstartService(intent);break;default:break;}}};    }
ExampleIntentService.java

package com.example1.servicedemo;import android.app.IntentService;import android.content.Intent;public class ExampleIntentService extends IntentService {private static final String tag = "ExampleIntentService";public ExampleIntentService(String name) {super("ExampleIntentService");}@Overrideprotected void onHandleIntent(Intent arg0) {try {android.util.Log.i(tag,"Exampleservice线程ID:"+Thread.currentThread().getId());android.util.Log.i(tag,"文件下载...");Thread.sleep(2000);            } catch (InterruptedException e) {e.printStackTrace();}}}
记得在XML中声明服务!!: <service android:name=".ExampleIntentService"/>

结果:

多次点击startnormalservice按键:

主线程ID:1

Exampleservice线程ID:9

文件下载...

主线程ID:1

Exampleservice线程ID:10

文件下载...

主线程ID:1

Exampleservice线程ID:11

文件下载...

多次点击startintentservice按键:

主线程ID:1

主线程ID:1

主线程ID:1

Exampleservice线程ID:9

文件下载...

Exampleservice线程ID:9

文件下载...

Exampleservice线程ID:9

文件下载...




4 0