Android使用前臺服務和普通服務在代碼上的區(qū)別也就是一個Notification会宪,代碼如下:
public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Logger.t("MyService").i("onCreate");
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
builder.setContentTitle("title");
builder.setContentText("text");
builder.setWhen(System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pt = PendingIntent.getActivity(this, 0, notificationIntent, 0);
builder.setContentIntent(pt);
Notification notification = builder.build();
startForeground(1, notification);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Logger.t("MyService").i("onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Logger.t("MyService").i("onDestroy");
}
}
要從前臺刪除服務,需要調用stopForeground()方法,這個方法需要一個布爾型參數,指示是否刪除狀態(tài)欄通知温鸽。這個方法不終止服務。但是,如果你終止了正在運行的前臺服務涤垫,那么通知也會被刪除姑尺。
下面談談這期間遇到的蛋疼的事,直接上圖對比:
before.gif
after.gif
一開始我寫完代碼運行蝠猬,一直是圖before的效果切蟋,檢查代碼一遍又一遍,也沒發(fā)現問題出在哪里榆芦,就在我?guī)捉罎⒌臅r候柄粹,想著是不是因為我沒設置小圖標,就試著設置了下圖標匆绣,結果就ok了驻右,之后我又復習了一下Notification的知識,原來不設置小圖標Notification根本顯示不出來崎淳,哎~
builder.setSmallIcon(R.mipmap.ic_launcher);
順便附上學習Notification時參考過的好文一篇——郭神(郭霖)之《Android通知欄的微技巧》