下面是我写的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);
}
}