android 清除某个通知,android清除通知栏消息
這近項目快到結尾了,經理要我處理一個問題,就是我們程序關閉后,程序發出通知 在狀態欄上始終沒有消除,需要手動的清楚,
體驗效果極其不好,現在是想在程序推出后,把通知給消除了,琢磨了下,不知怎么清楚,看了下api 有清除的方法,后面安心多了
,但有出現毛病了,我什么調用通知管理器把通知消除啊,他是開一個一個服務中的,我們不能new 這個類,是系統的,當時想了下
決定發送廣播清楚, 當程序退出的時候,調用該廣播把消息清楚,等到快寫完的時候,才發現,既然是系統調用的,系統肯定有結束的回調啊
立馬想到了 ondesory()方法,因為我程序不管怎么退出,都會調用該方法,而且省了我很大的一筆功夫,代碼也就一行!
寫這個只想告訴自己,在應用系統的東西時候,我們應該遵循系統的規則進行游戲,該創建的時候就要創建,該釋放的地方就要釋放!
看來對系統的生命周期認識還不是很到位啊!
說了這么多廢話 ,也貼上測試代碼 ,隨便寫的
package com.liao.notification;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
private int type ;
private String message ;
private NotificationManager notiManager;
Handler handler = new Handler(){
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
if(msg.what ==1){
message = "type ====1";
}else if (msg.what == 2){
message = "type ====2";
}
notiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon,
"您有新消息" + type, System.currentTimeMillis());
Intent intent = new Intent();
intent.setClass(getApplicationContext(), ReciveActivity.class);
intent.putExtra("hello", "hello Dialog");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(
getApplicationContext(), 100, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(getApplicationContext(), type + "",
message, pendingIntent);
notiManager.notify(0, notification);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
Button button = new Button(this);
button.setText("測試notification1");
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
type = 1;
handler.sendEmptyMessage(1);
}
});
Button button2 = new Button(this);
button2.setText("測試notification2");
button2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// handler.sendEmptyMessage(2);
// type= 2;
notiManager.cancel(0);// 調用他就行 這個0 和notiManager創建時候傳入的0 是唯一的 ,所以可以根據他刪除
}
});
layout.addView(button);
layout.addView(button2);
setContentView(layout);
}
}
總結
以上是生活随笔為你收集整理的android 清除某个通知,android清除通知栏消息的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2022-2027年中国城市公共汽车客运
- 下一篇: 阿凡题UWP的源码公开