Android开发笔记3:Service基础

1、Service

1)两种启动方式及其生命周期

2)bindService(Intent service, ServiceConnection conn, int flags)

执行onBind方法,返回IBinder类型,用于IPC(进程间通信)。实现ServiceConnection接口,即可获取onBind方法返回的IBinder。

Binder类实现了IBinder接口,如果接收到Binder类型的返回值,调用transact(int code, Parcel data, Parcel reply, int flags), 即可执行回调函数onTransact(int code, Parcel data, Parcel reply, int flags),通过传递Parcel类型的数据实现了进程间通信。

3)IntentService

a)Service需要新起线程执行任务

Caution: A services runs in the same process as the applicationin which it is declared and in the main thread of that application, by default. So, if your serviceperforms intensive or blocking operations while the user interacts with an activity from the sameapplication, the service will slow down activity performance. To avoid impacting applicationperformance, you should start a new thread inside the service.

所以IntentService中,使用了HandlerThread(继承了Thread),另起一个新的线程来执行我们的任务

当Service第一次被启动时,会执行onCreate方法,也就是说当Service第一次运行时,处理任务的线程也就开始执行了。

注:同时用当前线程的Looper来初始化Handler。

public void onCreate() {

        super.onCreate();
        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
        thread.start();

        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

b)HandlerThread的run()方法

线程开始执行后,调用Looper.prepare()初始化当前线程中的Looper mLooper,并且调用Looper.loop()持续分发消息。

public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }

注:同时可以实现void onLooperPrepared() 方法

 /**
     * Call back method that can be explicitly over ridden if needed to execute some
     * setup before Looper loops.
     */
    protected void onLooperPrepared() {
    }

为什么这样设计呢?接着往下看。

在Service创建后再调用startService时只会执行onStart,也就是说每个IntentService只有一个线程来处理任务。就是通过不断的发送消息到消息队列,然后交由Handler来处理

@Override
    public void onStart(Intent intent, int startId) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
    }
 @Override
        public void handleMessage(Message msg) {
            onHandleIntent((Intent)msg.obj);
            stopSelf(msg.arg1);
        }
可以通过实现抽象方法abstract void onHandleIntent(Intent intent),来完成我们的任务

注:按照前面的生命周期,当使用bindService启动IntentService时,只执行onBind方法,而IntentService并没有实现该方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值