Android中的service 实现之 利用onStart方式


service的实现主要有两种方式,一种是onStart方式,另一种是onBoundd方式。两种方式的关于service的生命周期不一样。前者是和activity的生命周期一样的,后者则不是。activity结束了service可以继续运行。

onStart 方法来调用service的话,调用者其实和service是没有关系的,调用者消亡了的话,service是依然可以继续运行的;

onBound方式的话调用者和service是绑定在一起的,调用者消亡的了话,service也会跟着消亡了。

onStart 方法的创建的service一开始是onCreate 然后调用onStartCommand()  (在老的版本中是onStart()函数,新版本中调用onStartCommand的话还是会去调用onStar方法,建议使用onStartCommand方式)。如果该service不stop的话,再点的话一直会是onstar相应,onCreate只有在第一次启动的时候会调用。

下面的例子:

有两个按钮:一个启动service,另一个停止service。具体实现如下:

1)ServiceText1.java

用于调用sercice程序:

代码:

  1. package com.huawei.Android.servicetext1;  
  2. import android.app.Activity;  
  3. import android.content.Intent;  
  4. import android.os.Bundle;  
  5. import android.view.View;  
  6. import android.view.View.OnClickListener;  
  7. import android.widget.Button;  
  8. public class ServiceText1 extends Activity {  
  9.     private Button mbtnStarServ = null;  
  10.     private Button mbtnStopServ = null;  
  11.     /** Called when the activity is first created. */  
  12.     @Override  
  13.     public void onCreate(Bundle savedInstanceState) {  
  14.         super.onCreate(savedInstanceState);  
  15.         setContentView(R.layout.main);  
  16.         mbtnStarServ = (Button)findViewById(R.id.starService);  
  17.         mbtnStopServ = (Button)findViewById(R.id.stopService);  
  18.         mbtnStarServ.setOnClickListener(new listener());  
  19.         mbtnStopServ.setOnClickListener(new listener());  
  20.           
  21.     }  
  22.       
  23.     class listener implements OnClickListener  
  24.     {  
  25.         @Override  
  26.         public void onClick(View v) {  
  27.             // TODO Auto-generated method stub   
  28.             Intent intent = new Intent(ServiceText1.this,Service.class);  
  29.             switch(v.getId())  
  30.             {  
  31.             case R.id.starService:  
  32.                 //Intent intent = new Intent();   
  33.                   
  34.                 //intent.setClass(ServiceText1.this, Service.class);   
  35.                 startService(intent);  
  36.                 break;  
  37.             case R.id.stopService:  
  38.                 stopService(intent);  
  39.                 break;  
  40.             default:  
  41.                 break;  
  42.             }  
  43.               
  44.         }  
  45.           
  46.         }  
  47. }  

2)service.java,实现的service

  1. package com.huawei.android.servicetext1;  
  2. import android.content.Intent;  
  3. import android.os.IBinder;  
  4. import android.util.Log;  
  5. /** 
  6.  *  
  7.  * @author bluesky 
  8.  * @notes 创建一个service步骤 
  9.  * 1.简历一个service类,继承自Service类, 
  10.  * 2.复写onCreate,onDestory,onStartCommand函数。当需要onStartService方法来执行service方法的时候, 
  11.  * 这个时候onBind函数不需要执行任何操作,直接返回null就ok了 
  12.  * 3.在需要使用service的类得manifest.xml中进行注册。 
  13.  */  
  14. public class Service extends android.app.Service {  
  15.     //创建service 需要复写 onCreate,onDestory,onStartCommand函数。这里是通过onStartService来执行service操作的,   
  16.     //这个时候onBind函数不需要执行任何操作,直接返回null就ok了   
  17.     private static final String TAG = "Service";  
  18.     @Override  
  19.     public void onCreate() {  
  20.         // TODO Auto-generated method stub   
  21.         Log.i(TAG, "Service------->onCreate");  
  22.         super.onCreate();  
  23.     }  
  24.     @Override  
  25.     public void onDestroy() {  
  26.         // TODO Auto-generated method stub   
  27.         Log.i(TAG, "Service------->onDestory");  
  28.         super.onDestroy();  
  29.     }  
  30.     //需要执行操作在onStartCommand里面来进行操作就可以了。   
  31.     @Override  
  32.     public int onStartCommand(Intent intent, int flags, int startId) {  
  33.         // TODO Auto-generated method stub   
  34.         Log.i(TAG, "Service------->onStartCommand");  
  35.         //这里的返回有三种类型,可以自己手动返回。return XXXXX;   
  36.         return super.onStartCommand(intent, flags, startId);  
  37.     }  
  38.     @Override  
  39.     public IBinder onBind(Intent arg0) {  
  40.         // TODO Auto-generated method stub   
  41.         return null;  
  42.     }  
  43. }  

3)ServiceText1.java

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       package="com.huawei.android.servicetext1"  
  4.       android:versionCode="1"  
  5.       android:versionName="1.0">  
  6.     <uses-sdk android:minSdkVersion="8" />  
  7.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  8.         <activity android:name=".ServiceText1"  
  9.                   android:label="@string/app_name">  
  10.             <intent-filter>  
  11.                 <action android:name="android.intent.action.MAIN" />  
  12.                 <category android:name="android.intent.category.LAUNCHER" />  
  13.             </intent-filter>  
  14.         </activity>  
  15.         <service android:name=".Service">  
  16.         </service>  
  17.     </application>  
  18. </manifest>  

main.xml文件:

  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. <TextView    
  8.     android:layout_width="fill_parent"   
  9.     android:layout_height="wrap_content"   
  10.     android:text="@string/hello"  
  11.     />  
  12.     <Button  
  13.     android:id="@+id/starService"  
  14.     android:layout_width="fill_parent"  
  15.     android:layout_height="wrap_content"  
  16.     android:text="@string/starservice"  
  17. />  
  18. <Button  
  19.     android:id="@+id/stopService"  
  20.     android:layout_width="fill_parent"  
  21.     android:layout_height="wrap_content"  
  22.     android:text="@string/stopService"  
  23. />  
  24. </LinearLayout>  

截图:


这里补充一点知识:

stop service 有两种方法:
1.使用调用程序来停止一个service :即调用stopService();
2.使用service 本身来停止一个service:即调用stopSelf(int srvId);
我们来想象一个场景:
如果service被很多的程序并发调用的话,如果在某个程序里你调用了stopService();那么第二个程序来调用的时候service的服务已经关掉了,这样你又得去重新onCreate()下service,如果量大的话,开销将是很大的。那么怎么办呢?
推荐的方式就是第二种了。stopSelf(int srvId),参数是srv的id,该id在startCommand的时候创建,stopSelf(int srvId)执行的时候会发送id给startCommand(),匹配所关掉服务的id是否匹配,这样如果某个启动服务的程序结束之前另一个线程也调用了startCommand(),这样前面一个程序就无法使用stopSelf(int srvId)来关闭service了。因为id已经变更了。这样就可以节约开销。

相关内容