Android Service初解

Service是什麼呢?

他同Activity相比,最大的不同就是他沒有專門的Layout展示界面,他默默的工作在App的後臺

雖然除了少數幾種情況,我們不需要使用Service,但我們也有必要了解一下Service的使用方法

我們知道Activity由於其自有缺陷,如果Activity產生了跳轉,那麼當前Activity的工作就會被完全停止。

但是有時候我們希望在聽歌、打接電話、下載文件的過程中繼續別的活動,這時候我們就應該使用Service,不論前端的Activity如何變幻,只要Service沒有被停止,Service就會繼續他的工作。

Service的工作流程圖如下:



使用Service首先需要新建一個繼承自Service的類

package com.example.testservice;

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

public class ServiceTest extends Service {

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		Toast.makeText(getApplicationContext(), "已經綁定好了", Toast.LENGTH_SHORT).show();
		return null;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Toast.makeText(getApplicationContext(), "服務解除", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		Toast.makeText(getApplicationContext(), "已經綁定好了", Toast.LENGTH_SHORT).show();
	}

}


接着我們需要在AndroidManifest.xml文件中對Service進行一次註冊


<service android:name="ServiceTest"></service>

下面我們來看看調用Service服務的兩種方案:

一、startService

Intent startService = new Intent(MainActivity.this,ServiceTest.class);
startService(startService);

二、bindService

Intent startService = new Intent(MainActivity.this,ServiceTest.class);
ServiceConnection serviceConnect = null;
bindService(startService,serviceConnect,Context.BIND_AUTO_CREATE);

這兩種方法最大的不同在於bindService會在APP程序退出時自動解除對於Service的綁定,而startService則需要手動終止服務,所以我們需要根據自己的需要選擇合適的方法調用Service



發佈了28 篇原創文章 · 獲贊 7 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章