2015-12-05 62 views
0

我有一個簡單的應用程序,使用顯示進度對話框中的進度以及正在進行的通知的服務從互聯網下載文件。 我的問題是如何通過強制關閉應用程序停止下載(例如通過長按主頁按鈕並清除所有最近的應用程序列表)來刪除通知。Android - 取消通知

我試着用這樣的:

@Override 
protected void onDestroy() { 


    Toast.makeText(getApplicationContext(), "ADDIO", Toast.LENGTH_SHORT).show(); 

    NotificationManager nm =(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); 

    nm.cancelAll(); 

    super.onDestroy(); 

} 

,但它不工作。

請幫忙

+0

您是否嘗試過在onStop或onPause中停止通知? –

回答

0

你可以從你的活動開始一項服務。

第1步創建一個服務,殺死 簡單的一個。它只是殺死一個創建通知,並有他的特殊粘合劑。

public class KillNotificationsService extends Service { 

    public class KillBinder extends Binder { 
     public final Service service; 

     public KillBinder(Service service) { 
      this.service = service; 
     } 

    } 

    public static int NOTIFICATION_ID = 666; 
    private NotificationManager mNM; 
    private final IBinder mBinder = new KillBinder(this); 

    @Override 
    public IBinder onBind(Intent intent) { 
      return mBinder; 
    } 
    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
      return Service.START_STICKY; 
    } 
    @Override 
    public void onCreate() { 
      mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
      mNM.cancel(NOTIFICATION_ID); 
    } 
} 

第二步:將它添加到您的清單: 某處它添加插圖中的<應用>標籤。

<service android:name="KillNotificationsService"></service> 

第三步:燒的通知之前,請務必創建服務,並使用靜態notificationid。

​​

,直到服務重新啓動(1-5秒),這可能需要一點時間,但最終會啓動並殺死的通知。

+0

void執行,但通知不消失! – asdf

+0

檢查編輯。 –

+0

@asdf是否有效? –