Service沒(méi)有用戶(hù)界面,運(yùn)行在后臺(tái)尘盼。和Activity一樣,都是運(yùn)行在主線(xiàn)程中烦绳。如果要做CPU耗時(shí)操作和阻塞操作卿捎,那就應(yīng)該創(chuàng)建一個(gè)新的線(xiàn)程,防止導(dǎo)致系統(tǒng)提示“APP無(wú)響應(yīng)”(ANR) 径密。
Service兩種使用方式:
1.通過(guò)startService()啟動(dòng)
執(zhí)行一些操作午阵,但不需要返回執(zhí)行結(jié)果。比如通過(guò)網(wǎng)絡(luò)上傳或下載文件享扔。完成操作后底桂,需要stopSelf()或者stopService()顯式停止Service。這種啟動(dòng)方式使得Service和啟動(dòng)它的組件無(wú)關(guān)惧眠,即使啟動(dòng)它的組件停止運(yùn)行了籽懦,該Service還能繼續(xù)運(yùn)行。需要繼承Service,并重寫(xiě)onStartCommand()氛魁。
2.通過(guò)bindService()綁定
提供類(lèi)似client-server接口猫十,從而允許組件和Service交互,比如發(fā)送請(qǐng)求呆盖,獲取執(zhí)行結(jié)果拖云。需要繼承Service,并重寫(xiě)onBind()。
IntentService是Service的子類(lèi),使用一個(gè)工作線(xiàn)程處理所有請(qǐng)求,所有請(qǐng)求排隊(duì)處理爆存。如果需要同時(shí)處理多個(gè)請(qǐng)求,則需要在實(shí)現(xiàn)Service的子類(lèi)尤筐,每收到一個(gè)請(qǐng)求時(shí),創(chuàng)建一個(gè)線(xiàn)程去執(zhí)行一個(gè)請(qǐng)求洞就。
使用IntentService只需要實(shí)現(xiàn)一個(gè)構(gòu)造函數(shù)和重寫(xiě)onHandleIntent()
public class HelloIntentService extends IntentService {
/**
- A constructor is required, and must call the super IntentService(String)
- constructor with a name for the worker thread.
*/
public HelloIntentService() {
super("HelloIntentService");
}
/**
- The IntentService calls this method from the default worker thread with
- the intent that started the service. When this method returns, IntentService
- stops the service, as appropriate.
/
@Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
long endTime = System.currentTimeMillis() + 51000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
}
}
onStartCommand()返回值:
START_NOT_STICKY 系統(tǒng)停掉Service后不重啟它
START_STICKY 系統(tǒng)停掉Service后等有資源時(shí)會(huì)重啟它盆繁,但不會(huì)傳遞最后一個(gè)請(qǐng)求
START_REDELIVER_INTENT 系統(tǒng)停掉Service后等有資源時(shí)會(huì)重啟它,會(huì)傳遞最后一個(gè)請(qǐng)求旬蟋。適合類(lèi)似下載文件等需要立即恢復(fù)的操作
如果想讓Service一直運(yùn)行油昂,可使用前臺(tái)Service
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);