Android Service徹底解析,關於服務你所需知道的一切(上)

Service的基本用法


關於Service最基本的用法天然就是如何啓動一個Service了,啓動Service的方法和啓動Activity很相似,都須要藉助Intent來實現,下面咱們就經過一個具體的例子來看一下。python

新建一個Android項目,項目名就叫ServiceTest,這裏我選擇使用4.0的API。android

 

而後新建一個MyService繼承自Service,並重寫父類的onCreate()、onStartCommand()和onDestroy()方法,以下所示:面試

public class MyService extends Service { public static final String TAG = "MyService"; @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate() executed"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand() executed"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy() executed"); } @Override public IBinder onBind(Intent intent) { return null; } }

 

能夠看到,咱們只是在onCreate()、onStartCommand()和onDestroy()方法中分別打印了一句話,並無進行其它任何的操做。服務器

 

而後打開或新建activity_main.xml做爲程序的主佈局文件,代碼以下所示:app

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >
 
    <Button android:id="@+id/start_service" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Start Service" />
 
    <Button android:id="@+id/stop_service" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Stop Service" />
 
</LinearLayout>

 

咱們在佈局文件中加入了兩個按鈕,一個用於啓動Service,一個用於中止Service。框架

 

而後打開或新建MainActivity做爲程序的主Activity,在裏面加入啓動Service和中止Service的邏輯,代碼以下所示:ide

public class MainActivity extends Activity implements OnClickListener { private Button startService; private Button stopService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startService = (Button) findViewById(R.id.start_service); stopService = (Button) findViewById(R.id.stop_service); startService.setOnClickListener(this); stopService.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.start_service: Intent startIntent = new Intent(this, MyService.class); startService(startIntent); break; case R.id.stop_service: Intent stopIntent = new Intent(this, MyService.class); stopService(stopIntent); break; default: break; } } }

 

能夠看到,在Start Service按鈕的點擊事件裏,咱們構建出了一個Intent對象,並調用startService()方法來啓動MyService。而後在Stop Serivce按鈕的點擊事件裏,咱們一樣構建出了一個Intent對象,並調用stopService()方法來中止MyService。代碼的邏輯很是簡單,相信不須要我再多作解釋了吧。 佈局

 

另外須要注意,項目中的每個Service都必須在AndroidManifest.xml中註冊才行,因此還須要編輯AndroidManifest.xml文件,代碼以下所示:學習

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.servicetest" android:versionCode="1" android:versionName="1.0" >
 
    <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="17" />
 
    <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > …… <service android:name="com.example.servicetest.MyService" >
        </service>
    </application>
 
</manifest>

 

這樣的話,一個簡單的帶有Service功能的程序就寫好了,如今咱們將程序運行起來,並點擊一下Start Service按鈕,能夠看到LogCat的打印日誌以下:測試

 

 

 

也就是說,當啓動一個Service的時候,會調用該Service中的onCreate()和onStartCommand()方法。

 

那麼若是我再點擊一次Start Service按鈕呢?這個時候的打印日誌以下:

 

 

 

能夠看到,此次只有onStartCommand()方法執行了,onCreate()方法並無執行,爲何會這樣呢?這是因爲onCreate()方法只會在Service第一次被建立的時候調用,若是當前Service已經被建立過了,無論怎樣調用startService()方法,onCreate()方法都不會再執行。所以你能夠再多點擊幾回Start Service按鈕試一次,每次都只會有onStartCommand()方法中的打印日誌。

 

咱們還能夠到手機的應用程序管理界面來檢查一下MyService是否是正在運行,以下圖所示:

 

 

 

恩,MyService確實是正在運行的,即便它的內部並無執行任何的邏輯。

 

回到ServiceTest程序,而後點擊一下Stop Service按鈕就能夠將MyService中止掉了。

 

Service和Activity通訊


上面咱們學習了Service的基本用法,啓動Service以後,就能夠在onCreate()或onStartCommand()方法裏去執行一些具體的邏輯了。不過這樣的話Service和Activity的關係並不大,只是Activity通知了Service一下:「你能夠啓動了。」而後Service就去忙本身的事情了。那麼有沒有什麼辦法能讓它們倆的關聯更多一些呢?好比說在Activity中能夠指定讓Service去執行什麼任務。固然能夠,只須要讓Activity和Service創建關聯就行了。

 

觀察MyService中的代碼,你會發現一直有一個onBind()方法咱們都沒有使用到,這個方法其實就是用於和Activity創建關聯的,修改MyService中的代碼,以下所示:

public class MyService extends Service { public static final String TAG = "MyService"; private MyBinder mBinder = new MyBinder(); @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate() executed"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand() executed"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy() executed"); } @Override public IBinder onBind(Intent intent) { return mBinder; } class MyBinder extends Binder { public void startDownload() { Log.d("TAG", "startDownload() executed"); // 執行具體的下載任務
 } } }

 

這裏咱們新增了一個MyBinder類繼承自Binder類,而後在MyBinder中添加了一個startDownload()方法用於在後臺執行下載任務,固然這裏並非真正地去下載某個東西,只是作個測試,因此startDownload()方法只是打印了一行日誌。

 

而後修改activity_main.xml中的代碼,在佈局文件中添加用於綁定Service和取消綁定Service的按鈕:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >
 
    <Button android:id="@+id/start_service" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Start Service" />
 
    <Button android:id="@+id/stop_service" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Stop Service" />
 
    <Button android:id="@+id/bind_service" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Bind Service" />
    
    <Button android:id="@+id/unbind_service" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Unbind Service"
        />
    
</LinearLayout>

 

接下來再修改MainActivity中的代碼,讓MainActivity和MyService之間創建關聯,代碼以下所示:

public class MainActivity extends Activity implements OnClickListener { private Button startService; private Button stopService; private Button bindService; private Button unbindService; private MyService.MyBinder myBinder; private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { } @Override public void onServiceConnected(ComponentName name, IBinder service) { myBinder = (MyService.MyBinder) service; myBinder.startDownload(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startService = (Button) findViewById(R.id.start_service); stopService = (Button) findViewById(R.id.stop_service); bindService = (Button) findViewById(R.id.bind_service); unbindService = (Button) findViewById(R.id.unbind_service); startService.setOnClickListener(this); stopService.setOnClickListener(this); bindService.setOnClickListener(this); unbindService.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.start_service: Intent startIntent = new Intent(this, MyService.class); startService(startIntent); break; case R.id.stop_service: Intent stopIntent = new Intent(this, MyService.class); stopService(stopIntent); break; case R.id.bind_service: Intent bindIntent = new Intent(this, MyService.class); bindService(bindIntent, connection, BIND_AUTO_CREATE); break; case R.id.unbind_service: unbindService(connection); break; default: break; } } }

 

能夠看到,這裏咱們首先建立了一個ServiceConnection的匿名類,在裏面重寫了onServiceConnected()方法和onServiceDisconnected()方法,這兩個方法分別會在Activity與Service創建關聯和解除關聯的時候調用。在onServiceConnected()方法中,咱們又經過向下轉型獲得了MyBinder的實例,有了這個實例,Activity和Service之間的關係就變得很是緊密了。如今咱們能夠在Activity中根據具體的場景來調用MyBinder中的任何public方法,即實現了Activity指揮Service幹什麼Service就去幹什麼的功能。

 

固然,如今Activity和Service其實還沒關聯起來了呢,這個功能是在Bind Service按鈕的點擊事件裏完成的。能夠看到,這裏咱們仍然是構建出了一個Intent對象,而後調用bindService()方法將Activity和Service進行綁定。bindService()方法接收三個參數,第一個參數就是剛剛構建出的Intent對象,第二個參數是前面建立出的ServiceConnection的實例,第三個參數是一個標誌位,這裏傳入BIND_AUTO_CREATE表示在Activity和Service創建關聯後自動建立Service,這會使得MyService中的onCreate()方法獲得執行,但onStartCommand()方法不會執行。

 

而後如何咱們想解除Activity和Service之間的關聯怎麼辦呢?調用一下unbindService()方法就能夠了,這也是Unbind Service按鈕的點擊事件裏實現的邏輯。

如今讓咱們從新運行一下程序吧,在MainActivity中點擊一下Bind Service按鈕,LogCat裏的打印日誌以下圖所示:

 

 

 

另外須要注意,任何一個Service在整個應用程序範圍內都是通用的,即MyService不只能夠和MainActivity創建關聯,還能夠和任何一個Activity創建關聯,並且在創建關聯時它們均可以獲取到相同的MyBinder實例。

 

如何銷燬Service


在Service的基本用法這一部分,咱們介紹了銷燬Service最簡單的一種狀況,點擊Start Service按鈕啓動Service,再點擊Stop Service按鈕中止Service,這樣MyService就被銷燬了,能夠看到打印日誌以下所示:

 

 

 

那麼若是咱們是點擊的Bind Service按鈕呢?因爲在綁定Service的時候指定的標誌位是BIND_AUTO_CREATE,說明點擊Bind Service按鈕的時候Service也會被建立,這時應該怎麼銷燬Service呢?其實也很簡單,點擊一下Unbind Service按鈕,將Activity和Service的關聯解除就能夠了。

 

先點擊一下Bind Service按鈕,再點擊一下Unbind Service按鈕,打印日誌以下所示:

 

 

 

以上這兩種銷燬的方式都很好理解。那麼若是咱們既點擊了Start Service按鈕,又點擊了Bind Service按鈕會怎麼樣呢?這個時候你會發現,無論你是單獨點擊Stop Service按鈕仍是Unbind Service按鈕,Service都不會被銷燬,必要將兩個按鈕都點擊一下,Service纔會被銷燬。也就是說,點擊Stop Service按鈕只會讓Service中止,點擊Unbind Service按鈕只會讓Service和Activity解除關聯,一個Service必需要在既沒有和任何Activity關聯又處理中止狀態的時候纔會被銷燬。

 

爲了證明一下,咱們在Stop Service和Unbind Service按鈕的點擊事件裏面加入一行打印日誌:

public void onClick(View v) { switch (v.getId()) { case R.id.start_service: Intent startIntent = new Intent(this, MyService.class); startService(startIntent); break; case R.id.stop_service: Log.d("MyService", "click Stop Service button"); Intent stopIntent = new Intent(this, MyService.class); stopService(stopIntent); break; case R.id.bind_service: Intent bindIntent = new Intent(this, MyService.class); bindService(bindIntent, connection, BIND_AUTO_CREATE); break; case R.id.unbind_service: Log.d("MyService", "click Unbind Service button"); unbindService(connection); break; default: break; } }

 

而後從新運行程序,先點擊一下Start Service按鈕,再點擊一下Bind Service按鈕,這樣就將Service啓動起來,並和Activity創建了關聯。而後點擊Stop Service按鈕後Service並不會銷燬,再點擊一下Unbind Service按鈕,Service就會銷燬了,打印日誌以下所示:

 

 

 

咱們應該始終記得在Service的onDestroy()方法裏去清理掉那些再也不使用的資源,防止在Service被銷燬後還會有一些再也不使用的對象仍佔用着內存。

 

Service和Thread的關係


很多Android初學者均可能會有這樣的疑惑,Service和Thread到底有什麼關係呢?何時應該用Service,何時又應該用Thread?答案可能會有點讓你吃驚,由於Service和Thread之間沒有任何關係!

 

之因此有很多人會把它們聯繫起來,主要就是由於Service的後臺概念。Thread咱們你們都知道,是用於開啓一個子線程,在這裏去執行一些耗時操做就不會阻塞主線程的運行。而Service咱們最初理解的時候,總會以爲它是用來處理一些後臺任務的,一些比較耗時的操做也能夠放在這裏運行,這就會讓人產生混淆了。可是,若是我告訴你Service實際上是運行在主線程裏的,你還會以爲它和Thread有什麼關係嗎?讓咱們看一下這個殘酷的事實吧。

 

 

在MainActivity的onCreate()方法里加入一行打印當前線程id的語句:

Log.d("MyService", "MainActivity thread id is " + Thread.currentThread().getId());

 

而後在MyService的onCreate()方法裏也加入一行打印當前線程id的語句:

Log.d("MyService", "MyService thread id is " + Thread.currentThread().getId());

 

如今從新運行一下程序,並點擊Start Service按鈕,會看到以下打印日誌:

 

 

能夠看到,它們的線程id徹底是同樣的,由此證明了Service確實是運行在主線程裏的,也就是說若是你在Service裏編寫了很是耗時的代碼,程序一定會出現ANR的。

 

你可能會驚呼,這不是坑爹麼!?那我要Service又有何用呢?其實你們不要把後臺和子線程聯繫在一塊兒就好了,這是兩個徹底不一樣的概念。Android的後臺就是指,它的運行是徹底不依賴UI的。即便Activity被銷燬,或者程序被關閉,只要進程還在,Service就能夠繼續運行。好比說一些應用程序,始終須要與服務器之間始終保持着心跳鏈接,就可使用Service來實現。你可能又會問,前面不是剛剛驗證過Service是運行在主線程裏的麼?在這裏一直執行着心跳鏈接,難道就不會阻塞主線程的運行嗎?固然會,可是咱們能夠在Service中再建立一個子線程,而後在這裏去處理耗時邏輯就沒問題了。

 

額,既然在Service裏也要建立一個子線程,那爲何不直接在Activity裏建立呢?這是由於Activity很難對Thread進行控制,當Activity被銷燬以後,就沒有任何其它的辦法能夠再從新獲取到以前建立的子線程的實例。並且在一個Activity中建立的子線程,另外一個Activity沒法對其進行操做。可是Service就不一樣了,全部的Activity均可以與Service進行關聯,而後能夠很方便地操做其中的方法,即便Activity被銷燬了,以後只要從新與Service創建關聯,就又可以獲取到原有的Service中Binder的實例。所以,使用Service來處理後臺任務,Activity就能夠放心地finish,徹底不須要擔憂沒法對後臺任務進行控制的狀況。

 

一個比較標準的Service就能夠寫成:

 

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
	new Thread(new Runnable() {
		@Override
		public void run() {
			// 開始執行後臺任務
		}
	}).start();
	return super.onStartCommand(intent, flags, startId);
}
 
class MyBinder extends Binder {
 
	public void startDownload() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				// 執行具體的下載任務
			}
		}).start();
	}
 
}

 

建立前臺Service


Service幾乎都是在後臺運行的,一直以來它都是默默地作着辛苦的工做。可是Service的系統優先級仍是比較低的,當系統出現內存不足狀況時,就有可能會回收掉正在後臺運行的Service。若是你但願Service能夠一直保持運行狀態,而不會因爲系統內存不足的緣由致使被回收,就能夠考慮使用前臺Service。前臺Service和普通Service最大的區別就在於,它會一直有一個正在運行的圖標在系統的狀態欄顯示,下拉狀態欄後能夠看到更加詳細的信息,很是相似於通知的效果。固然有時候你也可能不只僅是爲了防止Service被回收才使用前臺Service,有些項目因爲特殊的需求會要求必須使用前臺Service,好比說墨跡天氣,它的Service在後臺更新天氣數據的同時,還會在系統狀態欄一直顯示當前天氣的信息,以下圖所示:

 

 

那麼咱們就來看一下如何才能建立一個前臺Service吧,其實並不複雜,修改MyService中的代碼,以下所示:

public class MyService extends Service {
 
	public static final String TAG = "MyService";
 
	private MyBinder mBinder = new MyBinder();
 
	@Override
	public void onCreate() {
		super.onCreate();
		Notification notification = new Notification(R.drawable.ic_launcher,
				"有通知到來", System.currentTimeMillis());
		Intent notificationIntent = new Intent(this, MainActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
				notificationIntent, 0);
		notification.setLatestEventInfo(this, "這是通知的標題", "這是通知的內容",
				pendingIntent);
		startForeground(1, notification);
		Log.d(TAG, "onCreate() executed");
	}
 
	.........
 
}

 

這裏只是修改了MyService中onCreate()方法的代碼。能夠看到,咱們首先建立了一個Notification對象,而後調用了它的setLatestEventInfo()方法來爲通知初始化佈局和數據,並在這裏設置了點擊通知後就打開MainActivity。而後調用startForeground()方法就可讓MyService變成一個前臺Service,並會將通知的圖片顯示出來。

 

如今從新運行一下程序,並點擊Start Service或Bind Service按鈕,MyService就會之前臺Service的模式啓動了,而且在系統狀態欄會彈出一個通欄圖標,下拉狀態欄後能夠看到通知的詳細內容,以下圖所示。

 

 

但願本文對你有所幫助~~若是對軟件測試、接口測試、自動化測試、面試經驗交流感興趣能夠加入咱們。642830685,免費領取最新軟件測試大廠面試資料和Python自動化、接口、框架搭建學習資料!技術大牛解惑答疑,同行一塊兒交流。

相關文章
相關標籤/搜索