报警管理器对我不起作用

时间:2011-06-17 10:07:58

标签: android alarmmanager

我正试图让警报起作用,但它没有做任何事情,我在做什么? 我的代码是

        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);

我的广播接收器看起来像这样

    public class OnetimeAlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
    }
}

这是一个内部阶级。

我缺少什么?

2 个答案:

答案 0 :(得分:7)

您必须注册广播接收器才能工作,可以使用Context.registerReceiver()方法在AndroidManifest.xml中或动态地完成。

您可以阅读有关注册接收者statically的开发者指南,或查看参考资料以了解如何执行此操作dynamically

答案 1 :(得分:2)

这是有效的代码。

添加到Manifest.xml:

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

代码:

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
     }
}