一、Service的概念

Service是Android程序中四大基础组件之一,它和Activity一样都是Context的子类,只不过它没有UI界面,是在后台运行的组件。

1.jpg

二、Service的生命周期

Service对象不能自己启动,需要通过某个Activity、Service或者其他Context对象来启动。启动的方法有两种,Context.startService和Context.bindService()。两种方式的生命周期是不同的,具体如下所示。

Context.startService方式的生命周期:
启动时,startService –> onCreate() –> onStart()
停止时,stopService –> onDestroy()

Context.bindService方式的生命周期:
绑定时,bindService  -> onCreate() –> onBind()
解绑定时,unbindService –>onUnbind() –> onDestory()

三、实例:控制音乐播放的Service

下面我们用一个可以控制在后台播放音乐的例子来演示刚才所学知识,同学们可以通过该例子可以明显看到通过绑定方式运行的Service在绑定对象被销毁后也被销毁了。

下面把代码分享如下:

1、建立一个新项目名字叫 Lesson14_HelloService,Activity起名叫MainHelloService.java

2、res/layout/main.xml中代码写成


  1. < ?xml version="1.0" encoding="utf-8"?>

  2. <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">

  3. <textview android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="音乐播放服务" android:textsize="25sp" android:layout_margintop="10dp">

  4. <button android:text="开启音乐播放服务" android:textsize="20sp" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="10dp">

  5. </button>

  6. <button android:text="停止音乐播放服务" android:textsize="20sp" android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="10dp">

  7. </button>


  8. <button android:text="绑定音乐播放服务" android:textsize="20sp" android:id="@+id/Button03" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="10dp">

  9. </button>

  10. <button android:text="解绑定音乐播放服务" android:textsize="20sp" android:id="@+id/Button04" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="10dp">

  11. </button>

  12. </textview></linearlayout>



2、在res目录中建立一个raw目录,并把一个音乐文件babayetu.mp3拷贝进来3、在Activity的同目录新建一个service文件MusicService.java
  1. package android.basic.lesson14;


  2. import android.app.Service;

  3. import android.content.Intent;

  4. import android.media.MediaPlayer;

  5. import android.os.IBinder;

  6. import android.util.Log;

  7. import android.widget.Toast;


  8. public class MusicService extends Service {


  9.        //为日志工具设置标签

  10.        String tag ="MusicService";        


  11.        //定义音乐播放器变量

  12.        MediaPlayer mPlayer;


  13.        //其他对象通过bindService方法通知该Service时该方法会被调用

  14.        @Override

  15.        public IBinder onBind(Intent intent) {

  16.                Toast.makeText(this,"MusicService onBind()",Toast.LENGTH_SHORT).show();

  17.                Log.i(tag, "MusicService onBind()");

  18.                mPlayer.start();

  19.                return null;

  20.        }


  21.        //其他对象通过unbindService方法通知该Service时该方法会被调用

  22.        @Override

  23.        public boolean onUnbind(Intent intent){

  24.                Toast.makeText(this, "MusicService onUnbind()", Toast.LENGTH_SHORT).show();

  25.                Log.i(tag, "MusicService onUnbind()");

  26.                mPlayer.stop();

  27.                return false;

  28.        }


  29.        //该服务不存在需要被创建时被调用,不管startService()还是bindService()都会在启动时调用该方法

  30.        @Override

  31.        public void onCreate(){

  32.                Toast.makeText(this, "MusicService onCreate()", Toast.LENGTH_SHORT).show();

  33.                //创建一个音乐播放器对象

  34.                mPlayer=MediaPlayer.create(getApplicationContext(), R.raw.babayetu);

  35.                //设置可以重复播放

  36.                mPlayer.setLooping(true);

  37.                Log.i(tag, "MusicService onCreate()");

  38.        }


  39.        //用startService方法调用该服务时,在onCreate()方法调用之后,会调用改方法

  40.        @Override

  41.        public void onStart(Intent intent,int startid){

  42.                Toast.makeText(this,"MusicService onStart",Toast.LENGTH_SHORT).show();

  43.                Log.i(tag, "MusicService onStart()");

  44.                mPlayer.start();

  45.        }


  46.        //该服务被销毁时调用该方法

  47.        @Override

  48.        public void onDestroy(){

  49.                Toast.makeText(this, "MusicService onDestroy()", Toast.LENGTH_SHORT).show();

  50.                mPlayer.stop();

  51.                Log.i(tag, "MusicService onDestroy()");

  52.        }

  53. }


4、MainHelloService.java中的代码:
  1. package android.basic.lesson14;


  2. import android.app.Activity;

  3. import android.content.ComponentName;

  4. import android.content.Context;

  5. import android.content.Intent;

  6. import android.content.ServiceConnection;

  7. import android.os.Bundle;

  8. import android.os.IBinder;

  9. import android.util.Log;

  10. import android.view.View;

  11. import android.view.View.OnClickListener;

  12. import android.widget.Button;

  13. import android.widget.Toast;


  14. public class MainHelloService extends Activity {


  15.        //为日志工具设置标签

  16.        String tag = "MusicService";


  17.    /** Called when the activity is first created. */

  18.    @Override

  19.    public void onCreate(Bundle savedInstanceState) {

  20.        super.onCreate(savedInstanceState);

  21.        setContentView(R.layout.main);


  22.        //输出Toast消息和日志记录

  23.                Toast.makeText(MainHelloService.this, "MainHelloService onCreate", Toast.LENGTH_SHORT).show();

  24.                Log.i(tag, "MainHelloService onCreate");


  25.        //定义组件对象

  26.        Button b1= (Button)findViewById(R.id.Button01);

  27.        Button b2= (Button)findViewById(R.id.Button02);

  28.        Button b3= (Button)findViewById(R.id.Button03);

  29.        Button b4= (Button)findViewById(R.id.Button04);


  30.         //定义服务链接对象

  31.         final ServiceConnection conn = new ServiceConnection(){


  32.                        @Override

  33.                        public void onServiceConnected(ComponentName name, IBinder service) {

  34.                                Toast.makeText(MainHelloService.this, "ServiceConnection onServiceConnected", Toast.LENGTH_SHORT).show();

  35.                                Log.i(tag, "ServiceConnection onServiceConnected");


  36.                        }


  37.                        @Override