Android Service两种启动方式

来源:互联网 发布:美国驻港总领馆 知乎 编辑:程序博客网 时间:2024/05/20 07:31

1.Context.startService()方式启动 

①Context.startService()方式的生命周期: 启动时,startService –> onCreate() –> onStart()(可多次调用) ,Service running,停止时,stopService –> onDestroy()

note:

Service未被创建并运行时,则android先调用onCreate(),然后调用onStart()。

如果调用startService()方法前服务已经被创建,多次调用startService()方法并不会导致多次创建服务,但会导致多次调用onStart()方法。

同上,如果Service已经运行,则只调用onStart(),所以一个Service的onStart方法可能会重复调用多次。 


采用startService()方法启动的服务,只能调用Context.stopService()方法结束服务,服务结束时会调用onDestroy()。如果是调用者自己(即启动服务的应用或活动)直接退出而没有调用stopService的话,Service会一直在后台运行 Context.startService()方法启动服务,该Service的调用者再启动起来后可以通过stopService关闭Service。

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

2.Context.bindService()方式启动:

①Context.bindService()方式的生命周期: 绑定时,bindService -> onCreate() –> onBind()(只一次,不可多次绑定)->onServiceConnected,Service running, 调用者退出了,即解绑定时,Srevice就会unbindService –>onUnbind() –> onDestory()

note:

Context.bindService()方式启动 Service的方法:绑定Service需要三个参数:bindService(intent, conn, Service.BIND_AUTO_CREATE);第一个:Intent对象第二个:ServiceConnection对象,创建该对象要实现它的onServiceConnected()和 onServiceDisconnected()来判断连接成功或者是断开连接第三个:如何创建Service,一般指定绑定的时候自动创建。

onBind()将返回给客户端一个IBind接口实例,IBind允许客户端回调服务的方法,比如得到Service的实例、运行状态或其他操作。这个时候把调用者(Context,例如Activity)会和Service绑定在一起,Context退出了,Srevice就会调用onUnbind->onDestroy相应退出。 


两种启动方式,在Service每一次的开启关闭过程中,只有onStart可被多次调用(通过多次startService调用),其他onCreate,onBind,onUnbind,onDestory在一个生命周期中只能被调用一次。



下面的应用,分别使用startService和bindService来启动本地的服务。

1.Context.startService()方式启动 

简单的音乐播放

Activity

[java] view plain copy
 print?在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 plain copy
 print?在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 plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. <activity  
  2.     android:name=".service.PlayMusicService"  
  3.     android:label="@string/app_name" />  

注册service

[css] view plain copy
 print?在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>  

2.Context.bindService()方式启动:


[java] view plain copy
  1. package com.dada.test;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.ComponentName;  
  5. import android.content.Context;  
  6. import android.content.Intent;  
  7. import android.content.ServiceConnection;  
  8. import android.os.Bundle;  
  9. import android.os.IBinder;  
  10. import android.util.Log;  
  11. import android.view.View;  
  12. import android.widget.Button;  
  13.   
  14. import com.dada.test.BindService.MyBinder;  
  15.   
  16. public class TestActivity extends Activity {  
  17.       
  18.     private boolean flag;  
  19.     private static final String TAG = "TestActivity";  
  20.     /** Called when the activity is first created. */  
  21.     @Override  
  22.     public void onCreate(Bundle savedInstanceState) {  
  23.         super.onCreate(savedInstanceState);  
  24.         setContentView(R.layout.main);  
  25.           
  26.         super.onCreate(savedInstanceState);   
  27.         setContentView(R.layout.main);   
  28.    
  29.         Button btnStart = (Button) findViewById(R.id.btnStart);   
  30.    
  31.         Button btnStop = (Button) findViewById(R.id.btnStop);   
  32.    
  33.           
  34.         btnStart.setOnClickListener(new View.OnClickListener() {   
  35.             @Override   
  36.             public void onClick(View v) {   
  37.                 //启动service 方式2  
  38.                 bindService();  
  39.             }   
  40.         });   
  41.           
  42.         btnStop.setOnClickListener(new View.OnClickListener() {   
  43.                
  44.             @Override   
  45.             public void onClick(View v) {   
  46.  //停止service 方式2  
  47.                 unBindService();  
  48.             }   
  49.         });   
  50.     }  
  51.       
  52.     //启动service 方式2  
  53.     //  
  54.     private void bindService(){  
  55.         Intent intent = new Intent(TestActivity.this,BindService.class);  
  56.         Log.i(TAG, "bindService()");  
  57.         bindService(intent, conn, Context.BIND_AUTO_CREATE);  //在activity 绑定服务
  58.     }  
  59.       
  60.     private void unBindService(){  
  61.         Log.i(TAG, "unBindService() start....");  
  62.         if(flag == true){  
  63.             Log.i(TAG, "unBindService() flag");  
  64.             unbindService(conn);  
  65.             flag = false;  
  66.         }  
  67.     }  
  68.       
  69. private ServiceConnection conn = new ServiceConnection() {  
  70.           
  71.         @Override  
  72.         public void onServiceDisconnected(ComponentName name) {  
  73.             // TODO Auto-generated method stub  
  74.             Log.i(TAG, "onServiceDisconnected()");  
  75.         }  
  76.           
  77.         @Override  
  78.         public void onServiceConnected(ComponentName name, IBinder service) {  
  79.             // 在服务成功绑定的回调方法onServiceConnected, 会传递过来一个 IBinder对象service
  80.             Log.i(TAG, "onServiceConnected()"); 
  81.             /*通过向下转型得到了 MyBinder 的实例,有了这个实例,活动和服务之间的关系就变得非常紧密了*/ 
  82.             MyBinder binder = (MyBinder)service;  
  83.             /*强制类型转化为自定义的接口类型MyBinder,调用接口里面的方法。*/ 
  84.             BindService bindService = binder.getService1(); 
  85.             bindService.MyMethod();  
  86.             flag = true;  
  87. /*上面这段就实现了活动绑定并启动服务,服务通过其自建内部类MyBinder来调用服务的方法。
  88. activity->bindService方法-》服务的onBind方法(返回自建内部类MyBinder实例)-》ServiceConnection.onServiceConnected()-》通过MyBinder实例 调用服务方法, 现在我们可以在活动中根据具体的场景来调用MyBinder中的任何 public 方法,即实现了指挥服务干什么,服务就去干什么的功能。*/
  89.         }  
  90.     };  
  91. }  

9.3.3 活动和服务进行通信

绑定本地服务调用方法的步骤:

在服务的内部创建一个内部binder类 并提供一个方法,可以间接调用服务的方法
实现服务的onbind方法,返回的就是这个内部binder类
在activity 绑定服务。bindService();
在服务成功绑定的回调方法onServiceConnected, 会传递过来一个 IBinder对象
强制类型转化为自定义的接口类型binder类,调用接口里面的方法。

service

[java] view plain copy
  1. package com.dada.test;  
  2.   
  3. import android.app.Service;  
  4. import android.content.Intent;  
  5. import android.os.Binder;  
  6. import android.os.IBinder;  
  7. import android.util.Log;  
  8.   
  9. public class BindService extends Service {  
  10.   
  11.     private static final String TAG = "BindService";  
  12.     private MyBinder myBinder = new MyBinder();  
  13.     public void MyMethod(){  
  14.         Log.i(TAG, "BindService-->MyMethod()");  
  15.     }  
  16.       
  17.     @Override  
  18.     public IBinder onBind(Intent intent) {  
  19.         Log.i(TAG, "BindService-->onBind()");  
  20.         return myBinder;  
  21.     }  
  22.       
  23.   //在服务的内部创建一个内部类MyBinder 提供一个方法getService1(),可以间接调用服务的方法MyMethod() 
  24.     public class MyBinder extends Binder{
  25.           
  26.         public BindService getService1(){  
  27.             return BindService.this;  
  28.         }  
  29.     }  
  30.       
  31.     
  32.   
  33.     @Override  
  34.     public void onCreate() {  
  35.         Log.i(TAG, "BindService-->onCreate()");  
  36.         super.onCreate();  
  37.     }  
  38.   
  39.     @Override  
  40.     public void onStart(Intent intent, int startId) {  
  41.         Log.i(TAG, "BindService-->onStart()");  
  42.         super.onStart(intent, startId);  
  43.     }  
  44.   
  45.     @Override  
  46.     public void onDestroy() {  
  47.         Log.i(TAG, "BindService-->onDestroy()");  
  48.         super.onDestroy();  
  49.     }  
  50.   
  51.     @Override  
  52.     public boolean onUnbind(Intent intent) {  
  53.         Log.i(TAG, "BindService-->onUnbind()");  
  54.         return super.onUnbind(intent);  
  55.     }  
  56.       
  57. }  

运行日志

点击启动


点击停止


没有打出onServiceDisconnected的日志的原因:

注:SDK上是这么说的:This is called when the connection with the service has been 
unexpectedly disconnected -- that is, its process crashed. Because it is running in our same 
process, we should never see this happen.

所以说,只有在service因异常而断开连接的时候,这个方法才会用到

其他

由于Service 的onStart()方法只有在startService()启动Service的情况下才调用,故使用onStart()的时候要注意这点。

与 Service 通信并且让它持续运行

      如果我们想保持和 Service 的通信,又不想让 Service 随着 Activity 退出而退出呢?你可以先 startService() 然后再 bindService() 。当你不需要绑定的时候就执行 unbindService() 方法,执行这个方法只会触发 Service 的 onUnbind() 而不会把这个 Service 销毁。这样就可以既保持和 Service 的通信,也不会随着 Activity 销毁而销毁了。


另外需要注意,任何一个服务在整个应用程序范围内都是通用的,即 Service 不仅可以和 MainActivity 绑定,还可以和任何一个其他的活动进行绑定,而且在绑定完成后它们都可以获取到相同的 Binder 实例。

http://blog.csdn.net/dada360778512/article/details/7720107
http://blog.csdn.net/sunboy_2050/article/details/7364024
0 0
原创粉丝点击