BlueBerryVanilla 2015-06-04 08:14 采纳率: 0%
浏览 3272

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);       
}

}

  • 写回答

4条回答

  • danielinbiti 2015-06-04 08:46
    关注

    还是得看click哪触发的,看日志是不是都打印了两次,可能是双击了两次。
    可以调试一下,看click是不是进入了2次还是click进入了一次,thread运行了2次。

    评论

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试