简体   繁体   中英

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?

do you register you Receiver with intent-filter? like below

        <intent-filter android:priority="2147483647" >
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>

When adjusting the time components for the Calendar object, only those you specifically set are modified. If you want the alarm to fire at 10:00pm, you need to set the Calendar.MINUTE value as well. For example, if you run your app 6:47pm, then your alarm, as you have it, is being set for 10:47pm.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM