1

I am trying to execute an action once at a later time using AlarmManager. I followed the code and the question here and came up with this.

public class EmailAccountUpdater extends BroadcastReceiver
{
   // Constructors

   public void onReceive(Context context, Intent intent)
   {
       if (intent.getAction().equals(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION))
       {
           Log.v("Test", " Step 1 -  Creating the alarm " );
           // Place holder 
           AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
           Intent newIntent = new Intent("com.test.EMAIL_ACCOUNTS_CHANGED");
           PendingIntent pendingIntent = PendingIntent.getBroadcast( context, 0, newIntent, PendingIntent.FLAG_CANCEL_CURRENT);
           alarmManager.set( AlarmManager.RTC_WAKEUP, 35000, pendingIntent);
       }
   }
}

AlarmReceiver.java

public class AlarmReceiver extends BroadcastReceiver
{
    // constructors

    @Override
    public void onReceive(Context context, Intent intent)
    {
        Log.v("Test","Step 2 - Alarm received");
        if (intent.getAction().equals("com.test.EMAIL_ACCOUNTS_CHANGED"))
        {
             onAccountsUpdated();
        }
    }

    public void onAccountsUpdated()
    {
        // do something
    }
}

In the manifestManifest.xml

<receiver android:name="full.path.AlarmReceiver">
       <intent-filter>
           <action android:name="com.test.EMAIL_ACCOUNTS_CHANGED"/>
       </intent-filter>
</receiver>

Basically what I wanted to do was to put the following in Placeholder (just below the first log statement).

Thread.sleep(35000);
onAccountsUpdated();

But according to this, it is not suggestible to use postDelayed and Thread.sleep in BroadcastReceiver. So I came up with this. What happens is I always get the Step 1 but never reach the step 2. What I am I doing wrong? Any help would be welcome.

Community
  • 1
  • 1
user1429322
  • 1,266
  • 2
  • 24
  • 38

1 Answers1

0

The solution is (as per the thread you linked):

you want something to happen some time after the broadcast you can start a service, and that service wait the amount of time, or if the amount of time you want to wait is longer than a few seconds, you should just put the launch of this service in the AlarmManager and let the AlarmManager launch the service for you.

Your plan doesn't work because the context is destroyed after EmailAccountUpdater.onReceive returns.

Buddy
  • 10,874
  • 5
  • 41
  • 58
  • Thanks. I already have a service running. Can I use AlarmManager to run a function in existing service? – user1429322 Nov 02 '15 at 00:01
  • If your service is already an IntentService, then you could just have it listen for the broadcast and schedule its own alarm. Otherwise you can communicate with your service like this: http://stackoverflow.com/a/2463746 – Buddy Nov 02 '15 at 17:21