现在的位置: 首页 > 综合 > 正文

Android Service用法讲解与实例

2013年07月16日 ⁄ 综合 ⁄ 共 6804字 ⁄ 字号 评论关闭

 Service是android 系统中的一种组件,它跟Activity的级别差不多,但是他不能自己运行,只能后台运行,并且可以和其他组件进行交互。Service的启动有两种方式:context.startService()context.bindService()。
 
使用context.startService()
启动Service是会会经历:

context.startService()  ->onCreate()- >onStart()->Service running
context.stopService() | ->onDestroy() ->Service stop 
 
如果Service还没有运行,则android先调用onCreate()然后调用onStart();如果Service已经运行,则只调用onStart(),所以一个Service的onStart方法可能会重复调用多次。 
 
stopService的时候直接onDestroy,如果是调用者自己直接退出而没有调用stopService的话,Service会一直在后台运行。该Service的调用者再启动起来后可以通过stopService关闭Service。
 
所以调用startService的生命周期为:onCreate --> onStart(可多次调用) --> onDestroy
 
使用使用context.bindService()启动Service会经历:
context.bindService()->onCreate()->onBind()->Service
running

onUnbind() ->onDestroy()
->Service stop

 
onBind将返回给客户端一个IBind接口实例,IBind允许客户端回调服务的方法,比如得到Service运行的状态或其他操作。这个时候把调用者(Context,例如Activity)会和Service绑定在一起,Context退出了,Srevice就会调用onUnbind->onDestroy相应退出。 
      
所以调用bindService的生命周期为:onCreate --> onBind(只一次,不可多次绑定) --> onUnbind --> onDestory。
 
在Service每一次的开启关闭过程中,只有onStart可被多次调用(通过多次startService调用),其他onCreate,onBind,onUnbind,onDestory在一个生命周期中只能被调用一次。
 
service可以在和多场合的应用中使用,比如播放多媒体的时候用户启动了其他Activity这个时候程序要在后台继续播放,比如检测SD卡上文件的变化,再或者在后台记录你地理信息位置的改变等等,总之服务嘛,总是藏在后头的。
 
下面我做了一个简单的音乐播放的应用,分别使用startService和bindService来启动本地的服务。
而在下一篇《android
service 学习(下) 
》会介绍通过AIDL对Service进行远程调用。

 
下面是整个应用启动界面:
先从使用startService启动Service学起
 
 
首先编写一个Activity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public
class
PlayMusic extendsActivityimplementsOnClickListener {
    privatestaticfinal
String TAG = "PlayMusic";
    privateButton playBtn;
    privateButton stopBtn;
    privateButton pauseBtn;
    privateButton exitBtn;
    privateButton closeBtn;
  
    //....(详见源码)
  
@Override
    publicvoidonClick(View v) {
        intop = -1;
        Intent intent =newIntent("org.allin.android.musicService");
          
        //广播用
//      Intent intent = new Intent("org.allin.android.musicReceiver");
          
        switch(v.getId()) {
        caseR.id.play:
            Log.d(TAG,"onClick: playing muic");
            op =1;
            break;
        caseR.id.stop:
            Log.d(TAG,"onClick: stoping music");
            op =2;
            break;
        caseR.id.pause:
            Log.d(TAG,"onClick: pausing music");
            op =3;
            break;
        caseR.id.close:
            Log.d(TAG,"onClick: close");
            this.finish();
            break;
        caseR.id.exit:
            Log.d(TAG,"onClick: exit");
            op =4;
            stopService(intent);
            this.finish();
            break;
        }
          
        Bundle bundle  =newBundle();
        bundle.putInt("op", op);
        intent.putExtras(bundle);
        startService(intent);
          
//      sendBroadcast(intent);
    }
  
  
}

 
通过重写onClick方法来实现对播放音乐的控制。这里把播放音乐的各种操作用数字的方式通过Intent传递给service。 
构造一个Intent ,ntent intent = new Intent("org.allin.android.musicService");
"org.allin.android.musicService"是在AndroidManifest.xml文件中对service类的定义

1
2
3
4
5
<service android:enabled="true"android:name=".MusicService">
<intent-filter>
<action android:name="org.allin.android.musicService"/>
</intent-filter>
</service>

把操作码放在Bundle中 
Bundle bundle  = new Bundle();
bundle.putInt("op", op);
intent.putExtras(bundle);
最后使用startService(intent);启动服务。 
下面看看Service是怎么实现的。
 
MusicService.java
 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
 * @author allin.dev
 
 */
public
class
MusicService extendsService {
  
    privatestaticfinal
String TAG = "MyService";
    privateMediaPlayer mediaPlayer;
  
    /*
     * (non-Javadoc)
     
     * @see android.app.Service#onBind(android.content.Intent)
     */
    @Override
    publicIBinder onBind(Intent arg0) {
        returnnull;
    }
  
    @Override
    publicvoidonCreate() {
        Log.v(TAG,"onCreate");
        if(mediaPlayer ==null) {
            mediaPlayer = MediaPlayer.create(this, R.raw.tmp);//其中“R.raw.tmp”是一个音频文件:名称为tmp
            mediaPlayer.setLooping(false);
        }
    }
  
    @Override
    publicvoidonDestroy() {
        Log.v(TAG,"onDestroy");
        if(mediaPlayer !=null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }
  
    @Override
    publicvoidonStart(Intent intent,intstartId)
{
        Log.v(TAG,"onStart");
        if(intent !=null) {
            Bundle bundle = intent.getExtras();
            if(bundle !=null) {
  
                intop = bundle.getInt("op");
                switch(op) {
                case1:
                    play();
                    break;
                case2:
                    stop();
                    break;
                case3:
                    pause();
                    break;
                }
  
            }
        }
  
    }
  
    publicvoidplay() {
        if(!mediaPlayer.isPlaying()) {
            mediaPlayer.start();
        }
    }
  
    publicvoidpause() {
        if(mediaPlayer !=null&& mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }
    }
  
    publicvoidstop() {
        if(mediaPlayer !=null) {
            mediaPlayer.stop();
            try{
                // 在调用stop后如果需要再次通过start进行播放,需要之前调用prepare函数
                mediaPlayer.prepare();
            }catch(IOException ex) {
                ex.printStackTrace();
            }
        }
    }
  
}

 
 
服务 使用了系统自带MediaPlayer进行音乐的播放控制。 当调用了startService后服务会先调用onCreate,我们在里面对MediaPlayer进行初始化。接着会调用onStart,可以看到传递给startService()的Intent对象会传递给onStart()方法,这样我们就可以得到intent里面的操作码: 
Iundle bundle = intent.getExtras(); 
int op = bundle.getInt("op");
然后更具定义好的操作码进行相应的f播放操作。启动后界面如下图: 
 
图中的”close”和“exit”是不同的,close只是调用finish()退出当前的Activity,但是Service并没有关掉,音乐会继续播放。而exit就是调用了stopService(intent);来停止服务,Service会调用onDestroy()方法来对mediaPlayer进行停止和释放资源。
 
有时候如果服务只提供一些操作接口,我们也可以通过广播的g方式来启动服务。
首先要定义一个Receiver,并继承BroadcastReceiver,然后在AndroidManifest.xml中进行注册:

1
2
3
4
5
<receiver android:name=".MusicReceiver">
<intent-filter>
<action android:name="org.allin.android.musicReceiver"/>
</intent-filter>
</receiver>

 
Receiver的实现:
 
MusicReceiver.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
 * @author allin.dev
 *
 */
public
class
MusicReceiver extendsBroadcastReceiver {
  
    privatestaticfinal
String TAG = "MusicReceiver";
    @Override
    publicvoidonReceive(Context context, Intent intent) {
        Log.d(TAG,"onReceive");
        Intent it =newIntent("org.allin.android.musicService");
        Bundle bundle = intent.getExtras();
        it.putExtras(bundle);
          
        if(bundle !=null){
            intop = bundle.getInt("op");
            if(op ==4){
                context.stopService(it);
            }else{
                context.startService(it);
            }
        }
          
    }
  
}

 
然后对PlayMusic中的onclick方法进行些改造,把Intent指向Receiver
Intent intent = new Intent("org.allin.android.musicReceiver");
intent中绑定的操作码都不变,再调用sendBroadcast(intent);把intentg广播出去。
MusicReceiver接受到广播后根据操作码进行相应的操作。




接下来的例子就是使用bindService来启动Service
首先一样是写一个Activity

1
2
3
4

抱歉!评论已关闭.