Alarm Manager Example

前端 未结 10 1859
情话喂你
情话喂你 2020-11-21 05:12

I want to implement a schedule function in my project. So I Googled for an Alarm manager program but I can`t find any examples.

Can anyone help me with a basic alar

10条回答
  •  深忆病人
    2020-11-21 05:40

    Here's a fairly self-contained example. It turns a button red after 5sec.

        public void SetAlarm()
        {
            final Button button = buttons[2]; // replace with a button from your own UI
            BroadcastReceiver receiver = new BroadcastReceiver() {
                @Override public void onReceive( Context context, Intent _ )
                {
                    button.setBackgroundColor( Color.RED );
                    context.unregisterReceiver( this ); // this == BroadcastReceiver, not Activity
                }
            };
    
            this.registerReceiver( receiver, new IntentFilter("com.blah.blah.somemessage") );
    
            PendingIntent pintent = PendingIntent.getBroadcast( this, 0, new Intent("com.blah.blah.somemessage"), 0 );
            AlarmManager manager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
    
            // set alarm to fire 5 sec (1000*5) from now (SystemClock.elapsedRealtime())
            manager.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000*5, pintent );
        }
    

    Remember though that the AlarmManager fires even when your application is not running. If you call this function and hit the Home button, wait 5 sec, then go back into your app, the button will have turned red.

    I don't know what kind of behavior you would get if your app isn't in memory at all, so be careful with what kind of state you try to preserve.

提交回复
热议问题