开发者

Alarm Manager doesn't work for me

开发者 https://www.devze.com 2023-03-14 02:01 出处:网络
I\'m trying to get the alarm to work, but it doesn\'t do anything, what do I\'m mising? My code is Calendar cal = Calendar.getInstance();

I'm trying to get the alarm to work, but it doesn't do anything, what do I'm mising? My code is

        Calendar cal = Calendar.getInstance();
    Intent intent = new Intent(this, OnetimeAlarmReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);

    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() + 3000, sender);

And my broadcast receiver looks like this

    public class OnetimeAlarmReceiver extends BroadcastReceiver {

    @Override开发者_如何学JAVA
    public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
    }
}

Which is an inner class.

What do I'm missing?


You broadcast receiver must be registered in order to work, it can be done either in AndroidManifest.xml or dynamically, using the Context.registerReceiver() method.

You can read the developer's guide about registering receviers statically or check the reference to find out how to do this dynamically.


This is working code.

Add to Manifest.xml:

...
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
...
<receiver  android:process=":remote" android:name="Alarm"></receiver>
...

Code:

public class Alarm extends BroadcastReceiver 
{    
     @Override
     public void onReceive(Context context, Intent intent) 
     {   
         PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
         PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
         wl.acquire();

         // Put here YOUR code.
         Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example

         wl.release();
     }

     public void SetAlarm(Context context)
     {
         AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
         Intent i = new Intent(context, Alarm.class);
         PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
         am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (1000 * 60 * 10), pi); // Millisec * Second * Minute
     }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消