需要知道我的应用程序何时发送通知

Need to know when my app send a notification

我有一个应用程序,它有一个 MainActivity(Mr.Obvious)、一个服务和一个 BroadcastReceiver。在我的 MainActivity 中,我有一个像这样的 AlarmManager:

Intent myIntent = new Intent(MainActivity.this, BroadReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);

    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            calendar.getTimeInMillis(),
            AlarmManager.INTERVAL_HALF_DAY, pendingIntent);

在我的 BroadcastReceiver 中我有这个:

public void onReceive(Context context, Intent intent) {
    Intent service1 = new Intent(context, NotifyService.class);
    context.startService(service1);
}

在我的服务中,我有这个:

 public int onStartCommand(Intent intent, int flags, int startId) {


    NotificationManager notificationManager = (NotificationManager) this.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
    Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
    Notification notification = new NotificationCompat.Builder(this)
            .setTicker(getText(R.string.notification_ticker))
            .setSmallIcon(R.drawable.green)
            .setContentTitle(frase())
            .setContentText(getText(R.string.notification_text))
            .setAutoCancel(true)
            .build();
    intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
    notificationManager.notify(0, notification);}

我希望我的应用在用户收到通知时在 MainActivity 中启用一个按钮,这可能吗?

  • If your in background start activity newly
Intent in = new Intent(this, MainActivity.class);
in.putExtra("state", "background");
startActivity(in);
  • Get string extra then compare it and control the button

  • If your in foreground make button object as public then control it

  • Use a global variable to identify MainActivity in foreground or not(Using activity life cycle)

  onDistroy()


  onStart()