AsyncTask入门:http://blog.csdn.net/lincyang/article/details/6617802
IntentService:
今天要说的IntentService提供的功能也很类似,都是来处理异步工作的。
工作流程也非常简单,客户端通过startService(Intent) 方法来调用,服务启动后,开启worker线程来顺序处理intent的任务。注意这里,一个intentService可以处理多个任务,只不过是一个接着一个的顺序来处理的;AsyncTask通常情况是每个任务启动一个新的asycnTask来工作,一个asyncTask只能使用一次,当你想再次使用的话,只好再new一个任务,否则要报异常的。从表象上看,这是两者的区别。当任务完成后,IntentService自动停止。
IntentService是继承自Service的,从源码上看,它是Service、HandlerThread和Handler的强强联合。源码也比AsyncTask简单,有兴趣的童鞋可以去看看。
下面说说它的用法,和AsyncTask一样,使用IntentService必须要写一个类然后继承它。
因为IntentService本身是继承自Service,所以在使用的时候要先在AndroidManifest.xml中注册,否则报错:Unable to start service Intent not found
IntentService有7个方法,其中最重要的是onHandleIntent(),在这里调用worker线程来处理工作,每次只处理一个intent,像上面描述的,如果有多个,它会顺序处理,直到最后一个处理完毕,然后关闭自己。一点都不用我们操心,多好。
再介绍另一个很有意思的方法,setIntentRedelivery()。从字面理解是设置intent重投递。如果设置为true,onStartCommand(Intent, int, int)将会返回START_REDELIVER_INTENT,如果onHandleIntent(Intent)返回之前进程死掉了,那么进程将会重新启动,intent重新投递,如果有大量的intent投递了,那么只保证最近的intent会被重投递。这个机制也很好,大家可以尝试着用。
下面写个小例子,这个例子和之前asyncTask的一样,都是模拟处理耗时任务的。这里加上了广播机制来传递消息。
AndroidManifest.xml:-------------------------->
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.linc.TestIntentService"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".TestIntentService"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".LincIntentService"></service>
</application>
</manifest>
layout.xml---------------------->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:textColor="#FF0000"
android:text="@string/hello"
/>
<Button
android:id="@+id/btnStart"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start"
/>
<Button
android:id="@+id/btnSendOther"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="SendOtherBroadcast"
/>
</LinearLayout>
Activity
package com.linc.TestIntentService;
import android.app.Activity;
import android.app.IntentService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class TestIntentService extends Activity {
private final static String Tag="TestIntentService";
private TextView text;
private Button btnStart;
private Button btnSendOther;
private MessageReceiver receiver ;
/*
* Action
*/
private static final String ACTION_RECV_MSG = "com.linc.intent.action.RECEIVE_MESSAGE";
private static final String ACTION_OTHER_MSG = "com.linc.intent.action.OTHER_MESSAGE";
/*
* Message
*/
private static final String MESSAGE_IN="message_input";
private static final String MESSAGE_OUT="message_output";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text=(TextView)findViewById(R.id.text);
text.setText("准备");
btnStart=(Button)findViewById(R.id.btnStart);
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent msgIntent = new Intent(TestIntentService.this,
LincIntentService.class);
msgIntent.putExtra(MESSAGE_IN, text.getText().toString());
startService(msgIntent);
}
});
btnSendOther=(Button)findViewById(R.id.btnSendOther);
btnSendOther.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
//动态注册receiver
IntentFilter filter = new IntentFilter(ACTION_RECV_MSG);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new MessageReceiver();
registerReceiver(receiver, filter);
IntentFilter filter2 = new IntentFilter(ACTION_OTHER_MSG);
filter2.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new MessageReceiver();
registerReceiver(receiver, filter2);
}
//广播来接收
public class MessageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra(MESSAGE_OUT);
text.setText(message);
Toast.makeText(context, "message",
Toast.LENGTH_SHORT).show();
}
}
}
IntentService
package com.linc.TestIntentService;
import android.app.IntentService;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.text.format.DateFormat;
import android.util.Log;
//IntentService
public class LincIntentService extends IntentService {
/*
* Action
*/
private static final String ACTION_RECV_MSG = "com.linc.intent.action.RECEIVE_MESSAGE";
private static final String ACTION_OTHER_MSG = "com.linc.intent.action.OTHER_MESSAGE";
/*
* Message
*/
private static final String MESSAGE_IN="message_input";
private static final String MESSAGE_OUT="message_output";
private final static String Tag="---LincIntentService";
public LincIntentService() {
super("LincIntentService");
Log.d(Tag, "Constructor");
}
@Override
public IBinder onBind(Intent intent) {
Log.d(Tag, "onBind()");
return super.onBind(intent);
}
@Override
public void onCreate() {
Log.d(Tag, "onCreate()");
super.onCreate();
}
@Override
public void onDestroy() {
Log.d(Tag, "onDestroy()");
super.onDestroy();
}
@Override
public void onStart(Intent intent, int startId) {
Log.d(Tag, "onStart()");
super.onStart(intent, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(Tag, "onStartCommand()");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void setIntentRedelivery(boolean enabled) {
Log.d(Tag, "setIntentRedelivery()");
super.setIntentRedelivery(enabled);
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(Tag, "LincIntentService is onHandleIntent!");
String msgRecv = intent.getStringExtra(MESSAGE_IN);
for (int i = 0; i < 5; i++) {
String resultTxt = msgRecv + " "
+ DateFormat.format("MM/dd/yy hh:mm:ss", System.currentTimeMillis());
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(ACTION_RECV_MSG);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.putExtra(MESSAGE_OUT, resultTxt);
sendBroadcast(broadcastIntent);
SystemClock.sleep(1000);
}
}
// <service android:name=".LincIntentService"></service>
}
从这两篇文章中可以看到,andorid提供这两个处理耗时任务的工具,为我们开发者带来了极大的便利。跟随源码,又可以让我们的水平上升一个档次。看来,android提供的文档和例子就是一个宝库,我们要好好的利用起来!