转载

Service的启动与停止、绑定与解绑

---恢复内容开始---

Service 的意义就在于当软件停止之后还可以在背景中进行运行,换句话也就是说,比如一个音乐播放器,当我们退出音乐播放器的时候,还是希望它在背景中运行,也就是一直播放着音乐,这时候 Service 就派上了大的用途。

Service 的生命周期和 Activity 的生命周期差不多。也有开启和停止。 onCreate() 方法是初始化配置, onDestroy() 是释放所有剩余的资源。 Service 周期是发生在 onCreate() 和 onDestroy() 之间的。

startService() 方法是启动 Service 。

StopService() 方法是停止 Service 。

bindService() 方法是启动 Service 的激活生命周期始于 onBind() 调用,在 onUnbind() 返回时结束。

当一个组件启动 Service 时,是通过 startService() 进行启动 Service, 当 Service 被启动之后, onStartCommand() 方法被调用,并且接收 startService() 方法中传递的 Intent 值。

onStartServiceCommand() 方法必修返回一个整形值。这个整形值是说明了 Service 在系统中如何执行。其中三个比较常用的解释如下:

START_NOT_STICKY: 如果系统在 onStartServiceCommand() 返回后杀死 Service, 那么不会重新创建 Service ,除非有等待的 Intent 要传递。

START_STICKY 如果系统在 onStartServiceCommand() 返回后杀死 Service, 重启 Service, 并且重新调用 onStartServiceCommand(), 但不重新传递最新的 Intent 。

START_REDELIVER_INTENT 如果系统在 onStartServiceCommand() 返回后杀死 Service, 那么重新创建 Service, 并且最近传给 Service 的 Intent 调用 onStartServiceCommand() 。

创建一个 Service 启动周期的实例

  1 public class MyService extends Service{  2       3     //必须实现的方法,作用是用来返回binder对象  4       5       6     //重写onBind()方法,返回Service实例,使Service支持绑定,实现onBind()方法,并且返回MyService实例  7     @Override  8     public IBinder onBind(Intent intent) {  9         // TODO Auto-generated method stub 10         System.out.println("--onBind--"); 11         return null; 12     } 13      14      15     //用于创建Service的方法,只能调用一次 16     public void onCreate(){ 17         super.onCreate(); 18         System.out.println("--onCreate--"); 19  20     //每次启动Service时都会调用这个方法 21     @Override 22     public int onStartCommand(Intent intent, int flags, int startId) { 23         // TODO Auto-generated method stub 24         System.out.println("--onStartCommand--"); 25         return super.onStartCommand(intent, flags, startId); 26     } 27      28     //解绑的时候使用的这个方法 29     @Override 30     public boolean onUnbind(Intent intent) { 31         // TODO Auto-generated method stub 32         System.out.println("--onUnbind--"); 33         return super.onUnbind(intent); 34     } 35      36     //退出或者销毁的时候使用这个方法 37     @Override 38     public void onDestroy() { 39         // TODO Auto-generated method stub 40         serviceRunning = false; 41         System.out.println("--onDestroy--"); 42         super.onDestroy(); 43          44     } 45  46 } 

注意:在测试的时候一定要在 onCreate() 方法中写一个多线程,以便输出,让我们更加的明白。如下:

  1 //用于创建Service的方法,只能调用一次  2     public void onCreate(){  3         super.onCreate();  4         System.out.println("--onCreate--");  5         serviceRunning = true;  6         new Thread(){  7             public void run(){  8                 while(serviceRunning){  9                     System.out.println("--Service运行中--"); 10                     try{ 11                         sleep(1000); 12                     }catch(Exception e){ 13                         e.printStackTrace(); 14                     } 15                 } 16             } 17         }.start(); 18     } 

绑定 Service

绑定 Service 的时候会比较的复杂,其中,看绑定方法 bindService(Intent service, ServiceConnection conn, int flags) 时大家就可以看出。其中 Intent 需要传递 Intent 的值, conn 是 ServiceConnection 的实例, flags 是所需要的一个标示。下面就为大家解析绑定 Service 所需要的三个步骤:

第一步:需要在 Service 中创建一个 Binder 接口,并且实现:

  1. 包含客户端可以调用 public 方法

  2. 或返回当前 Service 的实例 -- 也包含客户端可以调用的 Public 方法

  3. 或返回 Service 持有的其他类型的实例 -- 也包含客户端可以调用的 Public 方法

代码如下:

public class MyBinder extends Binder{   MyService getService(){    return MyService.this;   }  }

第二步:在 onBind() 中返回 Binder 实例。

代码如下:

 1 //必须实现的方法,作用是用来返回binder对象 2 //重写onBind()方法,返回Service实例,使Service支持绑定,实现onBind()方法,并且返回MyService实例 3     @Override 4     public IBinder onBind(Intent intent) { 5         // TODO Auto-generated method stub 6         System.out.println("--onBind--"); 7         return null; 8     } 

第三步:在客户端中,从 onServiceConnected() 回调方法中接收这个 Binder, 并且使用 Binder 包含的 Service 提供的方法。

比如:

  1 public class MyServiceConn implements ServiceConnection{  2   3     MyService.MyBinder binder = null;  4       5     @Override  6     public void onServiceConnected(ComponentName name, IBinder service) {  7         // TODO Auto-generated method stub  8         binder = (MyService.MyBinder)service;  9     } 10  11     @Override 12     public void onServiceDisconnected(ComponentName name) { 13         // TODO Auto-generated method stub 14         binder = null; 15     } 16  17 } 

注意:一定要在客户端中声明这个实例:

1 final MyServiceConn myserviceconn = new MyServiceConn();

客户端在合适的时候也可以进行解绑:

 1 //解除绑定的Service 2         unbind.setOnClickListener(new OnClickListener() { 3              4             @Override 5             public void onClick(View v) { 6                 // TODO Auto-generated method stub 7                 unbindService(myserviceconn); 8             } 9         }); 

上述就把 Service 的启动、停止、绑定、解绑就完成了,下面的则是客户端的一些的代码:

  1 import android.app.Activity;  2 import android.content.ComponentName;  3 import android.content.Context;  4 import android.content.Intent;  5 import android.content.ServiceConnection;  6 import android.os.Bundle;  7 import android.os.IBinder;  8 import android.view.View;  9 import android.view.View.OnClickListener; 10 import android.widget.Button; 11  12 public class MainActivity extends Activity { 13  14     private Button start; 15     private Button stop; 16     private Button bind; 17     private Button unbind; 18     private Intent intent; 19      20     @Override 21     protected void onCreate(Bundle savedInstanceState) { 22         super.onCreate(savedInstanceState); 23         setContentView(R.layout.activity_main); 24         start = (Button)findViewById(R.id.btn1); 25         stop = (Button)findViewById(R.id.btn2); 26         bind = (Button)findViewById(R.id.btn3); 27         unbind = (Button)findViewById(R.id.btn4); 28          29         final MyServiceConn myserviceconn = new MyServiceConn(); 30          31         //给按钮设置事件,以便监听Service中的变化 32         //开启service 33         start.setOnClickListener(new OnClickListener() { 34              35             @Override 36             public void onClick(View v) { 37                 // TODO Auto-generated method stub 38                 intent = new Intent(getApplicationContext(),MyService.class); 39                 startService(intent); 40             } 41         }); 42          43         //结束Service 44         stop.setOnClickListener(new OnClickListener() { 45              46             @Override 47             public void onClick(View v) { 48                 // TODO Auto-generated method stub 49                 stopService(intent); 50             } 51         }); 52          53         //绑定service服务 54         bind.setOnClickListener(new OnClickListener() { 55              56             @Override 57             public void onClick(View v) { 58                 // TODO Auto-generated method stub 59                 bindService(intent,myserviceconn,Context.BIND_AUTO_CREATE); 60             } 61         }); 62          63         //解除绑定的Service 64         unbind.setOnClickListener(new OnClickListener() { 65              66             @Override 67             public void onClick(View v) { 68                 // TODO Auto-generated method stub 69                 unbindService(myserviceconn); 70             } 71         }); 72     } 73  74  75 } 

XML 文件的代码(只是一些简单的按钮,就不解释了):

  1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  2     xmlns:tools="http://schemas.android.com/tools"  3     android:id="@+id/LinearLayout1"  4     android:layout_width="match_parent"  5     android:layout_height="match_parent"  6     android:orientation="vertical"  7     tools:context=".MainActivity" >  8   9     <TextView 10         android:layout_width="wrap_content" 11         android:layout_height="wrap_content" 12         android:text="@string/service" /> 13  14     <Button 15         android:id="@+id/btn1" 16         android:layout_width="wrap_content" 17         android:layout_height="wrap_content" 18         android:text="StartService" /> 19  20     <Button 21         android:id="@+id/btn2" 22         android:layout_width="wrap_content" 23         android:layout_height="wrap_content" 24         android:text="StopService" /> 25  26     <Button 27         android:id="@+id/btn3" 28         android:layout_width="wrap_content" 29         android:layout_height="wrap_content" 30         android:text="bindService" /> 31  32     <Button 33         android:id="@+id/btn4" 34         android:layout_width="wrap_content"  35         android:layout_height="wrap_content" 36         android:text="unBindService" /> 37  38 </LinearLayout> 

一定要注意在 AndroidManifest.xml 文件中加上权限:

 1 <service            android:name="com.example.servicetest.MyService">    2  </service> 

到这里就完了,有什么不懂或者不对的地方可以留言,至于截图,上述的代码比较详细,我这里就不贴出了。

---恢复内容结束---

原文  http://www.cnblogs.com/bingbingliang-xiaomonv/p/5204680.html
正文到此结束
Loading...