Chinaunix首页 | 论坛 | 博客
  • 博客访问: 280406
  • 博文数量: 28
  • 博客积分: 11
  • 博客等级: 民兵
  • 技术积分: 895
  • 用 户 组: 普通用户
  • 注册时间: 2012-11-19 19:50
个人简介

不畏浮云遮望眼,只缘身在最高层

文章分类

全部博文(28)

文章存档

2014年(1)

2013年(27)

分类: Android平台

2013-05-09 19:10:33

Service:没有可视化的UI,能长时间的运行在后台,创建的Service不能自动运行,需要其他组件来指定启动它,开发一个Service需要在AndroidManifest.xml中注册,注册代码为:
     Service的生命周期如下图:


有两种方式可以启动Service,分别是 startService() 和bindService(),
示例代码如下:设置四个按钮,用于用于startService、stopService、bindService和unbindService。通过观察LogCat的输出,可以了解Service的生命周期!
1.strings.xml中代码:

点击(此处)折叠或打开

  1. <?xml version=\"1.0\" encoding=\"utf-8\"?>
  2. <resources>
  3.     <string name=\"app_name\">MyServiceDemo</string>
  4.     <string name=\"servicetest\">Service Test</string>
  5.     <string name=\"startservice\">Service start</string>
  6.     <string name=\"stopservice\">Service stop</string>
  7.     <string name=\"bindservice\">Service bind</string>
  8.     <string name=\"unbindservice\">Service unbind</string>
  9. </resources>

2.layout中的activity_main.xml代码:

点击(此处)折叠或打开

  1. <LinearLayout xmlns:android=\"\"
  2.     xmlns:tools=\"\"
  3.     android:layout_width=\"match_parent\"
  4.     android:layout_height=\"match_parent\"
  5.     android:orientation=\"vertical\"
  6.      >
  7.     <TextView
  8.         android:layout_width=\"wrap_content\"
  9.         android:layout_height=\"wrap_content\"
  10.         android:text=\"@string/servicetest\"
  11.         />
  12.     <Button
  13.      android:layout_width=\"wrap_content\"
  14.         android:layout_height=\"wrap_content\"
  15.         android:text=\"@string/startservice\"
  16.         android:id=\"@+id/startservice\"
  17.      />
  18.     <Button
  19.      android:layout_width=\"wrap_content\"
  20.         android:layout_height=\"wrap_content\"
  21.          android:text=\"@string/stopservice\"
  22.          android:id=\"@+id/stopservice\"
  23.      />
  24.     <Button
  25.      android:layout_width=\"wrap_content\"
  26.         android:layout_height=\"wrap_content\"
  27.          android:text=\"@string/bindservice\"
  28.          android:id=\"@+id/bindservice\"
  29.      />        
  30.      <Button
  31.      android:layout_width=\"wrap_content\"
  32.         android:layout_height=\"wrap_content\"
  33.          android:text=\"@string/unbindservice\"
  34.          android:id=\"@+id/unbindservice\"
  35.      />
  36. </LinearLayout>
3.接下来是MainActivity.java的代码:


点击(此处)折叠或打开

  1. package com.example.myservicedemo;

  2. import android.os.Bundle;
  3. import android.os.IBinder;
  4. import android.app.Activity;
  5. import android.content.ComponentName;
  6. import android.content.Context;
  7. import android.content.Intent;
  8. import android.content.ServiceConnection;
  9. import android.view.View;
  10. import android.widget.Button;
  11. import android.view.View.OnClickListener;


  12. /**
  13.  *
  14.  * @author zt
  15.  * 关于Service生命周期
  16.  *
  17.  */
  18. public class MainActivity extends Activity {

  19.     public MyService myservice;
  20.     public static boolean flag=false;
  21.     
  22.     @Override
  23.     protected void onCreate(Bundle savedInstanceState) {
  24.         super.onCreate(savedInstanceState);
  25.         setContentView(R.layout.activity_main);
  26. //        intent=new Intent("com.kennan.android.music");
  27.         
  28.         //监听start Service按钮
  29.         Button startbut=(Button)this.findViewById(R.id.startservice);
  30.         startbut.setOnClickListener(new OnClickListener(){
  31.             @Override
  32.             public void onClick(View v) {
  33.                 
  34.                 System.out.println("Click start Service..");
  35.                 Intent intent=new Intent(MainActivity.this,MyService.class);
  36.                 startService(intent);//启动服务        
  37.             }    
  38.             
  39.         });
  40.         //监听stop Service按钮
  41.         Button stopbut=(Button)this.findViewById(R.id.stopservice);
  42.         stopbut.setOnClickListener(new OnClickListener(){

  43.             @Override
  44.             public void onClick(View v) {
  45.                 
  46.                 System.out.println("Click stop Service..");
  47.                 Intent intent=new Intent(MainActivity.this,MyService.class);
  48.                 stopService(intent);//停止服务
  49.             }            
  50.         });
  51.         /**
  52.          * 特别注意:
  53. 1、Service.onBind如果返回null,则调用 bindService 会启动 Service,但不会连接上 Service,
  54. 因此 ServiceConnection.onServiceConnected 不会被调用,但你任然需要使用 unbindService 函数断开它,
  55.  这样 Service 才会停止。
  56.          */
  57.         //监听Bind Service按钮
  58.         Button bindbut=(Button) this.findViewById(R.id.bindservice);
  59.         bindbut.setOnClickListener(new OnClickListener(){

  60.             @Override
  61.             public void onClick(View v) {
  62.                 
  63.                 System.out.println("Click bind Service..");
  64.                 Intent intent=new Intent(MainActivity.this,MyService.class);
  65.                 bindService(intent,myserviceconnection,Context.BIND_AUTO_CREATE);//绑定服务            
  66.             }
  67.             
  68.         });
  69.         
  70.         //监听unBind Service按钮
  71.         Button unbindbut=(Button) this.findViewById(R.id.unbindservice);
  72.         unbindbut.setOnClickListener(new OnClickListener(){

  73.             @Override
  74.             public void onClick(View v) {
  75.                 System.out.println("Click unbind Service..");        
  76.                 unbindService(myserviceconnection);        //解绑服务
  77.             }
  78.                     
  79.         });        
  80.       
  81.     }
  82.     /**
  83.      * 当bindService之后,服务启动后会调用onBind()方法,返回一个Binder远程对象,
  84.      *服务连接上,会调用onServiceConnected()方法, 通过getService()获得服务接口
  85.      */
  86.     private ServiceConnection myserviceconnection=new ServiceConnection()
  87.     {

  88.         @Override
  89.         public void onServiceConnected(ComponentName intent, IBinder service) {
  90.             
  91.             System.out.println("Server is connected");
  92.             myservice=((MyService.MyBinder)service).getService();//获取服务接口
  93.             
  94.         }

  95.         @Override
  96.         public void onServiceDisconnected(ComponentName arg0) {
  97.             
  98.             System.out.println("Server is disconnected");
  99.             myservice=null;
  100.         }        
  101.     };
  102. }


4.MyService继承于Service,代码如下:

点击(此处)折叠或打开

  1. package com.example.myservicedemo;

  2. import android.app.Service;
  3. import android.content.Intent;
  4. import android.os.Binder;
  5. import android.os.IBinder;

  6. public class MyService extends Service {
  7.         
  8.     /**
  9.      * 代码关键之处,在于 onBind(Intent) 这个方法 返回了一个实现了 IBinder 接口的对象,
  10.      * 这个对象将用于绑定Service 的 MainActivity 与 MyService 通信。
  11.      */
  12.     private IBinder binder=new MyBinder();
  13.     @Override
  14.     public IBinder onBind(Intent intent) {
  15.         
  16.         System.out.println("onBind operation");
  17.         return binder;
  18.     }
  19.     
  20.     @Override
  21.     public boolean onUnbind(Intent intent)
  22.     {
  23.         System.out.println("onUnBind operation");
  24.         return super.onUnbind(intent);
  25.     }
  26.     
  27.     @Override
  28.     public void onCreate()
  29.     {
  30.         System.out.println("onCreate operation");
  31.         super.onCreate();
  32.     }
  33.     
  34.     @Override
  35.     public int onStartCommand(Intent intent,int flags,int startId)
  36.     {
  37.         System.out.println("onStartCommand operation");
  38.         return super.onStartCommand(intent, flags, startId);
  39.         
  40.     }
  41.     
  42.     @Override
  43.     public void onStart(Intent intent,int startId)
  44.     {
  45.         System.out.println("onStart operation");
  46.         super.onStart(intent, startId);
  47.     }
  48.     
  49.     @Override
  50.     public void onDestroy()
  51.     {
  52.         System.out.println("onDestroy operation");
  53.     
  54.         super.onDestroy();
  55.         
  56.     }
  57.     
  58.     //返回MyService对象
  59.     public class MyBinder extends Binder{
  60.      public MyService getService()
  61.      {
  62.          return MyService.this;
  63.      }
  64.     }
  65. }








5.模拟器界面:


6.程序运行结果如下:
A.点击Service start按钮后:
B.再次点击Service start按钮后:
发现再次点击Service start按钮后,不再执行onCreate(),

C:点击Service stop按钮后:

D:点击Service bind按钮后:
可以看到调用onBind()方法后,MainActivity自动调用 ServiceConnection接口中的onServiceConnected()方法,告诉主线程,服务已经连接上了!
E:多次点击Service bind按钮后:
发现多次绑定Service,只有第一次有效。对于绑定服务,只有一次绑定和一次解除绑定有效,多次绑定和多次解除绑定是无效的!

F:点击Service unbind按钮后:


小结:发现unbindService之后(),程序并没有调用ServcieConnection接口里面 的onServiceDisconnected()方法,
LogCat没有输出 Server  is disconnected,那这个服务还是存在的吧?
ServiceConnection接口里的onServiceDisconnected()方法只会在Service被停止或者被系统杀死以后调用。 








阅读(2964) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~