Android Service


  一.Service

服務是運行在後臺的一段代碼。它可以運行在它自己的進程,也可以運行在其他應用程序進程的上下文(context)裏面,這取決於自身的需要。其它的組件可以綁定到一個服務Service)上面,通過遠程過程調用(RPC)來調用這個方法。例如媒體播放器的服務,當用戶退出媒體選擇用戶界面,仍然希望音樂依然可以繼續播放,這時就是由服務 service)來保證當用戶界面關閉時音樂繼續播放的。

 

它跟Activity的級別差不多,但是他不能自己運行,需要通過某一個Activity或者其他Context對象來調用, Context.startService()Context.bindService()

兩種啓動Service的方式有所不同。這裏要說明一下的是如果你在ServiceonCreate或者onStart做一些很耗時間的事情,最好在Service裏啓動一個線程來完成,因爲Service是跑在主線程中,會影響到你的UI操作或者阻塞主線程中的其他事情。

什麼時候需要Service呢?比如播放多媒體的時候用戶啓動了其他Activity這個時候程序要在後臺繼續播放,比如檢測SD卡上文件的變化,再或者在後臺記錄你地理信息位置的改變等等。

  二.使用Service

private String MY_ACTION = "com.demo.MyService";
啓動Service

			Intent intent = new Intent();
			intent.setAction(MY_ACTION);
			startService(intent);

停止Service

			Intent intent = new Intent();
			intent.setAction(MY_ACTION);
			stopService(intent);

綁定Service

			Intent intent = new Intent();
			intent.setAction(MY_ACTION);
			unbindService(conn);

解除綁定Service

			Intent intent = new Intent();
			intent.setAction(MY_ACTION);
			bindService(intent, conn, Service.BIND_AUTO_CREATE);
	private ServiceConnection conn = new ServiceConnection(){
		public void onServiceConnected(ComponentName name, IBinder service) {
			System.out.println("連接成功!");
			showMessage("連接成功!");
		}
		public void onServiceDisconnected(ComponentName name) {
			System.out.println("斷開連接!");
			showMessage("斷開連接!");
		}
	};

Service類代碼:

package com.demo;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MyService extends Service {

	public IBinder onBind(Intent intent) {
		System.out.println("Service onBind");
		return null;
	}
	
	public void onCreate() {
		System.out.println("Service onCreate");
		super.onCreate();
	}
	
	public void onStart(Intent intent, int startId) {
		System.out.println("Service onStart");
		super.onStart(intent, startId);
	}
	
	public void onDestroy() {
		System.out.println("Service onDestory");
		super.onDestroy();
	}
	
}

AndroidManifest.xml

        <service android:name="MyService">
        	<intent-filter>
        		<action android:name="com.demo.MyService"/>
        	</intent-filter>
        </service>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章