ボタンを押してメッセージを押すことで通知バーにメッセージを作成する簡単なアプリを作成していますActivity
。押して閉じてActivity
から再度実行すると、ボタンを押しても何も起こりません。NotificationManager
また、2 番目のアクティビティの onCreate メソッドで、通知バーからメッセージ アイコンを自動的に削除するシングルトンも作成しました。シングルトン クラスが残っているようで、新しくObject
作成することはできません。アクティビティを強制的に終了する必要があり、そうして初めてシングルトン クラスが解放されると思います。android:noHistory="true"
でアクティブ化された両方で設定を試み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();
}
}
});
}
ちなみに、2 つ目のアクティビティでは、現在の通知を閉じるだけです。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_viewer);
NotifyManager.getInstance().cancel(0);
}