Service(一)简介

来源:互联网 发布:java 代码生成 方式 编辑:程序博客网 时间:2024/05/16 12:01

一、 Service简介

Service是android 系统中的四大组件之一(Activity、Service、BroadcastReceiver、ContentProvider),它跟Activity的级别差不多,但不能自己运行只能后台运行,并且可以和其他组件进行交互。service可以在很多场合的应用中使用,比如播放多媒体的时候用户启动了其他Activity这个时候程序要在后台继续播放,比如检测SD卡上文件的变化,再或者在后台记录你地理信息位置的改变等等,总之服务总是藏在后台的。

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


二、 Service启动流程

context.startService() 启动流程:

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()启动流程:

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生命周期 

Service的生命周期并不像Activity那么复杂,它只继承了onCreate()、onStart()、onDestroy()三个方法

当我们第一次启动Service时,先后调用了onCreate()、onStart()这两个方法;当停止Service时,则执行onDestroy()方法。

这里需要注意的是,如果Service已经启动了,当我们再次启动Service时,不会在执行onCreate()方法,而是直接执行onStart()方法。

它可以通过Service.stopSelf()方法或者Service.stopSelfResult()方法来停止自己,只要调用一次stopService()方法便可以停止服务,无论调用了多少次的启动服务方法。


四、 Service示例

下面我做了一个简单的音乐播放的应用,分别使用startService和bindService来启动本地的服务。

Activity

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. public class PlayMusicService extends Activity implements OnClickListener {  
  2.   
  3.     private Button playBtn;  
  4.     private Button stopBtn;  
  5.     private Button pauseBtn;  
  6.     private Button exitBtn;  
  7.     private Button closeBtn;  
  8.   
  9.     private Intent intent;  
  10.       
  11.     @Override  
  12.     public void onCreate(Bundle savedInstanceState) {  
  13.         super.onCreate(savedInstanceState);  
  14.         setContentView(R.layout.music_service);  
  15.   
  16.         playBtn = (Button) findViewById(R.id.play);  
  17.         stopBtn = (Button) findViewById(R.id.stop);  
  18.         pauseBtn = (Button) findViewById(R.id.pause);  
  19.         exitBtn = (Button) findViewById(R.id.exit);  
  20.         closeBtn = (Button) findViewById(R.id.close);  
  21.           
  22.         playBtn.setOnClickListener(this);  
  23.         stopBtn.setOnClickListener(this);  
  24.         pauseBtn.setOnClickListener(this);  
  25.         exitBtn.setOnClickListener(this);  
  26.         closeBtn.setOnClickListener(this);  
  27.   
  28.     }  
  29.   
  30.     @Override  
  31.     public void onClick(View v) {  
  32.         int op = -1;  
  33.         intent = new Intent("com.homer.service.musicService");  
  34.   
  35.         switch (v.getId()) {  
  36.         case R.id.play:                             // play music  
  37.             op = 1;  
  38.             break;  
  39.         case R.id.stop:                             // stop music  
  40.             op = 2;  
  41.             break;  
  42.         case R.id.pause:                            // pause music  
  43.             op = 3;  
  44.             break;  
  45.         case R.id.close:                            // close activity  
  46.             this.finish();  
  47.             break;  
  48.         case R.id.exit:                             // stopService  
  49.             op = 4;  
  50.             stopService(intent);  
  51.             this.finish();  
  52.             break;  
  53.         }  
  54.   
  55.         Bundle bundle = new Bundle();  
  56.         bundle.putInt("op", op);  
  57.         intent.putExtras(bundle);  
  58.           
  59.         startService(intent);                           // startService  
  60.     }  
  61.       
  62.     @Override  
  63.     public void onDestroy(){  
  64.         super.onDestroy();  
  65.   
  66.         if(intent != null){  
  67.             stopService(intent);  
  68.         }  
  69.     }  
  70. }  


Service

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. public class MusicService extends Service {  
  2.     private static final String TAG = "MyService";  
  3.       
  4.     private MediaPlayer mediaPlayer;  
  5.   
  6.     @Override  
  7.     public IBinder onBind(Intent arg0) {  
  8.         return null;  
  9.     }  
  10.   
  11.     @Override  
  12.     public void onCreate() {  
  13.         Log.v(TAG, "onCreate");  
  14.         Toast.makeText(this"show media player", Toast.LENGTH_SHORT).show();  
  15.   
  16.         if (mediaPlayer == null) {  
  17.             mediaPlayer = MediaPlayer.create(this, R.raw.tmp);  
  18.             mediaPlayer.setLooping(false);  
  19.         }  
  20.     }  
  21.   
  22.     @Override  
  23.     public void onDestroy() {  
  24.         Log.v(TAG, "onDestroy");  
  25.         Toast.makeText(this"stop media player", Toast.LENGTH_SHORT);  
  26.         if (mediaPlayer != null) {  
  27.             mediaPlayer.stop();  
  28.             mediaPlayer.release();  
  29.         }  
  30.     }  
  31.   
  32.     @Override  
  33.     public void onStart(Intent intent, int startId) {  
  34.         Log.v(TAG, "onStart");  
  35.         if (intent != null) {  
  36.             Bundle bundle = intent.getExtras();  
  37.             if (bundle != null) {  
  38.                 int op = bundle.getInt("op");  
  39.                 switch (op) {  
  40.                 case 1:  
  41.                     play();  
  42.                     break;  
  43.                 case 2:  
  44.                     stop();  
  45.                     break;  
  46.                 case 3:  
  47.                     pause();  
  48.                     break;  
  49.                 }  
  50.             }  
  51.         }  
  52.     }  
  53.   
  54.     public void play() {  
  55.         if (!mediaPlayer.isPlaying()) {  
  56.             mediaPlayer.start();  
  57.         }  
  58.     }  
  59.   
  60.     public void pause() {  
  61.         if (mediaPlayer != null && mediaPlayer.isPlaying()) {  
  62.             mediaPlayer.pause();  
  63.         }  
  64.     }  
  65.   
  66.     public void stop() {  
  67.         if (mediaPlayer != null) {  
  68.             mediaPlayer.stop();  
  69.             try {  
  70.                 mediaPlayer.prepare();  // 在调用stop后如果需要再次通过start进行播放,需要之前调用prepare函数  
  71.             } catch (IOException ex) {  
  72.                 ex.printStackTrace();  
  73.             }  
  74.         }  
  75.     }  
  76. }  

AndroidManifest.xml

注册activity

[css] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <activity  
  2.     android:name=".service.PlayMusicService"  
  3.     android:label="@string/app_name" />  

注册service

[css] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <service  
  2.     android:name=".service.MusicService"  
  3.     android:enabled="true" >  
  4.     <intent-filter>  
  5.         <action android:name="com.homer.service.musicService" />  
  6.     </intent-filter>  
  7. </service>  
0 0
原创粉丝点击