Android开发学习笔记:Service的简介和启动方式

一.Service的简介

1.Service介绍和作用
Service是Android系统中的四大组件之一,它是一种长生命周期的,没有可视化界面,运行于后台的一种服务程序。比如我们播放音乐的时候,有可能想边听音乐边干些其他事情,当退出播放音乐的应用,如果不用Service,我 们就听不到歌了,所以这时候就得用到Service了。
 
2. Service生命周期
Service的生命周期并不像Activity那么复杂,它只继承了onCreate(),onStart(),onDestroy()三个方法,当第一次启动Service时,先后调用了onCreate(),onStart()这两个方法,当停止Service时,则执行onDestroy()方法,这里需要注意的是,如果Service已经启动了,当我们再次启动Service时,不会在执行onCreate()方法,而是直接执行onStart()方法。
 
二.Service的启动方式
Service的有两种启动方式: Context.startService()和Context.bindService(),这两种方式对 Service生命周期的影响是不同的。
 
1.Context.startService()方式启动
 
①Context.startService()方式的生命周期: 
启动时,startService –> onCreate() –> onStart()
停止时,stopService –> onDestroy()
如果调用者直接退出而没有停止Service,则Service 会一直在后台运行
 
Context.startService()方法启动服务,在服务未被创建时,系统会先调用服务的onCreate()方法,接着调用onStart()方法。如果调用startService()方法前服务已经被创建,多次调用startService()方法并不会导致多次创建服务,但会导致多次调用onStart()方法。采用startService()方法启动的服务,只能调用Context.stopService()方法结束服务,服务结束时会调用onDestroy()方法。
 
②Context.startService()方式启动 Service的方法:
 
下面是具体例子:
 
MainActivity.java
 
 
 
  1. package com.android.service.activity;  
  2.  
  3. import android.app.Activity;  
  4. import android.content.Intent;  
  5. import android.os.Bundle;  
  6. import android.view.View;  
  7. import android.view.View.OnClickListener;  
  8. import android.widget.Button;  
  9.  
  10. public class MainActivity extends Activity  
  11. {  
  12.     private Button startBtn;  
  13.     private Button stopBtn;  
  14.     @Override 
  15.     public void onCreate(Bundle savedInstanceState)  
  16.     {  
  17.         super.onCreate(savedInstanceState);  
  18.         setContentView(R.layout.main);  
  19.         startBtn = (Button) findViewById(R.id.startBtn);  
  20.         stopBtn = (Button) findViewById(R.id.stopBtn);  
  21.         //添加监听器  
  22.         startBtn.setOnClickListener(listener);  
  23.         stopBtn.setOnClickListener(listener);  
  24.     }  
  25.       
  26.     //启动监听器  
  27.     private OnClickListener listener=new OnClickListener()  
  28.     {         
  29.         @Override 
  30.         public void onClick(View v)  
  31.         {  
  32.             Intent intent=new Intent(MainActivity.this, ServiceDemo.class);  
  33.             switch (v.getId())  
  34.             {  
  35.             case R.id.startBtn:  
  36.                 startService(intent);  
  37.                 break;  
  38.             case R.id.stopBtn:  
  39.                 stopService(intent);  
  40.                 break;  
  41.             default:  
  42.                 break;  
  43.             }             
  44.         }  
  45.     };  
 
ServiceDemo.java
 
 
 
  1. package com.android.service.activity;  
  2.  
  3. import android.app.Service;  
  4. import android.content.Intent;  
  5. import android.os.IBinder;  
  6. import android.util.Log;  
  7.  
  8. public class ServiceDemo extends Service  
  9. {  
  10.     private static final String TAG="Test";  
  11.       
  12.     @Override 
  13.     //Service时被调用  
  14.     public void onCreate()  
  15.     {  
  16.         Log.i(TAG, "Service onCreate--->");  
  17.         super.onCreate();  
  18.     }  
  19.  
  20.     @Override 
  21.     //当调用者使用startService()方法启动Service时,该方法被调用  
  22.     public void onStart(Intent intent, int startId)  
  23.     {  
  24.         Log.i(TAG, "Service onStart--->");  
  25.         super.onStart(intent, startId);  
  26.     }  
  27.  
  28.     @Override 
  29.     //当Service不在使用时调用  
  30.     public void onDestroy()  
  31.     {  
  32.         Log.i(TAG, "Service onDestroy--->");  
  33.         super.onDestroy();  
  34.     }  
  35.  
  36.     @Override 
  37.     //当使用startService()方法启动Service时,方法体内只需写return null  
  38.     public IBinder onBind(Intent intent)  
  39.     {  
  40.         return null;  
  41.     }  
  42. }  
  43.  
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.     <Button 
  8.         android:id="@+id/startBtn" 
  9.         android:layout_width="match_parent" 
  10.         android:layout_height="wrap_content" 
  11.         android:text="启动 Service" 
  12.         /> 
  13.     <Button 
  14.         android:id="@+id/stopBtn" 
  15.         android:layout_width="match_parent" 
  16.         android:layout_height="wrap_content" 
  17.         android:text="停止 Service" 
  18.         /> 
  19. </LinearLayout> 
 在AndroidManifest.xml文件中添加16~21行的声明
 
 
 
  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android" 
  3.       package="com.android.service.activity" 
  4.       android:versionCode="1" 
  5.       android:versionName="1.0"> 
  6.     <uses-sdk android:minSdkVersion="10" /> 
  7.  
  8.     <application android:icon="@drawable/icon" android:label="@string/app_name"> 
  9.         <activity android:name=".MainActivity" 
  10.                   android:label="@string/app_name"> 
  11.             <intent-filter> 
  12.                 <action android:name="android.intent.action.MAIN" /> 
  13.                 <category android:name="android.intent.category.LAUNCHER" /> 
  14.             </intent-filter> 
  15.         </activity> 
  16.     <service android:name=".ServiceDemo" >    
  17.              <intent-filter> 
  18.                 <action android:name="android.intent.action.MAIN" /> 
  19.                 <category android:name="android.intent.category.LAUNCHER" /> 
  20.             </intent-filter> 
  21.     </service>    
  22.     </application> 
  23. </manifest> 
效果图:

当点击按钮时,先后执行了Service中onCreate()->onStart()这两个方法,LogCat显示如下:

当点击 按钮时,Service则执行了onDestroy()方法,LogCat显示如下:

当点击按钮,进入Settings(设置)->Applications(应用)->Running Services(正在运行的服务)看一下我们新启动了的服务,效果图如下:

2.Context.bindService()方式启动:
 
Context.bindService()方式的生命周期: 
绑定时,bindService -> onCreate() –> onBind()
调用者退出了,即解绑定时,Srevice就会unbindService –>onUnbind() –> onDestory()
 
用Context.bindService()方法启动服务,在服务未被创建时,系统会先调用服务的onCreate()方法,接着调用onBind()方法。这个时候调用者和服务绑定在一起,调用者退出了,系统就会先调用服务的onUnbind()方法,接着调用onDestroy()方法。如果调用bindService()方法前服务已经被绑定,多次调用bindService()方法并不会导致多次创建服务及绑定(也就是说onCreate()和onBind()方法并不会被多次调用)。如果调用者希望与正在绑定的服务解除绑定,可以调用unbindService()方法,调用该方法也会导致系统调用服务的onUnbind()-->onDestroy()方法。
 
②Context.bindService()方式启动 Service的方法:
绑定Service需要三个参数:bindService(intent, conn, Service.BIND_AUTO_CREATE);
第一个:Intent对象
第二个:ServiceConnection对象,创建该对象要实现它的onServiceConnected()和 onServiceDisconnected()来判断连接成功或者是断开连接
第三个:如何创建Service,一般指定绑定的时候自动创建

 下面是具体的例子:

MainActivity.java

 
 
  1. package com.android.bindservice.activity;  
  2.  
  3. import android.app.Activity;  
  4. import android.app.Service;  
  5. import android.content.ComponentName;  
  6. import android.content.Intent;  
  7. import android.content.ServiceConnection;  
  8. import android.os.Bundle;  
  9. import android.os.IBinder;  
  10. import android.util.Log;  
  11. import android.view.View;  
  12. import android.view.View.OnClickListener;  
  13. import android.widget.Button;  
  14.  
  15. public class MainActivity extends Activity {  
  16.     // 声明Button  
  17.     private Button startBtn,stopBtn,bindBtn,unbindBtn;  
  18.     @Override 
  19.     public void onCreate(Bundle savedInstanceState) {  
  20.         super.onCreate(savedInstanceState);  
  21.         // 设置当前布局视图  
  22.         setContentView(R.layout.main);  
  23.         // 实例化Button  
  24.         startBtn = (Button)findViewById(R.id.startBtn1);  
  25.         stopBtn = (Button)findViewById(R.id.stopBtn2);  
  26.         bindBtn = (Button)findViewById(R.id.bindBtn3);  
  27.         unbindBtn = (Button)findViewById(R.id.unbindBtn4);  
  28.           
  29.         // 添加监听器  
  30.         startBtn.setOnClickListener(startListener);  
  31.         stopBtn.setOnClickListener(stopListener);  
  32.         bindBtn.setOnClickListener(bindListener);  
  33.         unbindBtn.setOnClickListener(unBindListener);  
  34.           
  35.     }  
  36.     // 启动Service监听器  
  37.     private OnClickListener startListener = new OnClickListener() {  
  38.         @Override 
  39.         public void onClick(View v) {  
  40.             // 创建Intent  
  41.             Intent intent = new Intent();  
  42.             // 设置Class属性  
  43.             intent.setClass(MainActivity.this, BindService.class);  
  44.             // 启动该Service  
  45.             startService(intent);  
  46.         }  
  47.     };  
  48.       
  49.     // 停止Service监听器  
  50.     private OnClickListener stopListener = new OnClickListener() {  
  51.         @Override 
  52.         public void onClick(View v) {  
  53.             // 创建Intent  
  54.             Intent intent = new Intent();  
  55.             // 设置Class属性  
  56.             intent.setClass(MainActivity.this, BindService.class);  
  57.             // 启动该Service  
  58.             stopService(intent);  
  59.         }  
  60.     };  
  61.       
  62.    // 连接对象  
  63.    private ServiceConnection conn = new ServiceConnection() {  
  64.         @Override 
  65.         public void onServiceConnected(ComponentName name, IBinder service) {  
  66.             Log.i("Service""连接成功!");  
  67.         }  
  68.         @Override 
  69.         public void onServiceDisconnected(ComponentName name) {  
  70.             Log.i("Service""断开连接!");  
  71.         }  
  72.     };  
  73.       
  74.     // 綁定Service监听器  
  75.     private OnClickListener bindListener = new OnClickListener() {  
  76.         @Override 
  77.         public void onClick(View v) {  
  78.             // 创建Intent  
  79.             Intent intent = new Intent();  
  80.             // 设置Class属性  
  81.             intent.setClass(MainActivity.this, BindService.class);  
  82.            
  83.             // 绑定Service  
  84.             bindService(intent, conn, Service.BIND_AUTO_CREATE);  
  85.         }  
  86.     };  
  87.           
  88.     // 解除绑定Service监听器  
  89.     private OnClickListener unBindListener = new OnClickListener() {  
  90.         @Override 
  91.         public void onClick(View v) {  
  92.             // 创建Intent  
  93.             Intent intent = new Intent();  
  94.             // 设置Class属性  
  95.             intent.setClass(MainActivity.this, BindService.class);  
  96.             // 解除绑定Service  
  97.             unbindService(conn);  
  98.         }  
  99.     };    

BindService.java

 
 
  1. package com.android.bindservice.activity;  
  2.  
  3. import android.app.Service;  
  4. import android.content.Intent;  
  5. import android.os.IBinder;  
  6. import android.util.Log;  
  7.  
  8. public class BindService extends Service{  
  9.       
  10.     private static final String TAG="Test";  
  11.       
  12.     //返回null  
  13.     public IBinder onBind(Intent intent) {  
  14.         Log.i(TAG, "Service onBind--->");  
  15.         return null;  
  16.     }  
  17.     // Service创建时调用  
  18.     public void onCreate() {  
  19.         Log.i(TAG, "Service onCreate--->");  
  20.     }  
  21.     // 当客户端调用startService()方法启动Service时,该方法被调用  
  22.     public void onStart(Intent intent, int startId) {  
  23.         Log.i(TAG, "Service onStart--->");  
  24.     }  
  25.     // 当Service不再使用时调用  
  26.     public void onDestroy() {  
  27.         Log.i(TAG, "Service onDestroy--->");  
  28.     }  
  29.     // 当解除绑定时调用  
  30.     public boolean onUnbind(Intent intent) {    
  31.         Log.i(TAG, "Service onUnbind--->");    
  32.         return super.onUnbind(intent);    
  33.     }    
  34. }  
  35.  

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.     <Button   
  8.         android:text="启动Service"   
  9.         android:id="@+id/startBtn1"   
  10.         android:layout_width="match_parent"   
  11.         android:layout_height="wrap_content" 
  12.         />    
  13.     <Button   
  14.         android:text="停止Service"   
  15.         android:id="@+id/stopBtn2"   
  16.         android:layout_width="match_parent"   
  17.         android:layout_height="wrap_content" 
  18.         />    
  19.     <Button   
  20.         android:text="绑定Service"   
  21.         android:id="@+id/bindBtn3"   
  22.         android:layout_width="match_parent"   
  23.         android:layout_height="wrap_content" 
  24.         /> 
  25.     <Button   
  26.         android:text="解除绑定"   
  27.         android:id="@+id/unbindBtn4"   
  28.         android:layout_width="match_parent"   
  29.         android:layout_height="wrap_content" 
  30.         /> 
  31. </LinearLayout> 

 在AndroidManifest.xml文件中添加16~21行的声明

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

效果图:

当点击按钮时,先后执行了Service中onCreate()->onStart()这两个方法,LogCat显示如下:

 

当点击按钮,则Service执行了onUnbind()方法,LogCat显示如下:

 

当点击按钮,则Service执行了onUnbind()方法,LogCat显示如下:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值