我正在尝试构建一个应用程序,该应用程序每小时检查一次服务器上的通知文件。我使用了警报管理器类来实现这一点。但是我无法在重新启动部分实现自动启动。我希望警报在重新启动后应定期运行。有人可以告诉我如何去做吗。
这是我的MyAlarmReceiver类。
package com.example.quickstart;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
public class MyAlarmReceiver extends BroadcastReceiver {
public static final int REQUEST_CODE = 12345;
public static final String ACTION = "com.example.quickstart.alarm";
// Triggered by the Alarm periodically (starts the service to run task)
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, NotificationService.class);
// i.putExtra("username", username);
context.startService(i);
}
}
这是我的NotificationBootReceiver类。
package com.example.quickstart;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
public class NotificationBootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Construct an intent that will execute the AlarmReceiver
Intent i = new Intent(context, MyAlarmReceiver.class);
// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(context, MyAlarmReceiver.REQUEST_CODE,
i, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup periodic alarm every every half hour from this point onwards
long firstMillis = System.currentTimeMillis(); // alarm is set right away
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
// Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),
2*60*60,pIntent);
// alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
// AlarmManager.INTERVAL_FIFTEEN_MINUTES, pIntent);
}
}
AndroidManifest文件如下所示(它不是完整的清单文件,而是相关部分)
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".NotificationBootReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
通知运行正常,但是我要的是重新启动时自动启动通知功能。当我重新启动时,通知功能不起作用,即,警报不会响起。并且android文档还说 (这仅在应用程序已经被用户至少启动过一次的情况下有效) ,有没有办法在重启时自动设置警报而不启动应用程序。任何帮助表示赞赏。预先感谢
文档链接android devs link (转到:设备重新启动时发出警报)
答案 0 :(得分:0)
否,即使没有启动应用程序也无法设置警报。一旦启动应用程序,便可以触发警报。