IntentService解析

IntentService中内置了一个HandlerThread,能够对数据进行处理。相比于普通的Service,IntentService有以下优点:

1. 不用在Service创建线程。

2. 不用考虑什么时候关闭Service。

IntentService使用示例

CountService类

package com.fxb.intentservicetest;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

public class CountService extends IntentService{

    private volatile boolean isRunning = true;

    public CountService(String name) {
        super(name);
    }

    public CountService(){
        super("CountService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.i(MainActivity.TAG, "StartCount");
        int count = intent.getIntExtra("StartCount", 0);
        startCount(count);

    }

    private void startCount(int count){
        isRunning = true;
        while(isRunning){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            count++;
            Intent intent = new Intent("MY_COUNTER");
            intent.putExtra("count", count);
            sendBroadcast(intent);
        }
    }


}

测试Activity

package com.fxb.intentservicetest;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements View.OnClickListener{

    public static final String TAG = "IntentServiceTest";

    private TextView tvShow;
    private Button btnStart;
    private BroadcastReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                int count = intent.getIntExtra("count", 0);
                tvShow.setText("count:"+count);
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction("MY_COUNTER");
        registerReceiver(receiver, filter);
    }

    private void initView(){
        tvShow = (TextView)findViewById(R.id.tvShow);
        btnStart = (Button)findViewById(R.id.btnStart);

        btnStart.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v == btnStart){
            Intent intent = new Intent(this, CountService.class);
            intent.putExtra("StartCount", 5);
            startService(intent);

            Log.i(MainActivity.TAG, "my click");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}

点击Start按钮后,tvShow依次递增变化,从5开始。

IntentService源码

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;

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

    public IntentService(String name) {
        super();
        mName = name;
    }

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

    protected abstract void onHandleIntent(Intent intent);
}
原文地址:https://www.cnblogs.com/MiniHouse/p/6706044.html