我有一个 Android 应用程序,允许用户添加将记录其位置的警报。例如,每天早上 8 点我都想记录我在哪里。当收到警报时,它会启动一个服务来获取用户的位置并将其保存到数据库中。该功能在应用程序运行时(在后台或前台)运行良好。
问题是,如果我进入任务管理器并强制关闭应用程序,警报似乎不会响起。这很重要,因为用户可以重新启动手机并终止应用程序。
这是设置警报的方法:
private void setNewAlarm(int hour, int minute, int id) {
Intent alarmIntent = new Intent(AutoLoggerActivity.this, AlarmReciever.class);
alarmIntent.putExtra(Constants.ALARMID_FIELD_NAME, id);
PendingIntent sender = PendingIntent.getBroadcast(AutoLoggerActivity.this, id, alarmIntent, 0);
Calendar alarmCal = Calendar.getInstance();
alarmCal.set(Calendar.HOUR_OF_DAY, hour); // set user selection
alarmCal.set(Calendar.MINUTE, minute); // set user selection
alarmCal.set(Calendar.SECOND, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmCal.getTimeInMillis(), 120000, sender);
}
这是广播接收器:
public class AlarmReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
int alarmId = bundle.getInt(Constants.ALARMID_FIELD_NAME);
Toast.makeText(context, "Alarm Running: ID = " + alarmId, Toast.LENGTH_LONG).show();
Log.d(TAG, "AlarmReceiver: onRecieve. ID = " + alarmId);
Intent serviceIntent = new Intent(context, LocationRecordingService.class);
serviceIntent.putExtra(Constants.ALARMID_FIELD_NAME, alarmId);
context.startService(serviceIntent);
}
}
知道为什么会这样吗?