android service基础

来源:互联网 发布:白俄罗斯知乎 编辑:程序博客网 时间:2024/05/25 23:56

一、启动/销毁service

//start service

intent = new Intent(context, MtpService.class);
intent.putExtra(UsbManager.USB_FUNCTION_PTP, true);
context.startService(intent);

//destroy service

context.stopService(new Intent(context, MtpService.class));

二、绑定/解绑定

private IMtpService mMtpService;

private final ServiceConnection mMtpServiceConnection = new ServiceConnection() {
         public void onServiceConnected(ComponentName className, android.os.IBinder service) {
            synchronized (this) {
                mMtpService = IMtpService.Stub.asInterface(service);
            }
        }

        public void onServiceDisconnected(ComponentName className) {
            synchronized (this) {
                mMtpService = null;
            }
        }

 };

//bind

context.bindService(new Intent(context, MtpService.class), mMtpServiceConnection, Context.BIND_AUTO_CREATE);

当bindService执行之后会自动调用mMtpServiceConnection接口里面的onServiceConnected方法,从而获得mMtpService,

然后在Activity里面就能够通过mMtpService调用IMtpService提供的方法。

//unbind

getContext().unbindService(mMtpServiceConnection);

unbindService之后不会自动调用mMtpServiceConnection接口里面的onServiceDisconnected方法,onServiceDisconnected只会

在Service被停止或者被系统杀死后调用。unbindService只是告诉系统对应的Activity不再使用该服务了,系统内存不足的时候可以优先

杀死这个服务。

Service在开始之后,除非调用stopService()或stopSelf(),否则不会停止。当然,如果内存不足,系统可能自动杀死Service。

三、IMtpService

新建文件IMtpService.aidl

package com.android.providers.media;

interface IMtpService
{
    void sendObjectAdded(int objectHandle);
    void sendObjectRemoved(int objectHandle);
}

是一个interface,具体实现在MtpService中。

四、MtpService

private final IMtpService.Stub mBinder =
            new IMtpService.Stub() {
        public void sendObjectAdded(int objectHandle) {

           //实现这个方法

        }

        public void sendObjectRemoved(int objectHandle) {
            //实现这个方法

        }
    };

在MtpService服务的onBind方法中返回这个mBinder。

@Override
    public IBinder onBind(Intent intent)
    {
        return mBinder;
    }

 

原创粉丝点击