Are there unintended consequences by registering o

2019-09-01 01:21发布

I have this method to register/cancel alarms that I call from two different Activities - hence the context passed in is different each time.

I designed it so that the alertId in the Uri is the unique identifier for an alarm - all other parameters class, category are the same.

However, sometimes ActivityA might register an alarm with alertId = 1 by using its contextA in the pending intent. ActivityB might update the alarm with alertId = 1 by registering it again by using its contextB. Similarly with canceling the alarm.

Will the same alarm get updated?

Hence, I was wondering if there might be a side effect to having different contexts while registering an alarm with the same alertId. Does anyone have insight into this?

static void registerAlarm(Context context, Alert alert, Date alarmTime) {
    // Get the AlarmManager Service
    AlarmManager mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent mNotificationReceiverIntent;
    PendingIntent mNotificationReceiverPendingIntent;
    // Create PendingIntent to start the AlarmNotificationReceiver
    mNotificationReceiverIntent = new Intent(context, NotifyActivity.class);
    mNotificationReceiverIntent.setAction(Intent.ACTION_SENDTO);
    // workaround from mazur - android bug database
    Bundle hackbundle = new Bundle();
    hackbundle.putParcelable(Alert.ALERT, alert);
    mNotificationReceiverIntent.putExtra(Alert.ALERT, hackbundle);
    mNotificationReceiverPendingIntent = PendingIntent.getBroadcast(context, 0,
            mNotificationReceiverIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    mNotificationReceiverIntent.setData(AlertsDbHelper.getUriForAlert(alert.alertId));
    mAlarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime.getTime() + JITTER,
            mNotificationReceiverPendingIntent);
    Log.i(TAG, "registerAlarm() Alarm Set for alert id:" + alert.alertId + " alarm Time "
            + alarmTime);

    Toast.makeText(context,
            "Alarm Set for alert id:" + alert.alertId + " alarm Time " + alarmTime,
            Toast.LENGTH_LONG).show();
}

1条回答
时光不老,我们不散
2楼-- · 2019-09-01 01:58

According to this Android: Does context affect filterEquals(), used to cancel alarm? it doesn't matter if you use different contexts, this doesn't affect the recognition of the PendingIntents as matching. I have confirmed this in my own app, I set an alarm from one activity using the activity as the context, and cancelled it from a different activity using that activity's context, and it was successfully cancelled, meaning the different context had no affect on identifying the correct alarm.

查看更多
登录 后发表回答