Android之Service

来源:互联网 发布:数据结构设计怎么写 编辑:程序博客网 时间:2024/06/05 11:59

简介:

基本概念:Service是Android四大组件之一,运行在后台执行耗时操作并且不提供用户界面。其他组件(如Activity)可以通过startService启动该组件,也可以通过bindService启动并绑定该组件进行通信。


使用场景:后台下载文件,播放音乐等。


注意:Service运行在主线程中,它不会创建属于自己的线程,也不是运行在独立的线程中,所以,在使用的时候,需要自己创建线程,而不应该直接执行耗时操作,这样会引起ANR(程序未响应)错误。


Service的两种形式:

Started Service
   基本概念:其他组件(如Activity)通过调用startService()启动该Service。拥有独立的生命周期,不依赖启动它的组件。


Bound Service
    基本概念:其他组件为了与Service建立一个长时间的连接,通过调bindService启动并绑定该Service。并能与之交互(发送请求,接受响应)。生命周期依赖绑定它的组件,可以是多个组件绑定同一个Service,一旦所有绑定它的组件取消绑定,则消亡。


Service的生命周期:

Started Service,Bound Service生命周期方法流程:



以下示例代码包含两个子Demo,所以第一个界面里面包含两个ListViewItem,分别可以进入这两个子Demo:

[java] view plain copy 在CODE上查看代码片派生到我的代码片
  1. public class MainActivity extends Activity {  
  2.   
  3.     private String[] datas = { "Started Service Demo""Bound Service Demo" };  
  4.   
  5.     @Override  
  6.     protected void onCreate(Bundle savedInstanceState) {  
  7.         super.onCreate(savedInstanceState);  
  8.         setContentView(R.layout.activity_main);  
  9.         setupViews();  
  10.     }  
  11.   
  12.     private void setupViews() {  
  13.         //新建一个数组适配器  
  14.         ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(  
  15.                 MainActivity.this, android.R.layout.simple_list_item_1, datas);  
  16.         //获取到ListView控件  
  17.         ListView mListView = (ListView) findViewById(R.id.list_view_main);  
  18.         //为ListView设置适配器  
  19.         mListView.setAdapter(arrayAdapter);  
  20.         //为ListView Item设置点击监听器  
  21.         mListView.setOnItemClickListener(new OnItemClickListener() {  
  22.   
  23.             @Override  
  24.             public void onItemClick(AdapterView<?> parent, View view,  
  25.                     int position, long id) {  
  26.                 switch (position) {  
  27.                 case 0:  
  28.                     //跳转到Started Service Demo Activity  
  29.                     redirectTOActivity(StartedServiceDemoActivity.class);  
  30.                     break;  
  31.                 case 1:  
  32.                     //跳转到Bound Service Demo Activity  
  33.                     redirectTOActivity(BoundServiceDemoActivity.class);  
  34.                     break;  
  35.   
  36.                 default:  
  37.                     break;  
  38.                 }  
  39.             }  
  40.         });  
  41.     }  
  42.       
  43.     //跳转到其他Activity  
  44.     private void redirectTOActivity(Class<?> destination){  
  45.         Intent intent = new Intent(MainActivity.this, destination);  
  46.         startActivity(intent);  
  47.     }  
  48. }  



以下是用StartService方法启动Service的Activity:

[java] view plain copy 在CODE上查看代码片派生到我的代码片
  1. //操作Servie01的Activity  
  2. public class StartedServiceDemoActivity extends Activity implements OnClickListener{  
  3.   
  4.     @Override  
  5.     protected void onCreate(Bundle savedInstanceState) {  
  6.         super.onCreate(savedInstanceState);  
  7.         setContentView(R.layout.activity_started_service_demo);  
  8.         setupViews();  
  9.     }  
  10.       
  11.     private void setupViews()   {  
  12.         //设置两个按钮的监听器为当前Activity  
  13.         findViewById(R.id.button01).setOnClickListener(this);  
  14.         findViewById(R.id.button02).setOnClickListener(this);  
  15.     }  
  16.   
  17.     @Override  
  18.     public void onClick(View v) {  
  19.           
  20.         Intent intent = new Intent(StartedServiceDemoActivity.this, Service01.class);  
  21.           
  22.         int id = v.getId();  
  23.         switch (id) {  
  24.         case R.id.button01:  
  25.             //Start Service按钮被点击  
  26.             //启动Service01  
  27.             startService(intent);  
  28.             break;  
  29.         case R.id.button02:  
  30.             //Stop Service按钮被点击  
  31.             //停止Service01  
  32.             stopService(intent);  
  33.             break;  
  34.         default:  
  35.             break;  
  36.         }  
  37.     }  
  38. }  


以下是Service01的内容,它的onBind()和onUnBInd()不会被回调:

[java] view plain copy 在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  *  
  3.  * Service01是以StartService方式启动,以StopService方式停止的Service 
  4.  * 如果当前无Service01实例,那么回调方法onCreate()、onStartCommand()、onStart()方法会被依次调用 
  5.  * 如果当前有Service01实例,那么回调方法onStartCommand()、onStart()方法会被依次调用 
  6.  * 
  7.  */  
  8. public class Service01 extends Service{  
  9.       
  10.     @Override  
  11.     public IBinder onBind(Intent intent) {  
  12.         System.out.println("Service01 onBind.....");  
  13.         return null;  
  14.     }  
  15.       
  16.     @Override  
  17.     public void unbindService(ServiceConnection conn) {  
  18.         System.out.println("Service01 onUnBind.....");  
  19.         super.unbindService(conn);  
  20.     }  
  21.       
  22.     @Override  
  23.     public void onCreate() {  
  24.         System.out.println("Service01 onCreate.....");  
  25.         super.onCreate();  
  26.     }  
  27.       
  28.     @Override  
  29.     public int onStartCommand(Intent intent, int flags, int startId) {  
  30.         System.out.println("Service01 onStartCommand.....");  
  31.         return super.onStartCommand(intent, flags, startId);  
  32.     }  
  33.       
  34.     @Override  
  35.     public void onStart(Intent intent, int startId) {  
  36.         System.out.println("Service01 onStart.....");  
  37.     }  
  38.       
  39.       
  40.     @Override  
  41.     public void onDestroy() {  
  42.         System.out.println("Service01 onDestroy.....");  
  43.         super.onDestroy();  
  44.     }  
  45.       
  46. }  

以下是用BindService方式启动Service的Activity:

[java] view plain copy 在CODE上查看代码片派生到我的代码片
  1. public class BoundServiceDemoActivity extends Activity implements OnClickListener {  
  2.   
  3.     //实例化一个ServiceConnection的匿名子类对象  
  4.     private ServiceConnection serviceConnection = new ServiceConnection() {  
  5.           
  6.         @Override  
  7.         public void onServiceDisconnected(ComponentName name) {  
  8.             //当解除绑定事件发生时,此方法被回调  
  9.             isBind = false;  
  10.         }  
  11.           
  12.         @Override  
  13.         public void onServiceConnected(ComponentName name, IBinder service) {  
  14.             //当绑定事件发生时,此方法被回调  
  15.             MyBinder myBinder = (MyBinder) service; //进行一个类型转换,得到MyBinder实例  
  16.             //得到Service02实例  
  17.             mService = myBinder.getService();  
  18.             isBind = true;  
  19.               
  20.         }  
  21.     };  
  22.       
  23.     //定义一个Servie02类型的实例  
  24.     private  Service02 mService = null;  
  25.     //定义一个bool变量,记录当前Activity是否绑定了Servie02  
  26.     private boolean isBind = false;  
  27.       
  28.     @Override  
  29.     protected void onCreate(Bundle savedInstanceState) {  
  30.         super.onCreate(savedInstanceState);  
  31.         setContentView(R.layout.activity_bound_service_demo);  
  32.         setupViews();  
  33.     }  
  34.       
  35.     private void setupViews(){  
  36.         findViewById(R.id.button01).setOnClickListener(this);  
  37.         findViewById(R.id.button02).setOnClickListener(this);  
  38.         findViewById(R.id.button03).setOnClickListener(this);  
  39.     }  
  40.       
  41.     @Override  
  42.     public void onClick(View v) {  
  43.           
  44.         Intent intent = new Intent(BoundServiceDemoActivity.this, Service02.class);  
  45.           
  46.         int id = v.getId();  
  47.         switch (id) {  
  48.         case R.id.button01:  
  49.             //开始绑定  
  50.             bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);  
  51.             break;  
  52.         case R.id.button02:  
  53.             //调用Service02的业务方法  
  54.             if(mService != null){  
  55.                 int x = mService.getRandomNumber();  
  56.                 Toast.makeText(BoundServiceDemoActivity.this"" + x, Toast.LENGTH_SHORT).show();  
  57.             }  
  58.             break;  
  59.         case R.id.button03:  
  60.             //解除当前Activity与Service02之间的绑定关系  
  61.             unbindService(serviceConnection);  
  62.             break;  
  63.           
  64.   
  65.         default:  
  66.             break;  
  67.         }  
  68.           
  69.     }  
  70. }  


以下是Service02的内容,它的onStart()和onStartCommand()方法不会被回调,

这种Service它一般去编写的时候分为四个步骤,必须要有一个Binder实例来传递Service实例,具体如下:

[java] view plain copy 在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  *  
  3.  * Service02是以BindService方式启动,以UnBindService方式解绑Service与组件之间的绑定关系, 
  4.  * 如果Service02已经绑定启动了,可以有其他的多个Activity通过BindService方式继续与其绑定,只有 
  5.  * 当所有的Activity都与Service02解除绑定关系,Service02实例才消亡 
  6.  *  
  7.  * 如果当前无Service02实例,那么回调方法onCreate()、onBind()方法会被依次调用 
  8.  * 如果当前有Service02实例,那么回调方法onBind()方法会被依次调用 
  9.  * 如果所有绑定Service02实例的组件都调用UnBind方法,那么回调方法onUnbind()、onDestroy()方法会依次被调用 
  10.  * 
  11.  */  
  12. public class Service02 extends Service {  
  13.   
  14.     // 第一步,定义一个Binder类型的子类,在子类种定义一个getService方法  
  15.     public class MyBinder extends Binder {  
  16.         public Service02 getService() {  
  17.             return Service02.this;  
  18.         }  
  19.     }  
  20.       
  21.     //第二步,定义一个MyBinder类型的实例  
  22.     private MyBinder mBinder = new MyBinder();  
  23.   
  24.     @Override  
  25.     public void onStart(Intent intent, int startId) {  
  26.         System.out.println("Service02 onStart.....");  
  27.         super.onStart(intent, startId);  
  28.     }  
  29.   
  30.     @Override  
  31.     public int onStartCommand(Intent intent, int flags, int startId) {  
  32.         System.out.println("Service02 onStartCommand.....");  
  33.         return super.onStartCommand(intent, flags, startId);  
  34.     }  
  35.   
  36.     @Override  
  37.     public void onCreate() {  
  38.         System.out.println("Service02 onCreate.....");  
  39.         super.onCreate();  
  40.     }  
  41.   
  42.     @Override  
  43.     public IBinder onBind(Intent intent) {  
  44.         System.out.println("Service02 onBind.....");  
  45.         //第三步,在onBind方法中,返回MyBinder的实例  
  46.         return mBinder;  
  47.     }  
  48.   
  49.     @Override  
  50.     public boolean onUnbind(Intent intent) {  
  51.         System.out.println("Service02 onUnBind.....");  
  52.         return super.onUnbind(intent);  
  53.     }  
  54.   
  55.     @Override  
  56.     public void onDestroy() {  
  57.         System.out.println("Service02 onDestroy.....");  
  58.         super.onDestroy();  
  59.     }  
  60.       
  61.     //第四步,在Service02中定义一个业务方法,让外面与当前Service02绑定的组件能够调用此方法,来完成既定目标  
  62.     public int getRandomNumber(){  
  63.         return new Random().nextInt(100);  
  64.     }  
  65.   
  66. }  


最后把整个Demo的Android工程压缩文件链接如下:

Android Service Demo


0 0
原创粉丝点击