Android Service的基本原理及启动模式、多请求下的线程同步

     Service是一种在Android应用后台的一种组件,没有自己的界面,不需要与用户交互。

      最基本的两种用途:执行长时间时间运行的耗时操作,如网络下载,音乐播放,文件系统检测。

      一种是组件间的交互(通过将某些功能以Service组件的形式进行封装,然后提供给其他应用组件调用,而不管这些组件是否与Service组件在同一进程中)。

Service组件有两种运行模式,一种是启动模式,一种是绑定模式。

        如果Service组件是长时间运行的操作,则一般采用启动模式,采用启动模式的Service一般持续执行一个单一的操作,而且并不会向调用者返回任何信息。Service被启动后,将一直处于运行状态,即使调用startService的进程结束了,Service仍然还存在,直到有进程调用stopService,或者Service调用stopSelf自杀。

如果Service组件提供一种封装的功能供其他组件使用,则一般采用绑定模式。步骤: 通过调用组件对象的bindService方法启动Service对象实例,如果没有指定的Service实例被创建,则该方法调用Service的onCreate()方法来创建一个实例,实例启动后,将调用onBind()方法,onBind方法返回给客户端一个IBinder接口实例,IBinder允许客户端回调Service方法,不如得到Service运行的状态或其他操作。只要连接建立,Service就会一直运行,(不管客户是否保留Service的IBinder的引用)。通常IBinder是一个使用AIDL写成的复杂接口。

 

绑定模式下Service的生命周期:onCreate()--->onBind(只一次,不能多次绑定)---->onUnbind()--->onDestory()

两种Service运行模式不是完全隔离的,通过调用startService方法启动的Service对象实例也可以被其他进程通过bindService方法来绑定,此时,只有对Service实例既调用了stopService,也调用unbindService饿,这个Service才会结束。

1、启动模式下的Service

实现步骤:1、创建Service类,继承android.app.Service类

2、实现onStartCommand等生命周期方法。

3.在Andridmanifest.xml文件中配置Service组件。

由于Service是在主线程运行的,为避免产生应用无响应异常,必须在Service类的内部创建一个单独的线程,用于耗时的业务逻辑。

Android SDK提供了更好的方法,既IntentService(同时解决了多请求下线程同步的问题)。

IntentService:

1、在应用的主线程外创建一个单独的工作线程来执行传递到onStartCommand方法的Intent组件。

2、创建一个工作队列,它每次将一个Intent传递到onHandleIntent(),不需要考虑多线程的同步问题。

3、当所有请求被处理完成后,将自动停止服务而不需要显示调用stopSelf方法。

4、提供一个返回null值的onBind方法的默认实现。

5、提供了onStartCommand方法的默认时间,它将所有的Intent发送到一个工作队列,并进一步发送到onHandleInteng方法。

例子:

CountIntentService.java

 

[java]  view plain copy
  1. <span style="font-size:14px;">package com.demo.startmodeservice;  
  2.   
  3. import java.text.SimpleDateFormat;  
  4.   
  5. import android.app.IntentService;  
  6. import android.content.Intent;  
  7. import android.os.Bundle;  
  8. import android.util.Log;  
  9.   
  10. public class CountIntentService extends IntentService {  
  11.     int span;  
  12.     public CountIntentService() {  
  13.         super("CountIntentService");  
  14.         // TODO Auto-generated constructor stub  
  15.     }  
  16.   
  17.     @Override  
  18.     protected void onHandleIntent(Intent arg0) {  
  19.         // TODO Auto-generated method stub  
  20.         Log.v("onHandleIntent""服务启动时间 " +getCurrentTime());  
  21.         Bundle b=arg0.getBundleExtra("attachment");  
  22.         span=b.getInt("waitingtime");  
  23.         long endTime = System.currentTimeMillis() + span*1000;  
  24.         Log.v("onHandleIntent""服务持续时间 " +span);  
  25.         while (System.currentTimeMillis() < endTime) {  
  26.         synchronized (this) {  
  27.         try {  
  28.         wait(endTime - System.currentTimeMillis());  
  29.         } catch (Exception e) {  
  30.         }  
  31.         }  
  32.         }  
  33.   
  34.     }  
  35.   
  36.     @Override  
  37.     public void onDestroy() {  
  38.         // TODO Auto-generated method stub  
  39.       
  40.           Log.v("onDestroy""服务销毁时间 " +getCurrentTime());  
  41.         super.onDestroy();  
  42.     }  
  43.     public String getCurrentTime(){  
  44.         SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  45.         String datetime = tempDate.format(new java.util.Date());  
  46.         return datetime;  
  47.     }  
  48.   
  49. }  
  50. </span>  


main.java

[java]  view plain copy
  1. <span style="font-size:14px;">package com.demo.startmodeservice;  
  2.   
  3. import android.app.Activity;  
  4. import android.view.View.OnClickListener;  
  5. import android.content.Intent;  
  6. import android.os.Bundle;  
  7. import android.view.View;  
  8. import android.widget.Button;  
  9.   
  10. public class main2  extends Activity {  
  11.     /** Called when the activity is first created. */  
  12.     @Override  
  13.     public void onCreate(Bundle savedInstanceState) {  
  14.         super.onCreate(savedInstanceState);  
  15.         setContentView(R.layout.main2);  
  16.         Button Button1 = (Button) findViewById(R.id.button1);  
  17.         Button1.setOnClickListener(new OnClickListener() {  
  18.             public void onClick(View v) {  
  19.                 Intent i=new Intent(main2.this, CountIntentService.class);  
  20.                 Bundle bd=new Bundle();  
  21.                 double a = Math.random()*10;    
  22.                   a = Math.ceil(a);    
  23.                   int randomNum = new Double(a).intValue();    
  24.                 bd.putInt("waitingtime", randomNum);  
  25.                 i.putExtra("attachment", bd);  
  26.   
  27.                  startService(i);  
  28.             }  
  29.         });  
  30.         Button Button2 = (Button) findViewById(R.id.button2);  
  31.         Button2.setOnClickListener(new OnClickListener() {  
  32.             public void onClick(View v) {  
  33.                  stopService(new Intent(main2.this, CountIntentService.class));  
  34.             }  
  35.         });  
  36.        // this.startService(new Intent(this, CountService.class));  
  37.     }  
  38.   
  39.     @Override  
  40.     protected void onDestroy() {  
  41.         super.onDestroy();  
  42.        // this.stopService(new Intent(this, CountService.class));  
  43.     }  
  44.      
  45.   
  46.   
  47. }  
  48. </span>  

xml文件:

 

[html]  view plain copy
  1. <span style="font-size:14px;"><?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent" android:layout_height="match_parent">  
  4.     <Button android:text="启动" android:id="@+id/button1"  
  5.         android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>  
  6.     <Button android:text="ֹͣ停止" android:id="@+id/button2"  
  7.         android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>  
  8. </LinearLayout>  
  9. </span>  

 

运行模式:

在启动模式下,Service中的业务逻辑主要在onStartCommand方法中实现,每次通过调用方法startService来启动Service,都会调用onStartCommand方法,其中方法的返回值决定了Service的运行模式。

1、START_NOT_STICKY:如果Sevice在启动后,被kill掉,并且没有新启动的Intent传给它,那么将Service移出启动状态并且不重新生成,知道再次显示调用Context.startService。适用场景:网上下载数据。

2、START_REDELIVER_INTENT:如果Service进程在启动后kill掉,那么它将会被重启,并且最后传给他的Intent通过onStartCommand(Intent ,int,int)会被重新传给他,这种模式保证了传给它Intent一定会被处理完毕,适用场景:关键业务处理。

3、START_STICKY:如果Service在它启动后被kill掉,那么Android将让Service继续保持started状态,但是不保留启动它的Intent,Android将重新创建Service实例,并执行onStartCommand方法,如果此时没有新的Intent请求,此时Intent的参数是null,这一点要特别注意。适用场景:后台播放音乐。这种运行模式的特点是需要显示启动并停止Service。


 

 2、绑定模式:

Service组件往往是用来实现一些底层的操作和业务功能,供其他组件来调用。

外部组件与Service交互,都是通过Context.bind()方法来绑定服务,此时需要Service组件返回一个实现了IBinder接口的对象,外部组件正是通过此对象来调用Service组件的功能。

实现对Service组件功能的调用Service组件要做以下改造:

1、将Service组件的功能封装到一个接口中。

2、实现一个内部类,它继承Bind类(既实现IBinder接口),并实现Service组件的功能接口类。

3、在Service组件的onBind方法中,返回步骤2的内部类对象,供其他组件使用。

例子:

ICountService.java

[java]  view plain copy
  1. <span style="font-size:14px;">package com.demo.bindservice;  
  2.   
  3. public interface ICountService {  
  4.      public abstract int getCount();  
  5. }  
  6.   
  7. </span>  


接口功能:一个返回计数信息的抽象方法。

LocalCountService.java

[java]  view plain copy
  1. <span style="font-size:14px;">package com.demo.bindservice;  
  2. import android.app.Service;  
  3. import android.content.Intent;  
  4. import android.os.Binder;  
  5. import android.os.IBinder;  
  6. import android.util.Log;  
  7. public class LocalCountService extends Service {  
  8.     private boolean threadDisable;  
  9.     private int count;  
  10.     private ServiceBinder serviceBinder = new ServiceBinder();  
  11.     public class ServiceBinder extends Binder implements ICountService {  
  12.         @Override  
  13.         public int getCount() {  
  14.             return count;  
  15.         }  
  16.     }  
  17.     @Override  
  18.     public IBinder onBind(Intent intent) {  
  19.         Log.v("CountService""onBind");  
  20.         return serviceBinder;  
  21.     }  
  22.     @Override  
  23.     public void onCreate() {  
  24.         super.onCreate();  
  25.         new Thread(new Runnable() {  
  26.             @Override  
  27.             public void run() {  
  28.                 while (!threadDisable) {  
  29.                     try {  
  30.                         Thread.sleep(1000);  
  31.                     } catch (InterruptedException e) {  
  32.                     }  
  33.                     count++;  
  34.                     Log.v("CountService""Count is " + count);  
  35.                 }  
  36.             }  
  37.         }).start();  
  38.         /**/  
  39.         Log.v("CountService""oncreate");  
  40.     }  
  41.   
  42.     @Override  
  43.     public int onStartCommand(Intent intent, int flag, int startid) {  
  44.         Log.v("CountService""onStartCommand");  
  45.         return START_STICKY;  
  46.     }  
  47.     @Override  
  48.     public void onDestroy() {  
  49.         super.onDestroy();  
  50.         this.threadDisable = true;  
  51.         Log.v("CountService""on destroy");  
  52.     }  
  53.     public int getCount() {  
  54.         return count;  
  55.     }  
  56.   
  57. }  
  58. </span>  


新增一个内部类ServiceBinder,它扩展了Binder并实现了countService的功能接口IciuntService,onBind()方法,它返回一个内部类对象。

在绑定模式下,onStartCommand方法将不会被执行,要将业务逻辑放置到onCreate方法中,这一点需要注意。

只有仅仅希望服务在后台运行,而不需要向其他组件提供功能服务的情况下才能将业务逻辑实现放在onStartCommand方法中。

创建一个Activity来调用conutService的功能:

LocalBind.java:


[java]  view plain copy
  1. <span style="font-size:14px;">package com.demo.bindservice;  
  2. import android.app.Activity;  
  3. import android.content.ComponentName;  
  4. import android.content.Intent;  
  5. import android.content.ServiceConnection;  
  6. import android.os.Bundle;  
  7. import android.os.IBinder;  
  8. import android.util.Log;  
  9. public class LocalBind extends Activity {  
  10.     private ServiceConnection serviceConnection = new ServiceConnection() {  
  11.         @Override  
  12.         public void onServiceConnected(ComponentName name, IBinder service) {  
  13.             LocalcountService = (ICountService) service;  
  14.             Log.v("CountService""on serivce connected, count is "  
  15.                     + LocalcountService.getCount());  
  16.         }  
  17.         @Override  
  18.         public void onServiceDisconnected(ComponentName name) {  
  19.             LocalcountService = null;  
  20.         }  
  21.     };  
  22.     private ICountService LocalcountService;  
  23.     /** Called when the activity is first created. */  
  24.     @Override  
  25.     public void onCreate(Bundle savedInstanceState) {  
  26.         super.onCreate(savedInstanceState);  
  27.         setContentView(R.layout.main);  
  28.         //第一个参数为Intent对象,定义要绑定哪个Service组件  
  29.         //第二个参数为ServerConnection对象,它代表了到Service组件的链接  
  30.         //第三个参数为常量,它代表绑定时如果没有Service实例存在则允许创建一个新的Service实例。  
  31.         this.bindService(new Intent("com.demo.service.LocalCountService"),  
  32.                 this.serviceConnection, BIND_AUTO_CREATE);  
  33.     }  
  34.     @Override  
  35.     protected void onDestroy() {  
  36.         this.unbindService(serviceConnection);  
  37.         super.onDestroy();  
  38.     }  
  39. }  
  40. </span>  

在onDestory方法中,必须先调用onbindService方法来解除对Service组件的绑定,然后才能调用super.onDestory销毁对象。否则会造成内存泄露。

AndroidManifest.xml

[html]  view plain copy
  1. <span style="font-size:14px;"><?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.demo.bindservice" android:versionCode="1"  
  4.     android:versionName="1.0">  
  5.     <uses-sdk android:minSdkVersion="7" />  
  6.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  7.         <activity android:name=".LocalBind" android:label="@string/app_name">  
  8.             <intent-filter>  
  9.                 <action android:name="android.intent.action.MAIN" />  
  10.                 <category android:name="android.intent.category.LAUNCHER" />  
  11.             </intent-filter>  
  12.         </activity>  
  13.         <service android:name=".LocalCountService">  
  14.   
  15.             <intent-filter>  
  16.                 <action android:name="com.demo.service.LocalCountService" />  
  17.             </intent-filter>  
  18.         </service>  
  19.           
  20.   
  21.           
  22.     </application>  
  23. </manifest></span>  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值