17.4前臺服務(wù)
前臺服務(wù)是被認(rèn)為是用戶已知的正在運行的服務(wù)袭艺,當(dāng)系統(tǒng)需要釋放內(nèi)存時不會優(yōu)先殺掉該進(jìn)程乍丈。前臺進(jìn)程必須發(fā)一個?notification?在狀態(tài)欄中顯示狡蝶,直到進(jìn)程被殺死。
因為前臺服務(wù)會一直消耗一部分資源夷恍,但不像一般服務(wù)那樣會在需要的時候被殺掉,所以為了能節(jié)約資源媳维,保護電池壽命酿雪,一定要在建前臺服務(wù)的時候發(fā)notification?,提示用戶侄刽。當(dāng)然指黎,系統(tǒng)提供的方法就是必須有?notification?參數(shù)的,所以不要想著怎么把?notification?隱藏掉州丹。
@Override
publicint onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Intent notificationIntent = new Intent(this,MainActivity.class);
PendingIntent pendingIntent =PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification noti = newNotification.Builder(this)
.setContentTitle("Title")
.setContentText("Message")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pendingIntent)
.build();
startForeground(12346, noti);
return Service.START_STICKY;
}
startForeground()?方法就是將服務(wù)設(shè)為前臺服務(wù)袋励,參數(shù)12346就是這個通知唯一的id,只要不為0即可当叭。
(轉(zhuǎn)自:http://www.tuicool.com/articles/iu22QnF)