从头学Android之Service初步二

在上一篇,咱们学习了经过startService来启动Service,因为篇幅过长,因此这一篇是接上一篇的java

2、bindService方法启动Serviceandroid

先看bindSerivce(Intent service,ServiceConnection conn,int flags)函数app

参数说明:ide

service:经过该参数也就是Intent咱们能够启动指定的Service函数

conn:该参数是一个ServiceConnection对象,这个对角用于监听访问者(也能够说成是客户端)与Service之间的链接状况,当访问者与Service链接成功时将回调ServiceConnection对象的onServiceConnected(ComponentName name,Ibinder service)方法;若是断开将回调onServiceDisConnected(CompontName name)方法oop

flags:指定绑定时是否自动建立Service。学习

步骤:ui

一、  新建一个类继承于Service类,重写onBind()、onCreate()、onUnBind()、onDestory()方法。再在这个类里声明一个Ibinder的子类对象用于提供于客户端,同时能够定义一些成员变量,客户端能够获取到这个成员变量属性this

二、  在AndroidMainfest.xml文件中注册这个Service编码

三、  在Activity里经过bindService绑定Service

示例代码:

 

[java]   view plain copy print ?
<EMBED id=ZeroClipboardMovie_1 height=14 name=ZeroClipboardMovie_1 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer width=29 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=1&width=29&height=14" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">
  1. package com.jiahui.serviceDemo;  
  2.   
  3. import android.app.Service;  
  4. import android.content.Intent;  
  5. import android.os.Binder;  
  6. import android.os.IBinder;  
  7.   
  8. public class MyService extends Service {  
  9.   
  10.     private int count;  
  11.   
  12.     private boolean quit;  
  13.   
  14.     private MyBinder binder = new MyBinder();  
  15.   
  16.     // 新建一个Binder对象用于提供给客户端  
  17.     public class MyBinder extends Binder {  
  18.   
  19.         public int getCount() {  
  20.             return count;  
  21.         }  
  22.     }  
  23.   
  24.     @Override  
  25.     public IBinder onBind(Intent intent) {  
  26.         System.out.println("----onBind-----");  
  27.         // 返回给客户端一个Binder对象  
  28.         return binder;  
  29.     }  
  30.   
  31.     @Override  
  32.     public void onCreate() {  
  33.         System.out.println("----onCreate-----");  
  34.   
  35.         // 启动一条线程修改为员变量属性  
  36.         new Thread() {  
  37.             @Override  
  38.             public void run() {  
  39.                 while (!quit) {  
  40.                     try {  
  41.                         Thread.sleep(1000);  
  42.                     } catch (Exception e) {  
  43.                       
  44.                     }  
  45.                     count++;  
  46.                 }  
  47.             }  
  48.   
  49.         }.start();  
  50.   
  51.     }  
  52.   
  53.     @Override  
  54.     public void onDestroy() {  
  55.         this.quit = true;  
  56.         System.out.println("----onDestory-----");  
  57.         super.onDestroy();  
  58.     }  
  59.   
  60.     @Override  
  61.     public boolean onUnbind(Intent intent) {  
  62.         System.out.println("----onUnbind-----");  
  63.         return super.onUnbind(intent);  
  64.     }  
  65.   
  66. }  


 

 

MainActivty

[java]   view plain copy print ?
<EMBED id=ZeroClipboardMovie_2 height=14 name=ZeroClipboardMovie_2 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer width=29 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=2&width=29&height=14" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">
  1. package com.jiahui.serviceDemo;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.ComponentName;  
  5. import android.content.Intent;  
  6. import android.content.ServiceConnection;  
  7. import android.os.Bundle;  
  8. import android.os.IBinder;  
  9. import android.view.View;  
  10. import android.widget.Button;  
  11. import android.widget.Toast;  
  12.   
  13. public class MainActivity extends Activity {  
  14.   
  15.     private Button btnBind;  
  16.     private Button btnUnBind;  
  17.     private Button btnGetData;  
  18.   
  19.     MyService.MyBinder binder;  
  20.     // 定义一个ServiceConnection对象  
  21.     private ServiceConnection conn = new ServiceConnection() {  
  22.   
  23.         // 当客户端与Service断开链接时  
  24.         @Override  
  25.         public void onServiceDisconnected(ComponentName name) {  
  26.             System.out.println("---onServiceDisconnected----");  
  27.   
  28.         }  
  29.   
  30.         // 当客户端与Service创建链接时  
  31.         @Override  
  32.         public void onServiceConnected(ComponentName name, IBinder service) {  
  33.             System.out.println("---onServiceConnected----");  
  34.             binder = (MyService.MyBinder) service;  
  35.         }  
  36.     };  
  37.   
  38.     public void onCreate(Bundle savedInstanceState) {  
  39.           
  40.         super.onCreate(savedInstanceState);  
  41.         setContentView(R.layout.main);  
  42.   
  43.         btnBind = (Button) findViewById(R.id.btnBind);  
  44.         btnUnBind = (Button) findViewById(R.id.btnUnBind);  
  45.         btnGetData = (Button) findViewById(R.id.btnGetData);  
  46.         final Intent intent = new Intent();  
  47.         intent.setAction("com.jiahui.myservice");  
  48.   
  49.         btnBind.setOnClickListener(new View.OnClickListener() {  
  50.   
  51.             @Override  
  52.             public void onClick(View v) {  
  53.   
  54.                 // 绑定Service  
  55.                 bindService(intent, conn, BIND_AUTO_CREATE);  
  56.             }  
  57.         });  
  58.   
  59.         btnUnBind.setOnClickListener(new View.OnClickListener() {  
  60.   
  61.             @Override  
  62.             public void onClick(View v) {  
  63.                 // 解除绑定  
  64.                 unbindService(conn);  
  65.   
  66.             }  
  67.         });  
  68.   
  69.         //获取数据  
  70.         btnGetData.setOnClickListener(new View.OnClickListener() {  
  71.             @Override  
  72.             public void onClick(View v) {  
  73.                 // 获取数据  
  74.                 Toast.makeText(MainActivity.this,  
  75.                         "Service的 count值为" + binder.getCount(),  
  76.                         Toast.LENGTH_LONG).show();  
  77.             }  
  78.         });  
  79.   
  80.     }  
  81. }  


 

实现效果:

点击”bindService”按钮

点击” 获取Service里的数据”按钮

点击“unBindService”按钮

因此也能够经过上图知道bindService的生命周期

bindService会经历onCreate()-->onBind()-->onUnbind()-->onDestory

 

如何去理解这种通讯方式?

个人理解是bindService这一方咱们能够看做是客户端,而后客户端调用bindService()方法去绑定一个Service,Service给咱们返回一个Binder对象用于客户端与Serivce通讯,而这个Binder对象咱们能够在客户端的ServiceConnection对象里的一个onServiceConnected()方法取到这个Binder对象,这样咱们就也能取到Service里的数据了

贴上一张图更加方便你们理解:

因此总结:

bindService与startService 的区别:

1. 生命周期 : startService() 方式启动 , Service 是经过接受 Intent 而且会经历 onCreate()和 onStart() 。当用户在发出意图使之销毁时会经历 onDestroy () ,而 bindService () 方

式启动 , 与 Activity 绑定的时候 , 会经历 onCreate() 和 onBind () , 而当 Activity 被销毁的时候, Service 会先调用 onUnbind () 而后是 onDestroy () 。

2. 控制方式 :前者的控制方式须要使用固定的方法,对 Service 进行单一的操做。然后者

因为与 Activity 绑定 , 不用考虑其生命周期问题 , 而且从发送 Intent 的被动操做 , 变为能够主动对 Service 对象进行操做,咱们甚至能够创建一个 Handler 类,对 Service 进行相关的操做。大大增强了 Service 的灵活性、可操做性。

 

总结 : 对于简单的应用 startService() 启动方式能带来更少的代码 , 简单的操做 。 对于复杂的应用 bindService () 方式,虽然带来的更多的编码,但同时也带来了更好的可操做性,使其使用起来更像 Activity 。

 如需转载引用请注明出处:http://blog.csdn.net/jiahui524

11
相关文章
相关标签/搜索