Android AlarmManager setRepeating Issue

2019-09-09 05:40发布

问题:

I'm developing a feeder application, and i have the option that let the user choose for each source (feed source) specify the time to get data from the internet and update the database.

I'm using AlarmManager for this.

What i do tipically is:

Get all providers. Group in a map> that the key is the sleep time and value is a list of providers

For what?...

Well i iterate later over this dictionary for each key and schedule an alarm to send a broadcast with data in a intent.

In my broadcast receiver i want to get this data..

The problem that i am not undestanding is i pass a Key (sleep time) in a for each loop to schedule the event... actually i got 2 keys, [5, 10]

and on my onreceive i get only key 5.. 2 times.... it seems like the same intent is delivered to the receiver..

Here is the code:

private void setAlarmForEnabledProviders(HashMap<Integer, ArrayList<Provider>> map)
        {
            Context ctx = FeederPeriodicalUpdater.this;
            AlarmManager alarmMngr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

            for(Integer key : map.keySet())
            {
                int keyValue = key.intValue();
                Intent intent = new Intent(FeederPeriodicalUpdater.this, OnAlarmReceiver.class);


                intent.putExtra(AlarmManager_IntentKey, keyValue);
                PendingIntent pIntent = PendingIntent.getBroadcast(ctx, 0, intent, 0);

                long firstTime = SystemClock.elapsedRealtime();
                alarmMngr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, pIntent);
            }               
        }

My Receiver:

public void onReceive(Context ctx, Intent intent) 
{
    Log.d(TAG, "onReceive");

    application = (DroidApplication)ctx.getApplicationContext();
    feedMessageService = application.getFeedMessageService();

    int sleep = intent.getIntExtra(FeederPeriodicalUpdater.AlarmManager_IntentKey, -1);

    if(sleep == -1)
        throw new IllegalStateException();

回答1:

try to change the request code as the second parameter of the getBroadcast() of the PendingIntent

PendingIntent pIntent = PendingIntent.getBroadcast(ctx, "here change the value everytime", intent, 0);

like pass the unique number because you send the same intent and request i think it will be overwrite