天天看点

Android中Service组件详解 .(转载)

Service是Android的四大组件之一,以下是我结合Android Doc和网上资料的学习总结,有不准确的地方请高手指出,互相学习嘛。。。

这篇文章讲的非常好 http://www.2cto.com/kf/201404/296058.html

1.Service是什么

Service是Android的四大组件之一,即Android系统的服务(不是一个线程,是主程序的一部分),与Activity不同,它是不能与用户交互的,不能自己启动的,需要调用Context.startService()来启动,运行后台,如果我们退出应用时,Service进程并没有结束,它仍然在后台行。比如我们播放音乐的时候,有可能想边听音乐边干些其他事情,当我们退出播放音乐的应用,如果不用Service,我们就听不到歌了,所以这时候就得用到Service了。

2.Service生命周期

①onCreate() 创建Service

②onStart(Intent intent, int startId) 启动Service

③onDestroy() 销毁Service

④onBind() 返回一个IBinder接口对象给Service

3.启动和停止Service

①启动:startService(Intent intent)来启动Service,这时Service会调用自身的onCreate()方法(该Service未创建),接着调用onStart()方法。

②停止:stopService(Intent intent)来停止Service,这时Service会调用自身的onDestory()方法。

4.绑定Service

调用bindService(Intent service, ServiceConnection conn, int flags)来绑定一个Service,这时Service会调用自身的onCreate()方法(该Service未创建),接着调用onBind()方法返回客户端一个IBinder接口对象。(注意:如果返回null,ServiceConnection对象的方法将不会被调用)

参数①service:Intent对象 。

参数②conn:ServiceConnection对象,实现其onServiceConnected()和onServiceDisconnected()在连接成功和断开连接时处理。

参数③flags:Service创建的方式,一般用Service.BIND_AUTO_CREATE表示绑定时自动创建。

5.示例代码,下载android_service.rar

MainActivity用来操作Service

view plain copy to clipboard print ?

  1. public class MainActivity extends Activity {  
  2.     private Button startBtn;  
  3.     private Button stopBtn;  
  4.     private Button bindBtn;  
  5.     private Button unBindBtn;  
  6.     private static final String TAG = "MainActivity";  
  7.     private LocalService myService;  
  8.     @Override  
  9.     public void onCreate(Bundle savedInstanceState) {  
  10.         super.onCreate(savedInstanceState);  
  11.         setContentView(R.layout.main);  
  12.         startBtn = (Button) findViewById(R.id.start);  
  13.         stopBtn = (Button) findViewById(R.id.stop);  
  14.         bindBtn = (Button) findViewById(R.id.bind);  
  15.         unBindBtn = (Button) findViewById(R.id.unbind);  
  16.         startBtn.setOnClickListener(new MyOnClickListener());  
  17.         stopBtn.setOnClickListener(new MyOnClickListener());  
  18.         bindBtn.setOnClickListener(new MyOnClickListener());  
  19.         unBindBtn.setOnClickListener(new MyOnClickListener());  
  20.     }  
  21.     class MyOnClickListener implements OnClickListener {  
  22.         @Override  
  23.         public void onClick(View v) {  
  24.             Intent intent = new Intent();  
  25.             intent.setClass(MainActivity.this, LocalService.class);  
  26.             switch (v.getId()) {  
  27.             case R.id.start:  
  28.                 // 启动Service   
  29.                 startService(intent);  
  30.                 break;  
  31.             case R.id.stop:  
  32.                 // 停止Service   
  33.                 stopService(intent);  
  34.                 break;  
  35.             case R.id.bind:  
  36.                 // 绑定Service   
  37.                 bindService(intent, conn, Service.BIND_AUTO_CREATE);  
  38.                 break;  
  39.             case R.id.unbind:  
  40.                 // 解除Service   
  41.                 unbindService(conn);  
  42.                 break;  
  43.             }  
  44.         }  
  45.     }  
  46.     private ServiceConnection conn = new ServiceConnection() {  
  47.         @Override  
  48.         public void onServiceConnected(ComponentName name, IBinder service) {  
  49.             Log.e(TAG, "连接成功");  
  50.             // 当Service连接建立成功后,提供给客户端与Service交互的对象(根据Android Doc翻译的,不知道准确否。。。。)  
  51.             myService = ((LocalService.LocalBinder) service).getService();  
  52.         }  
  53.         @Override  
  54.         public void onServiceDisconnected(ComponentName name) {  
  55.             Log.e(TAG, "断开连接");  
  56.             myService = null;  
  57.         }  
  58.     };  
  59. }  

Service实体类

view plain copy to clipboard print ?

  1. public class LocalService extends Service {  
  2.     private static final String TAG = "MyService";  
  3.     private final IBinder myBinder = new LocalBinder();  
  4.     @Override  
  5.     public IBinder onBind(Intent intent) {  
  6.         Log.e(TAG, "onBind()");  
  7.         Toast.makeText(this, "onBind()", Toast.LENGTH_SHORT).show();  
  8.         return myBinder;  
  9.     }  
  10.     // 调用startService方法或者bindService方法时创建Service时(当前Service未创建)调用该方法  
  11.     @Override  
  12.     public void onCreate() {  
  13.         Log.e(TAG, "onCreate()");  
  14.         Toast.makeText(this, "onCreate()", Toast.LENGTH_SHORT).show();  
  15.     }  
  16.     // 调用startService方法启动Service时调用该方法  
  17.     @Override  
  18.     public void onStart(Intent intent, int startId) {  
  19.         Log.e(TAG, "onStart()");  
  20.         Toast.makeText(this, "onStart()", Toast.LENGTH_SHORT).show();  
  21.     }  
  22.     // Service创建并启动后在调用stopService方法或unbindService方法时调用该方法  
  23.     @Override  
  24.     public void onDestroy() {  
  25.         Log.e(TAG, "onDestroy()");  
  26.         Toast.makeText(this, "onDestroy()", Toast.LENGTH_SHORT).show();  
  27.     }  
  28.     //提供给客户端访问   
  29.     public class LocalBinder extends Binder {  
  30.         LocalService getService() {  
  31.             return LocalService.this;  
  32.         }  
  33.     }  
  34. }  

需要在AndroidManifest.xml中注册建立的Service

view plain copy to clipboard print ?

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

布局文件main.xml

view plain copy to clipboard print ?

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical" android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent">  
  5.     <Button android:id="@+id/start" android:layout_width="wrap_content"  
  6.         android:layout_height="wrap_content" android:text="启动Service" />  
  7.     <Button android:id="@+id/stop" android:layout_width="wrap_content"  
  8.         android:layout_height="wrap_content" android:text="停止Service" />  
  9.     <Button android:id="@+id/bind" android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content" android:text="绑定Service" />  
  11.     <Button android:id="@+id/unbind" android:layout_width="wrap_content"  
  12.         android:layout_height="wrap_content" android:text="解除Service" />  
  13. </LinearLayout>  

程序运行截图:

Android中Service组件详解 .(转载)

依次点击四个按钮后的打印日志:

Android中Service组件详解 .(转载)