玩转Android---组件篇---Service(服务)

来源:互联网 发布:仿淘宝商城源码html 编辑:程序博客网 时间:2024/06/15 07:20

Service是Andorid系统提供的四大组件之一,它的地位和Activity是并列的,只是使用的频率没有Activity高。Service就是运行于后台的一种服务程序,一般很少和用户交互,因此没有可视化界面。

         定义一个Service类只要继承Service类即可,实现其生命周期中的方法就可以了,另外,一个定义好的Service组件必须要在AndoridManifest.xml文件中注册才能够使用。

         Service有自己的生命周期,可以调用startService()启动一个Service或者使用bindService()来绑定一个service,还可以通过RPC(远程进程调用)机制来实现不同进程间Service的调用。

 

Service中定义了一系列和自身生命周期相关的方法:

onBind(Intent intent):是必须实现的一个方法,返回一个绑定的接口给Service。

onCreate():当Service第一次被创建时,由系统调用。

onStart(Intent intent,int startId):当通过startService()方法启动Service时,该方法被调用。

onDestroy():当Service不再使用,系统调用该方法。

 

实例如下:

MyService.java

Java代码 复制代码 收藏代码
  1. /*  
  2.  * @author hualang  
  3.  */  
  4. package org.hualang.service;   
  5.   
  6. import android.app.Service;   
  7. import android.content.Intent;   
  8. import android.os.IBinder;   
  9. import android.util.Log;   
  10. import android.widget.Toast;   
  11.   
  12. public class MyService extends Service {   
  13.   
  14.     @Override  
  15.     public IBinder onBind(Intent intent) {   
  16.         // TODO Auto-generated method stub   
  17.         Log.i("SERVICE", "onBind.................");   
  18.         Toast.makeText(MyService.this, "onBind.................", Toast.LENGTH_LONG).show();   
  19.         return null;   
  20.     }   
  21.        
  22.     public void onCreate()   
  23.     {   
  24.         Log.i("SERVICE", "onCreate................");   
  25.         Toast.makeText(MyService.this, "onCreate................", Toast.LENGTH_LONG).show();   
  26.     }   
  27.     public void onStart(Intent intent,int startId)   
  28.     {   
  29.         Log.i("SERVICE", "onStart.................");   
  30.         Toast.makeText(MyService.this, "onStart.................", Toast.LENGTH_LONG).show();   
  31.     }   
  32.     public void onDestroy()   
  33.     {   
  34.         Log.i("SERVICE", "onDestroy.................");   
  35.         Toast.makeText(MyService.this, "onDestroy.................", Toast.LENGTH_LONG).show();   
  36.     }   
  37. }  
/* * @author hualang */package org.hualang.service;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;import android.widget.Toast;public class MyService extends Service {@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubLog.i("SERVICE", "onBind.................");Toast.makeText(MyService.this, "onBind.................", Toast.LENGTH_LONG).show();return null;}public void onCreate(){Log.i("SERVICE", "onCreate................");Toast.makeText(MyService.this, "onCreate................", Toast.LENGTH_LONG).show();}public void onStart(Intent intent,int startId){Log.i("SERVICE", "onStart.................");Toast.makeText(MyService.this, "onStart.................", Toast.LENGTH_LONG).show();}public void onDestroy(){Log.i("SERVICE", "onDestroy.................");Toast.makeText(MyService.this, "onDestroy.................", Toast.LENGTH_LONG).show();}}

 ServiceTest.java

Java代码 复制代码 收藏代码
  1. /*  
  2.  * @author hualang  
  3.  */  
  4. package org.hualang.service;   
  5.   
  6. import android.app.Activity;   
  7. import android.app.Service;   
  8. import android.content.ComponentName;   
  9. import android.content.Intent;   
  10. import android.content.ServiceConnection;   
  11. import android.os.Bundle;   
  12. import android.os.IBinder;   
  13. import android.util.Log;   
  14. import android.view.View;   
  15. import android.view.View.OnClickListener;   
  16. import android.widget.Button;   
  17. import android.widget.Toast;   
  18.   
  19. public class ServiceTest extends Activity {   
  20.     /** Called when the activity is first created. */  
  21.     private Button startService,stopService,bindService,unbindService;   
  22.     @Override  
  23.     public void onCreate(Bundle savedInstanceState) {   
  24.         super.onCreate(savedInstanceState);   
  25.         setContentView(R.layout.main);   
  26.         startService=(Button)findViewById(R.id.startButton);   
  27.         stopService=(Button)findViewById(R.id.stopButton);   
  28.         bindService=(Button)findViewById(R.id.bindButton);   
  29.         unbindService=(Button)findViewById(R.id.unbindButton);   
  30.         startService.setOnClickListener(startListener);   
  31.         stopService.setOnClickListener(stopListener);   
  32.         bindService.setOnClickListener(bindListener);   
  33.         unbindService.setOnClickListener(unbindListener);   
  34.            
  35.     }   
  36.     private OnClickListener startListener=new OnClickListener()   
  37.     {   
  38.   
  39.         @Override  
  40.         public void onClick(View v) {   
  41.             // TODO Auto-generated method stub   
  42.             Intent intent=new Intent();   
  43.             intent.setAction("org.hualang.service.action.MYSERVICE");   
  44.             startService(intent);   
  45.         }   
  46.            
  47.     };   
  48.     private OnClickListener stopListener=new OnClickListener()   
  49.     {   
  50.   
  51.         @Override  
  52.         public void onClick(View v) {   
  53.             // TODO Auto-generated method stub   
  54.             Intent intent=new Intent();   
  55.             intent.setAction("org.hualang.service.action.MYSERVICE");   
  56.             stopService(intent);   
  57.         }   
  58.            
  59.     };   
  60.     private ServiceConnection conn=new ServiceConnection()   
  61.     {   
  62.   
  63.         @Override  
  64.         public void onServiceConnected(ComponentName name, IBinder service) {   
  65.             // TODO Auto-generated method stub   
  66.             Log.i("SERVICE", "connection success");   
  67.             Toast.makeText(ServiceTest.this, "connection success", Toast.LENGTH_LONG).show();   
  68.         }   
  69.   
  70.         @Override  
  71.         public void onServiceDisconnected(ComponentName name) {   
  72.             // TODO Auto-generated method stub   
  73.             Log.i("SERVICE", "connection success");   
  74.             Toast.makeText(ServiceTest.this, "connection failure", Toast.LENGTH_LONG).show();   
  75.         }   
  76.            
  77.     };   
  78.     private OnClickListener bindListener=new OnClickListener()   
  79.     {   
  80.   
  81.         @Override  
  82.         public void onClick(View v) {   
  83.             // TODO Auto-generated method stub   
  84.             Intent intent=new Intent();   
  85.             intent.setAction("org.hualang.service.action.MYSERVICE");   
  86.             bindService(intent,conn,Service.BIND_AUTO_CREATE);   
  87.         }   
  88.            
  89.     };   
  90.     private OnClickListener unbindListener=new OnClickListener()   
  91.     {   
  92.   
  93.         @Override  
  94.         public void onClick(View v) {   
  95.             // TODO Auto-generated method stub   
  96.             Intent intent=new Intent();   
  97.             intent.setAction("org.hualang.service.action.MYSERVICE");   
  98.             unbindService(conn);   
  99.         }   
  100.            
  101.     };   
  102. }  
/* * @author hualang */package org.hualang.service;import android.app.Activity;import android.app.Service;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;public class ServiceTest extends Activity {    /** Called when the activity is first created. */private Button startService,stopService,bindService,unbindService;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        startService=(Button)findViewById(R.id.startButton);        stopService=(Button)findViewById(R.id.stopButton);        bindService=(Button)findViewById(R.id.bindButton);        unbindService=(Button)findViewById(R.id.unbindButton);        startService.setOnClickListener(startListener);        stopService.setOnClickListener(stopListener);        bindService.setOnClickListener(bindListener);        unbindService.setOnClickListener(unbindListener);            }    private OnClickListener startListener=new OnClickListener()    {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubIntent intent=new Intent();intent.setAction("org.hualang.service.action.MYSERVICE");startService(intent);}        };    private OnClickListener stopListener=new OnClickListener()    {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubIntent intent=new Intent();intent.setAction("org.hualang.service.action.MYSERVICE");stopService(intent);}        };    private ServiceConnection conn=new ServiceConnection()    {@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {// TODO Auto-generated method stubLog.i("SERVICE", "connection success");Toast.makeText(ServiceTest.this, "connection success", Toast.LENGTH_LONG).show();}@Overridepublic void onServiceDisconnected(ComponentName name) {// TODO Auto-generated method stubLog.i("SERVICE", "connection success");Toast.makeText(ServiceTest.this, "connection failure", Toast.LENGTH_LONG).show();}        };    private OnClickListener bindListener=new OnClickListener()    {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubIntent intent=new Intent();intent.setAction("org.hualang.service.action.MYSERVICE");bindService(intent,conn,Service.BIND_AUTO_CREATE);}        };    private OnClickListener unbindListener=new OnClickListener()    {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubIntent intent=new Intent();intent.setAction("org.hualang.service.action.MYSERVICE");unbindService(conn);}        };}

 

在AndroidManifest.xml文件中注册Service如下

Java代码 复制代码 收藏代码
  1. <service android:name="MyService">   
  2.             <intent-filter>   
  3.                 <action android:name="org.hualang.service.action.MYSERVICE"/>   
  4.             </intent-filter>   
  5.         </service>  
<service android:name="MyService"><intent-filter><action android:name="org.hualang.service.action.MYSERVICE"/></intent-filter></service>

 main.xml布局文件

Java代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>   
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >   
  7.     <Button   
  8.         android:text="启动Service"  
  9.         android:id="@+id/startButton"  
  10.         android:layout_width="fill_parent"  
  11.         android:layout_height="wrap_content"  
  12.     />   
  13.         <Button   
  14.         android:text="停止Service"  
  15.         android:id="@+id/stopButton"  
  16.         android:layout_width="fill_parent"  
  17.         android:layout_height="wrap_content"  
  18.     />   
  19.         <Button   
  20.         android:text="绑定Service"  
  21.         android:id="@+id/bindButton"  
  22.         android:layout_width="fill_parent"  
  23.         android:layout_height="wrap_content"  
  24.     />   
  25.         <Button   
  26.         android:text="解除绑定unbindService"  
  27.         android:id="@+id/unbindButton"  
  28.         android:layout_width="fill_parent"  
  29.         android:layout_height="wrap_content"  
  30.     />   
  31. </LinearLayout>  
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><Buttonandroid:text="启动Service"android:id="@+id/startButton"android:layout_width="fill_parent"android:layout_height="wrap_content"/><Buttonandroid:text="停止Service"android:id="@+id/stopButton"android:layout_width="fill_parent"android:layout_height="wrap_content"/><Buttonandroid:text="绑定Service"android:id="@+id/bindButton"android:layout_width="fill_parent"android:layout_height="wrap_content"/><Buttonandroid:text="解除绑定unbindService"android:id="@+id/unbindButton"android:layout_width="fill_parent"android:layout_height="wrap_content"/></LinearLayout>

 

不解释,看运行结果就会明白

(1)当点击“启动Servcie”会先弹出"onCreate",然后弹出"onStart"的Toast,在LogCat中会看到先显示

的也是

onCreate

onStart


(2)点击“停止Service”按钮,会弹出onDestroy的Toast

LogCat中也会显示

onDestroy()



 (3)点击"绑定Service"按钮,会弹出onCreate和onBind的Toast

LogCat中显示

onCreate

onBind



 (4)点击“解除绑定Service”按钮,会弹出onDestroy的Toast,LogCat中也如此



 

下面是LogCat中显示的信息