美文网首页
IntentService

IntentService

作者: 大盗海洲 | 来源:发表于2019-05-28 19:52 被阅读0次

使用

创建类

public class MyIntentService extends IntentService {

    public MyIntentService(){
        super("test");
    }

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

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Log.d("MyIntentService",intent.getStringExtra("MyIntentService")+"  before"+" threadName"+Thread.currentThread().getName());
        try {
            Thread.sleep(1000);
            Log.d("MyIntentService",intent.getStringExtra("MyIntentService")+"  after"+" threadName"+Thread.currentThread().getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        Log.e("onStartCommand", "onCreate");
        return super.onStartCommand(intent, flags, startId);

    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("MyIntentService", "onCreate");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("MyIntentService", "onDestroy");
    }
}

manifest 注册service

     <service android:name="d.test.MyIntentService"/>

启动service

  Intent intent = new Intent(MainActivity2.this, MyIntentService.class);
        intent.putExtra("MyIntentService", "-------MyIntentService----");
        startService(intent);

log


image.png

源码分析

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);
            //自动stopService
            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;
    }


    @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.
        //在处理期间有一个选项来保存部分唤醒锁,并且有一个静态的startService(Context,Intent)方法可以启动服务并交出唤醒锁。
        super.onCreate();
         //创建工作线程
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        //启动线程
        thread.start();
        // looper是在工作线程创建,所以此时的handler也是运行在工作线程的
        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }
   
    @Override
    public void onStart(@Nullable Intent intent, int startId) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        //发送消息到handler,回调onHandleIntent()
        //所以只能startService启动service,若是通过bindService,则不会走onStart方法,也就不会调用onHandleIntent()处理异步方法
         //bindService 生命周期 oncreate()--->onBind() ----->onUnBind() ---->onDestory()
        mServiceHandler.sendMessage(msg);
    }
    @Override
    public void onDestroy() {
        //自动清除MessageQueue里的looper
        mServiceLooper.quit();
    }
    //工作线程
    @WorkerThread
    protected abstract void onHandleIntent(@Nullable Intent intent);
}

/**
 * Handy class for starting a new thread that has a looper. The looper can then be 
 * used to create handler classes. Note that start() must still be called.
 */
 //用于启动具有looper的新线程的方便类。 然后可以使用looper来创建处理程序类。 请注意,仍然必须调用start()。
public class HandlerThread extends Thread {
    
    @Override
    public void run() {
        mTid = Process.myTid();
        //创建looper,此时的looper 位于工作线程
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }
    

}

相关文章

网友评论

      本文标题:IntentService

      本文链接:https://www.haomeiwen.com/subject/zhcjtctx.html