簡短問題:如何使用NotificationCompat.Builder和startForeground?
我試圖使用NotificationCompat.Builder類來創建將用於該服務的通知,但由於某種原因,我要麼沒有看到通知,要麼可以當服務應該被銷燬時(或停止在前臺)時,不會取消它。
我的代碼:
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
final String action = intent == null ? null : intent.getAction();
Log.d("APP", "service action:" + action);
if (ACTION_ENABLE_STICKING.equals(action)) {
final NotificationCompat.Builder builder = new Builder(this);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle("content title");
builder.setTicker("ticker");
builder.setContentText("content text");
final Intent notificationIntent = new Intent(this, FakeActivity.class);
final PendingIntent pi = PendingIntent.getActivity(this, 0, notificationIntent, 0);
builder.setContentIntent(pi);
final Notification notification = builder.build();
// notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
// notification.flags |= Notification.FLAG_NO_CLEAR;
// notification.flags |= Notification.FLAG_ONGOING_EVENT;
startForeground(NOTIFICATION_ID, notification);
// mNotificationManager.notify(NOTIFICATION_ID, notification);
} else if (ACTION_DISABLE_STICKING.equals(action)) {
stopForeground(true);
stopSelf();
// mNotificationManager.cancel(NOTIFICATION_ID);
}
return super.onStartCommand(intent, flags, startId);
}
註釋的命令是我的考驗,使其工作。由於某種原因沒有工作。
我甚至添加了一個假活動,因爲它需要一個contentIntent,但它仍然不起作用。
任何人都可以請幫忙嗎?
這個帖子,有公認的答案一起,幾天努力尋找解決方案後,固定我的問題。 – 2016-06-20 00:14:23