下面是我写的demo,可以完全显示问题。
我的app是发送一个地址到PC,先通知“正在发送。。”,在另一个线程中执行发送,完成后先cancel掉之前的“正在发送”,再notify一个“发送成功”通知。可结果,“发送成功”通知在状态栏弹出了两次。这个问题想了3天
package com.teana.teanatest;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
private NotificationManager mNotificationManager;
private Handler mhHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mhHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
}
};
mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void click(View view) {
sendNotificationMessage("正在发送....");
System.out.println("正在发送....");
new Thread() {
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("cancel 正在发送....");
mNotificationManager.cancel(1);
sendNotificationMessage("发送成功");
System.out.println("发送成功");
try {
Thread.sleep(2500);
mNotificationManager.cancel(1);
System.out.println("cancel 发送成功");
} catch (InterruptedException e) {
e.printStackTrace();
}
};
}.start();
}
private void sendNotificationMessage(String text) {
Notification notification = new Notification();
notification.tickerText = text;
notification.icon = R.drawable.ic_launcher;
notification.when = System.currentTimeMillis();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this, text, text, null);
mNotificationManager.notify(1, notification);
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。