//通知顯示
PendingIntent contentIntent = PendingIntent.getService(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setTicker("SMS")
.setPriority(Notification.PRIORITY_MIN)
.setContentIntent(contentIntent)
.setContentTitle("我怕誰!")
.setAutoCancel(true)
.setContentText("SMSContext")
.setWhen(System.currentTimeMillis());
//把service設置爲前臺運行,避免手機系統自動殺掉改服務。
startForeground(startId, builder.build());
或者
Notification.Builder builder = new Notification.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setChannelId(CHANNEL_ONE_ID);
builder.setContentTitle("SMS");
builder.setContentText("SMSListener is runing...");
startForeground(NOTICE_ID,builder.build());
複製代碼
//兼容版本服務
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//8.0上啓動前臺服務
startForegroundService(new Intent(this, ChannlService.class));
tv_runstatus.postDelayed(new Runnable() {
@Override
public void run() {
startService(new Intent(MainActivity.this, ChannlService.class));
}
}, 500);
} else {
startService(new Intent(this, ChannlService.class));
}複製代碼
避免了用戶看到通知欄,也是前臺服務 onstartCommon會調用兩次,本身處理下邏輯判斷便可bash