Android开发教程:Service简析


简介

Service是Android 四大组件之一,它跟Activity的级别差不多,但是他不能自己运行,只能后台运行,并且可以和其他组件进行交互。

Service的启动有两种方式:context.startService()和context.bindService()。
 
1.使用context.startService()启动Service

生命周期:
context.startService()  ->onCreate()- >onStart()->Servicerunning->context.stopService()

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

生命周期:

context.bindService()->onCreate()->onBind()->Service running

onUnbind() ->onDestroy() ->Servicestop

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卡上文件的变化,再或者在后台记录你地理信息位置的改变等等。

下面是一个实际的例子:

这个例子有四个类:



其中和Service有关的是PlayMusicActivit.java和MusicService.java

PlayMusicActivit是一个启动界面上面有四个按钮分别来启动、暂停、停止和关闭Service

MusicService是一个实际的Service类

另外连个类是用来做通知的,将在通知里面讲解

  1. package com.my;  
  2.   
  3. import android.app.Activity;  
  4. import android.app.NotificationManager;  
  5. import android.content.Intent;  
  6. import android.os.Bundle;  
  7. import android.view.View;  
  8. import android.widget.Button;  
  9.   
  10. public class PlayMusicActivity extends Activity {  
  11.     private static final int NOTIFICATION_ID = 10001;  
  12.   
  13.     private Button playBtn;  
  14.     private Button stopBtn;  
  15.     private Button pauseBtn;  
  16.     private Button closeBtn;  
  17.     private Button exitBtn;  
  18.   
  19.     @Override  
  20.     public void onCreate(Bundle savedInstanceState) {  
  21.         super.onCreate(savedInstanceState);  
  22.         setContentView(R.layout.main);  
  23.   
  24.         playBtn = (Button) findViewById(R.id.play_btn);  
  25.         stopBtn = (Button) findViewById(R.id.stop_btn);  
  26.         pauseBtn = (Button) findViewById(R.id.pause_btn);  
  27.         closeBtn = (Button) findViewById(R.id.close_btn);  
  28.         exitBtn = (Button) findViewById(R.id.exit_btn);  
  29.   
  30.         playBtn.setOnClickListener(new View.OnClickListener() {  
  31.   
  32.             @Override  
  33.             public void onClick(View v) {  
  34.                 Intent service = new Intent("com.my.musicService");  
  35.                 Bundle value = new Bundle();  
  36.                 value.putInt("opt"1);  
  37.                 service.putExtras(value);  
  38.                 startService(service);  
  39.                   
  40.             }  
  41.         });  
  42.         stopBtn.setOnClickListener(new View.OnClickListener() {  
  43.   
  44.             @Override  
  45.             public void onClick(View v) {  
  46.                 Intent service = new Intent("com.my.musicService");  
  47.                 Bundle value = new Bundle();  
  48.                 value.putInt("opt"2);  
  49.                 service.putExtras(value);  
  50.                 startService(service);  
  51.             }  
  52.         });  
  53.         pauseBtn.setOnClickListener(new View.OnClickListener() {  
  54.   
  55.             @Override  
  56.             public void onClick(View v) {  
  57.                 Intent service = new Intent("com.my.musicService");  
  58.                 Bundle value = new Bundle();  
  59.                 value.putInt("opt"3);  
  60.                 service.putExtras(value);  
  61.                 startService(service);  
  62.             }  
  63.         });  
  64.         closeBtn.setOnClickListener(new View.OnClickListener() {  
  65.   
  66.             @Override  
  67.             public void onClick(View v) {  
  68.                 PlayMusicActivity.this.finish();  
  69.             }  
  70.         });  
  71.         exitBtn.setOnClickListener(new View.OnClickListener() {  
  72.   
  73.             @Override  
  74.             public void onClick(View v) {  
  75.                 Intent service = new Intent("com.my.musicService");  
  76.                 stopService(service);  
  77.                 final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  
  78.                 nm.cancel(NOTIFICATION_ID);  
  79.                 PlayMusicActivity.this.finish();  
  80.             }  
  81.         });  
  82.     }  
  83.   
  84. }  
 
  1. package com.my;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import android.app.Service;  
  6. import android.content.Intent;  
  7. import android.media.MediaPlayer;  
  8. import android.os.Bundle;  
  9. import android.os.IBinder;  
  10. import android.util.Log;  
  11.   
  12. public class MusicService extends Service {  
  13.     private static final String TAG = "MusicService";  
  14.     private MediaPlayer mediaPlayer;  
  15.   
  16.     @Override  
  17.     public IBinder onBind(Intent intent) {  
  18.         return null;  
  19.     }  
  20.   
  21.     @Override  
  22.     public void onCreate() {  
  23.         Log.i(TAG, "create service");  
  24.         super.onCreate();  
  25.         if(mediaPlayer == null) {  
  26.             mediaPlayer = MediaPlayer.create(this, R.raw.he);  
  27.             mediaPlayer.setLooping(false);  
  28.         }  
  29.     }  
  30.       
  31.     @Override  
  32.     public void onDestroy() {  
  33.         Log.i(TAG, "destroy service");  
  34.         super.onDestroy();  
  35.         if(mediaPlayer != null) {  
  36.             mediaPlayer.stop();  
  37.             mediaPlayer.release();  
  38.         }  
  39.     }  
  40.       
  41.     @Override  
  42.     public void onStart(Intent intent, int startId) {  
  43.         Log.i(TAG, "start service");  
  44.         super.onStart(intent, startId);  
  45.         if(intent != null) {  
  46.             Bundle bundle = intent.getExtras();  
  47.             if(bundle != null) {  
  48.                 int opt = bundle.getInt("opt");  
  49.                 switch(opt) {  
  50.                 case 1:  
  51.                     play();break;  
  52.                 case 2:  
  53.                     stop();break;  
  54.                 case 3:  
  55.                     pause();break;  
  56.                 }  
  57.             }  
  58.         }  
  59.     }  
  60.       
  61.     private void play() {  
  62.         if(!mediaPlayer.isPlaying()) {  
  63.             mediaPlayer.start();  
  64.         }  
  65.     }  
  66.       
  67.     private void pause() {  
  68.         if(mediaPlayer != null && mediaPlayer.isPlaying()) {  
  69.             mediaPlayer.pause();  
  70.         }  
  71.     }  
  72.       
  73.     private void stop() {  
  74.         if(mediaPlayer != null) {  
  75.             mediaPlayer.stop();  
  76.             try {  
  77.                 mediaPlayer.prepare();  
  78.             } catch (IllegalStateException e) {  
  79.                 e.printStackTrace();  
  80.             } catch (IOException e) {  
  81.                 e.printStackTrace();  
  82.             }  
  83.         }  
  84.     }  
  85.       
  86. }  

相关内容