AlarmManager starting application instead of just

2019-04-16 17:05发布

问题:

I currently have an app which, when a button is pressed, and after a certain period of time, a statusbar notification is set.

Everything works fine apart from the fact if the user does not have the application open, when the notification appears, the app also reopens. This is not what i would like to happen. I would like the notification to appear on it's own (wherever the user is).

On my button press i use:

    // get a Calendar object with current time
Calendar cal = Calendar.getInstance();
// add minutes to the calendar object
cal.add(Calendar.SECOND, time);
Intent alarmintent = new Intent(getApplicationContext(), AlarmReceiver.class);
alarmintent.putExtras(bundle);
// In reality, you would want to have a static variable for the request code instead of 192837
PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), HELLO_ID, alarmintent, 0);
// Get the AlarmManager service
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);

This calls my AlarmReceiver.class, which uses this code to call my notification class:

        Intent myIntent = new Intent(context, Note.class);
    myIntent.putExtras(bundle2);


     myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);

    context.startActivity(myIntent);

notification.class:

public class Note extends Activity {




    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String ns = Context.NOTIFICATION_SERVICE;
        final NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

        int icon = R.drawable.launcher;
        CharSequence tickerText = "Remind Me!";
        long when = System.currentTimeMillis();

        final Notification notification = new Notification(icon, tickerText, when);

    notification.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_NO_CLEAR;

    final Context context = getApplicationContext();
    CharSequence contentTitle = "Remind Me!";
    CharSequence contentText = param1;

    Intent notificationIntent = new Intent(context, Completed.class);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);


            mNotificationManager.notify(HELLO_ID, notification);

            HELLO_ID++;


         }
}

回答1:

This is the expected result, as the Intent you create in your AlarmReceiver class explicitly launches your Note Activity.

Why not simply create the Notification in your AlarmReceiver? (rather than launching your activity)