AlarmManager不会触发WakefulBroadcastReceiver

时间:2015-08-05 10:38:11

标签: android

我尝试使用AlarmManager和WakefulBroadcastReceiver启动意向服务。我可以使用sendBroadcast()启动服务,它可以正常工作,但我无法通过AlarmManager启动它。

启动它的代码是这样的:

@Override
protected void onPause()
{
    super.onPause();

    AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
    Intent i = new Intent(this, Notifier.class);
    PendingIntent pi = PendingIntent.getService(this, 0, i, 0);

    am.set(RTC_WAKEUP, System.currentTimeMillis(), pi);
}

Notifier类是这样的:

public class Notifier extends WakefulBroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        Log.i("Notifier", "onReceive()");
        ComponentName comp = new ComponentName(context.getPackageName(), NotifierService.class.getName());
        startWakefulService(context, (intent.setComponent(comp)));
    }
}

NotifierService就像这样:

public class NotifierService extends IntentService
{
    private static final String TAG = "NotifService";

    public NotifierService()
    {
        super("NotifierService");
   }

    @Override
    protected void onHandleIntent(Intent intent)
    {
        Log.i(TAG, "NotifierService: handling an intent");
    }

清单上有这些:

<service android:name=".NotifierService" />
<receiver android:name=".Notifier" />

为什么AlarmManager不会触发接收器?

3 个答案:

答案 0 :(得分:2)

变化:

Intent i = new Intent(this, Notifier.class);

要:

Intent i = new Intent(this, NotifierService .class);

答案 1 :(得分:0)

您是否已按照documentation中的说明向您的清单添加WAKE_LOCK权限?

<manifest xlmns:android...>
 ...
 <uses-permission android:name="android.permission.WAKE_LOCK" />
 <application ...
</manifest>

答案 2 :(得分:0)

    <html>
      <head/head>
      <body>
          <script type="text/javascript">
              for (i = 1; i <= 100; i++)
                  if (i % 3 == 0 && i % 5 != 0) {
                      document.write("Fizz");
                      document.write("<br />");
                  } else if (i % 5 == 0 && i % 3 != 0) {
                      document.write("Buzz");
                      document.write("<br />");
                  } else if (i % 3 == 0 && i % 5 == 0) {
                      document.write("FizzBuzz");
                      document.write("<br />");
                  } else {
                      document.write(+i);
                      document.write("<br />");
                  }
          </script>
      </body>
      </html>