第三章--四大组件之一Service

一直是听过其大名,现在终于是学到了。

1、什么是Service

作为android四大组件之一,它一直默默付出,不像Activity,可以被人所见。Service一般进行长时间的后台操作,没有界面,不是进程也不是线程,比avtivity有更高的优先级。使用Service,有两步。

  1. 定义一个继承Service的子类
  2. 在AndroidManifest中注册该Service

Service有一些可以重写的方法:

  1. IBinder onBind(Intent intent):这是必须重写的方法,当有一个客户端和Service绑定时,返回的对象可以作为communication channel(我不知道怎么翻译)和Service通信,如果没有绑定,返回null。IBinder是一个接口,但是一般不直接实现,而是继承IBinder的实现类Binder。
  2. void onCreate():第一次创建Service后会被调用。
  3. onStartCommand(Intent intent, int flags, int startId):客户端调用startService(Intent intent)时会被调用。取代了原本的方法onStart(Intent intent, int startId)
  4. void onDestroy():Service关闭之前会调用的方法

Service的生命周期

说完了service的一些基本知识,下面看下它的生命周期:


第三章--四大组件之一Service_第1张图片
这里写图片描述

从图中可以看出Service有两个运行方式,一个是startService(),另一个是bindService()。所以下面我用两种方式运行Service来看一下它的运行过程

2、启动和停止service

写好Service的子类之后,然后写了两个按钮,为其添加点击事件如下

 @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.start:
                startService(new Intent(MusicButtonActivity.this, MusicService.class));
                break;
            case R.id.stop:
                stopService(new Intent(MusicButtonActivity.this, MusicService.class));
                break;

        }
    }

然后Service的代码如下,使用MediaPlayer播放了一段放在res\raw下的音乐

public class MusicService extends Service{

    private static final String TAG = MusicService.class.getSimpleName();
    //private MyBinder mMyBinder = new MyBinder();
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate");
        mMediaPlayer = MediaPlayer.create(this, R.raw.my);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand");
        mMediaPlayer.start();
        return START_NOT_STICKY;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy");
        mMediaPlayer.stop();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind");
        return mMyBinder;
    }

    @Override
    //客户端和Service解绑时回调的方法
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "onUnbind");
        return super.onUnbind(intent);
    }
}

按下start,然后stop,可以看到后台打印

I/MusicService: onCreate
I/MusicService: onStartCommand
I/MusicService: onDestroy

按下start,然后再按start,后台打印如下:

I/MusicService: onCreate
I/MusicService: onStartCommand
I/MusicService: onStartCommand

可见onCreate()只会调用一次,当Service已经启动后,之后就只会调用onStartCommand()方法。
以上使用Service的方法,Activity和Service基本上没有什么关联,两者之间无法进行通信,交换数据什么的。所以想实现通信应该用bindService()和unBindService()

3、绑定Service

bindService()里面有三个参数boolean bindService(Intent service, ServiceConnection conn, int flags)

  • 第一个就是通过Intent启动指定的Service。
  • 第二个是ServiceConnection对象,监听访问者(clients)和Service的连接情况,我们可以看一下它的代码
private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("connected");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

            System.out.println("disconnected");
        }
    };

当访问者和Servive连接成功时会回调onServiceConnected(ComponentName name, IBinder service)其中service就是onBinder(Intent intent)返回的IBinder对象,通过这个IBinder对象与Service就可以进行通信。另外onServiceDisconnected(ComponentName name)只会在异常断开和Service连接时,才会调用该方法,正常断开不会回调

  • 最后一个指定绑定的时候如果还没有创建Service,是否自动创建Service,0为不创建,BIND_AUTO_CREATE为自动创建。
    在上个代码上修改,在activity里得到歌曲的总时长(毫秒)。
public class MusicService extends Service{

    private static final String TAG = MusicService.class.getSimpleName();
    private MyBinder mMyBinder = new MyBinder();

    private MediaPlayer mMediaPlayer;
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate");
        mMediaPlayer = MediaPlayer.create(this, R.raw.my);
        mMediaPlayer.start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand");
       // mMediaPlayer.start();
        return START_NOT_STICKY;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy");
        mMediaPlayer.stop();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind");
        return mMyBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "onUnbind");
        return super.onUnbind(intent);
    }

    public class MyBinder extends Binder{
        public int getProgress(){

            return mMediaPlayer.getDuration();
        }
    }
}

上面onBind()方法返回了一个可以得到歌曲总时长的Binder对象,该对象将会传给访问该Service的访问者。
在activity里的代码:

public class MusicButtonActivity extends AppCompatActivity implements View.OnClickListener{

    private Button mStop_button;
    private Button mStart_button;
    MusicService.MyBinder mBinder;

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            System.out.println("connected");
            //得到传入的对象
            mBinder = (MusicService.MyBinder) service;
            //得到了歌曲的时长
            int a = mBinder.getProgress();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

            System.out.println("disconnected");
        }
    };

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

        mStart_button = (Button) findViewById(R.id.start);
        mStop_button = (Button) findViewById(R.id.stop);

        mStart_button.setOnClickListener(this);
        mStop_button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.start:
                //startService(new Intent(MusicButtonActivity.this, MusicService.class));
                bindService(new Intent(MusicButtonActivity.this, MusicService.class), mServiceConnection, Service.BIND_AUTO_CREATE);

                break;
            case R.id.stop:
                unbindService(mServiceConnection);
                //stopService(new Intent(MusicButtonActivity.this, MusicService.class));
                break;

        }
    }
}

点击start,后台打印

MusicService: onCreate
MusicService: onBind

点击stop,后台打印

08-07 15:59:01.430 14412-14412/com.example.myactionbardemo I/MusicService: onCreate
08-07 15:59:01.485 14412-14412/com.example.myactionbardemo I/MusicService: onBind
08-07 15:59:04.333 14412-14412/com.example.myactionbardemo I/MusicService: onUnbind
08-07 15:59:04.334 14412-14412/com.example.myactionbardemo I/MusicService: onDestroy

通过这种方法可以对Service的数据进行我们需要的操作。
除了以上的两种情况,如果在Service已经启动的情况下,再去绑定的话,这个时候如果只是先解绑,在stop才能把Service销毁

08-07 16:01:29.551 17091-17091/com.example.myactionbardemo I/MusicService: onCreate
08-07 16:01:29.596 17091-17091/com.example.myactionbardemo I/MusicService: onStartCommand
08-07 16:01:29.599 17091-17091/com.example.myactionbardemo I/MusicService: onBind
08-07 16:01:40.265 17091-17091/com.example.myactionbardemo I/MusicService: onUnbind
08-07 16:01:40.275 17091-17091/com.example.myactionbardemo I/MusicService: onDestroy

4、IntentService

我们开篇说过Service不是一个线程,它其实运行在主线程里,所以它里面不能处理一个耗时操作,当Service处理耗时操作超过20秒时,将会出现ANR(application not responding)异常,这是不能允许的。如果确实想在Service处理耗时操作,建议另开一条线程处理。除此之外,还可以使用Service的子类IntentService。如下面的代码

public class MyIntentService  extends IntentService{
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public MyIntentService(String name) {
        super(name);
    }

    @Override
    protected void onHandleIntent(Intent intent) {

    }
}

看了下IntentService的源码

public abstract class IntentService extends Service {
    private volatile Looper mServiceLooper;
    private volatile ServiceHandler mServiceHandler;
    private String mName;
    private boolean mRedelivery;
    //处理Intent请求
    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);
        }
    }

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

    //发送处理intent请求的消息
    @Override
    public void onStart(Intent intent, int startId) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
    }

    /**
     * You should not override this method for your IntentService. Instead,
     * override {@link #onHandleIntent}, which the system calls when the IntentService
     * receives a start request.
     * @see android.app.Service#onStartCommand
     */
    @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();
    }

    /**
     * Unless you provide binding for your service, you don't need to implement this
     * method, because the default implementation returns null. 
     * @see android.app.Service#onBind
     */
    @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.
     * When all requests have been handled, the IntentService stops itself,
     * so you should not call {@link #stopSelf}.
     *
     * @param intent The value passed to {@link
     *               android.content.Context#startService(Intent)}.
     */
    @WorkerThread
    protected abstract void onHandleIntent(Intent intent);
}

IntentService会创建一个HandlerThread这样的线程来处理所有的Intent请求,而我们只用重写void onHandleIntent(Intent intent)。IntentService就会帮我们处理。

你可能感兴趣的:(第三章--四大组件之一Service)