开发者社区> 问答> 正文

Android,在两个线程里发送notification,第二个notification弹出两次

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

展开
收起
爵霸 2016-07-29 16:37:49 2939 0
2 条回答
写回答
取消 提交回答
  • 在sendNotificationMessage("发送成功");行设断点,看看究竟发了几次。

    2019-07-17 20:01:55
    赞同 展开评论 打赏
  • 代码不全...

    2019-07-17 20:01:55
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
58同城Android客户端Walle框架演进与实践之路 立即下载
Android组件化实现 立即下载
蚂蚁聚宝Android秒级编译——Freeline 立即下载