一个例子带IntentService入门

 

之前写过一篇文章讲AsyncTask入门的,http://blog.csdn.net/lincyang/article/details/6617802。
今天要说的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




    
 

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);
		}

    }
//    
}

从这两篇文章中可以看到,andorid提供这两个处理耗时任务的工具,为我们开发者带来了极大的便利。跟随源码,又可以让我们的水平上升一个档次。看来,android提供的文档和例子就是一个宝库,我们要好好的利用起来!
附上源码

/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.app;

import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;

/**
 * IntentService is a base class for {@link Service}s that handle asynchronous
 * requests (expressed as {@link Intent}s) on demand.  Clients send requests
 * through {@link android.content.Context#startService(Intent)} calls; the
 * service is started as needed, handles each Intent in turn using a worker
 * thread, and stops itself when it runs out of work.
 *
 * 

This "work queue processor" pattern is commonly used to offload tasks * from an application's main thread. The IntentService class exists to * simplify this pattern and take care of the mechanics. To use it, extend * IntentService and implement {@link #onHandleIntent(Intent)}. IntentService * will receive the Intents, launch a worker thread, and stop the service as * appropriate. * *

All requests are handled on a single worker thread -- they may take as * long as necessary (and will not block the application's main loop), but * only one request will be processed at a time. * * @see android.os.AsyncTask */ public abstract class IntentService extends Service { private volatile Looper mServiceLooper; private volatile ServiceHandler mServiceHandler; private String mName; private boolean mRedelivery; private final class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { onHandleIntent((Intent)msg.obj); stopSelf(msg.arg1); } } /** * Creates an IntentService. Invoked by your subclass's constructor. * * @param name Used to name the worker thread, important only for debugging. */ public IntentService(String name) { super(); mName = name; } /** * Sets intent redelivery preferences. Usually called from the constructor * with your preferred semantics. * *

If enabled is true, * {@link #onStartCommand(Intent, int, int)} will return * {@link Service#START_REDELIVER_INTENT}, so if this process dies before * {@link #onHandleIntent(Intent)} returns, the process will be restarted * and the intent redelivered. If multiple Intents have been sent, only * the most recent one is guaranteed to be redelivered. * *

If enabled is false (the default), * {@link #onStartCommand(Intent, int, int)} will return * {@link Service#START_NOT_STICKY}, and if the process dies, the Intent * dies along with it. */ public void setIntentRedelivery(boolean enabled) { mRedelivery = enabled; } @Override public void onCreate() { // TODO: It would be nice to have an option to hold a partial wakelock // during processing, and to have a static startService(Context, Intent) // method that would launch the service & hand off a wakelock. super.onCreate(); HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); thread.start(); mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); } @Override public void onStart(Intent intent, int startId) { Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = intent; mServiceHandler.sendMessage(msg); } @Override public int onStartCommand(Intent intent, int flags, int startId) { onStart(intent, startId); return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY; } @Override public void onDestroy() { mServiceLooper.quit(); } @Override public IBinder onBind(Intent intent) { return null; } /** * This method is invoked on the worker thread with a request to process. * Only one Intent is processed at a time, but the processing happens on a * worker thread that runs independently from other application logic. * So, if this code takes a long time, it will hold up other requests to * the same IntentService, but it will not hold up anything else. * * @param intent The value passed to {@link * android.content.Context#startService(Intent)}. */ protected abstract void onHandleIntent(Intent intent); }






 

 

你可能感兴趣的:(Android)