Search code examples
javaandroidalarmmanagerandroid-pendingintent

Setting up AlarmManager to run when Android app isn't running?


I've looked at several guides and I've basically done this:

Main.java

public class Main extends Activity 
{
    PendingIntent pendingIntent;

    @Override
    public void onCreate(Bundle savedInstanceState) 
     {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("America/New_York"));

      cal.set(Calendar.HOUR_OF_DAY, 22);
      cal.set(Calendar.MINUTE, 0);
      cal.set(Calendar.SECOND, 0);

      Intent myIntent = new Intent(Main.this, Receiver.class);
      pendingIntent = PendingIntent.getBroadcast(Main.this, 0, myIntent,0);

      AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
      alarmManager.set(AlarmManager.RTC, cal.getTimeInMillis(), pendingIntent);
    }
}

Receiver.java

public class Receiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
       Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
    }   
}

AndroidManifest.xml also contains <receiver android:name=".Receiver"/>.

So, from what I've read, the above code should show a toast whenever it is 10 pm in New York, whether or not the app is actually running. At present, it does nothing, even if the app is running. It looks like the Receiver class isn't even being called. What am I missing?


Solution

  • I found the problem (as was hinted to me here): my Main.java and Receiver.java files were not placed in the same package. I don't understand the logic behind this. I like separating my java files into different packages for organization purposes, but apparently Android doesn't like this.

    If anyone can tell me how to do the above with the java files in 2 different packages/folders under src, I'll make that the correct answer.