我正在构建一个简单的应用程序,它通过按下按钮并按下消息在通知栏中创建一条消息,我正在运行一个新的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);
}