How do you start an Activity with AlarmManager in Android?

前端 未结 8 932
鱼传尺愫
鱼传尺愫 2020-12-01 17:01

I\'ve poured through a dozen tutorials and forum answers about this problem, but still haven\'t been able to get some working code together. I\'ll try to keep the question s

8条回答
  •  时光说笑
    2020-12-01 17:24

    In case someone else stumbles upon this - here's some working code (Tested on 2.3.3 emulator):

    public final void setAlarm(int seconds) {
        // create the pending intent
        Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
        // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0,
                intent, 0);
        // get the alarm manager, and scedule an alarm that calls the receiver
        ((AlarmManager) getSystemService(ALARM_SERVICE)).set(
                AlarmManager.RTC, System.currentTimeMillis() + seconds
                        * 1000, pendingIntent);
        Toast.makeText(MainActivity.this, "Timer set to " + seconds + " seconds.",
                Toast.LENGTH_SHORT).show();
    }
    
    public static class AlarmReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            Log.d("-", "Receiver3");
        }
    }
    

    AndroidManifest.xml:

        
        
    

    Issues with BenLambell's code :

    • EITHER:
      • Move the receiver to it's own .java file or
      • make the inner class static - so it can be accessed from outside
    • Receiver is not declared correctly in the manifest:
      • if it's an inner class in MainActivity use:
      • if it's in a separate file:

    If your intention is to display a dialog in the receiver's onReceive (like me): that's not allowed - only activities can start dialogs. This can be achieved with a dialog activity.

    You can directly call an activity with the AlarmManager:

    Intent intent = new Intent(MainActivity.this, TriggeredActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    ((AlarmManager) getSystemService(ALARM_SERVICE)).set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + seconds * 1000, pendingIntent);
    

提交回复
热议问题