1

我正在构建一个简单的应用程序,它通过按下按钮并按下消息在通知栏中创建一条消息,我正在运行一个新的Activity. 当我Activity通过按回关闭然后再次运行它时,按下按钮什么也不做。我还创建了一个单例NotificationManager,以在第二个活动的 onCreate 方法中自动从通知栏中删除消息图标。看来我的单例类仍然存在,不能Object创建新的。我需要强制关闭活动,我相信只有这样我的单身课程才会被释放。我尝试android:noHistory="true"在两个 activitied 上进行设置,manifest.xml并在以下位置创建了这个MainActivity

public void onContextMenuClosed(Menu menu) {
        super.onContextMenuClosed(menu);
        this.finish();
    }

并在活动中尝试了这个MessageViewer

public void onBackPressed() {
        super.onBackPressed();
        this.finish();
    }

这是我的代码:

public class NotifyManager {
    private static NotificationManager notificationManager=null;

    public static NotificationManager getInstance() {
        if(notificationManager==null) {
            throw new NullPointerException("NotificationManager has not been set yet.");
        }
        else {
            return notificationManager;
        }
    }

    public static void setNotificationManager(NotificationManager nm) throws NotificationManagerException {
        if(notificationManager==null) {
            notificationManager = nm;
        }
        else {
            throw new NotificationManagerException("NotificationManager has already been set.");
        }
    }
}



public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button b = (Button) findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                    NotifyManager.setNotificationManager(nm);
                    Notification notify = new Notification(
                            R.drawable.icon,
                            "New message", System.currentTimeMillis());
                    Context context = MainActivity.this;
                    CharSequence title = "You have a new message";
                    CharSequence details = "";
                    Intent intent = new Intent(context, MessageViewer.class);
                    PendingIntent pending = PendingIntent.getActivity(context, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
                    notify.setLatestEventInfo(context, title, details, pending);
                    nm.notify(0, notify);
                }
                catch(Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

顺便说一句,在我的第二个活动中,我所做的就是关闭当前通知:

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_viewer);

        NotifyManager.getInstance().cancel(0);
    }
4

1 回答 1

0

好吧,您必须使用不同的 id 创建不同的通知。在nm.notify(0, notify);你不能给每个通知相同的 id。因此,只需尝试为您创建的每个通知提供不同的通知 ID。希望它会奏效

于 2012-10-24T20:30:37.987 回答