2011-08-06 44 views
6

我需要編寫一些應用程序,它將在後臺執行一些工作。這個應用程序將從自動啓動運行,不會有任何啓動GUI。 Gui可以通過點擊通知來打電話,通知將以自動啓動顯示。我擔心,當用戶清除通知時,他失去了調用這個gui的機會。我的問題是,有沒有辦法阻止用戶清除我的通知?爲我的應用程序禁用清除通知

回答

-4

你想實現一個Foreground Service

+0

前臺服務可以工作,因爲它「不適合系統在內存不足時殺死」並且需要顯示通知。但是,僅僅爲了顯示無法清除的通知而創建服務真的是最佳做法嗎? Kurro的答案似乎好得多。 – spaaarky21

4

您可能想要查看通知的「正在運行」部分中的通知。這些通知在用戶清除時不會被清除。使用Notification.FLAG_NO_CLEAR AND Notification.FLAG_ONGOING_EVENT。這應該給你想要的效果

+1

確實有兩個理由使用兩者嗎?在Android 4.2.x上,我只使用Notification.Builder.setOngoing(),並且它本身似乎阻止通知被清除。我很好奇,因爲我發現Notification.Builder似乎沒有對應於FLAG_NO_CLEAR的方法。 – spaaarky21

17

下面是一個不允許用戶清除它的通知。

Notification notification = new NotificationCompat.Builder(this) 
     .setTicker(r.getString(R.string.app_name)) 
     .setSmallIcon(R.drawable.ic_launcher) 
     .setContentTitle(r.getString(R.string.app_name)) 
     .setAutoCancel(false) 
     .setOngoing(true) 
     .build(); 

setOngoing(true)通話acheives這一點,從setAutoCancel(false)當用戶點擊該通知要離開終止通知。

如果應用被卸載或致電取消或CancelAll通知將被清除:http://developer.android.com/reference/android/app/NotificationManager.html#cancel(int)

+0

通知根本沒有顯示。 – ralphgabb

+0

@ralphspoon請問一個新的問題,並在這裏鏈接 – cja

1

雖然他雖然缺少代碼的一些幾行(通知不會顯示或顯示不會對@cja答案可能是正確的您的通知托盤)。

這是完整的工作功能:

public void createNotification() { 
    NotificationCompat.Builder notification = new NotificationCompat.Builder(this); 

    notification.setTicker("Ticker Text"); 
    notification.setSmallIcon(R.drawable.ic_launcher); 
    notification.setContentTitle("Content Title"); 
    notification.setContentText("Content Text"); 
    notification.setAutoCancel(false); 
    notification.setOngoing(true); 
    notification.setNumber(++NotificationCount); 

    Intent intent = new Intent(this, MainActivity.class); 
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0); 
    notification.setContentIntent(pIntent); 

    notification.build(); 

    NotificationManager nManger = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
    nManger.notify(NotificationID, notification.build()); 
} 

NotificationID類型爲int作爲您的通知的ID。

您可以使用此清除:

public void clear() { 
    NotificationManager oldNoti = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
    oldNoti.cancel(NotificationID); 
} 

確保notification.setAutoCancel(false);設置爲當按下清除按鈕或者滑動手勢出現時,它不會被清除。

幾行代碼最初來自@cja文章。

歡呼/快樂值編碼...

+0

謝謝@ralphgabb我試過使用相同的,但我仍然能夠通過單擊清除所有和滑動手勢清除通知。我正在開發最低API級別19和目標API級別25 – bhavikshah28

+0

多數民衆贊成在怪異,生病嘗試檢查出來,這個功能真的在我的最終(用於多個項目),或者你可以在這裏發表你的代碼幾行。 – ralphgabb

+0

@ralphgaab https://prnt.sc/hpzi9e – bhavikshah28

0

就這兩個標誌添加到通知,FLAG_AUTO_CANCEL防止通知當用戶觸摸它,FLAG_ONGOING_EVENT使它成爲Ongoing Notification自動解除。

notification.flags=Notification.FLAG_AUTO_CANCEL|Notification.FLAG_ONGOING_EVENT; 
相關問題