我正在测试AlarmManager
以便在我的应用中使用,当我希望它在1分钟后启动时,它会立即触发我的广播接收器。代码如下:
public class SetMealTimersActivity extends Activity {
PendingIntent pi;
BroadcastReceiver br;
AlarmManager am;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_meal_timers);
br = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
Toast.makeText(c, "Ready to Go!", Toast.LENGTH_LONG).show();
}
};
registerReceiver(br, new IntentFilter("com.ian.mealtimer"));
pi = PendingIntent.getBroadcast(this, 0, new Intent(
"com.ian.mealtimer"), 0);
am = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
am.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() +
60 * 1000, pi );
}
答案 0 :(得分:3)
尝试:
am.set(AlarmManager.RTC_WAKEUP,
Calendar.getInstance().getTimeInMillis()+60*1000, pendingIntent);
它对我有用。
答案 1 :(得分:1)
如果使用确切的警报,请确保现在是将来。否则它将立即触发。
答案 2 :(得分:0)
尝试将SystemClock.elapsedRealtime()
更改为System.currentTimeMillis()
,将AlarmManager.ELAPSED_REALTIME_WAKEUP
更改为AlarmManager.RTC_WAKEUP
。
答案 3 :(得分:0)
如果您使用Android API>尝试使用AlarmManager.setExact(int, long, PendingIntent)
18或用API编译< 19,因为这种方法的时间管理随API 19而改变。也许这有所帮助。有关详细信息,请阅读documentation。
答案 4 :(得分:0)
为id
制作pendingIntent
pendingIntent = PendingIntent.getActivity(this, 999123266,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
所有示例
public void setAlarm_sat(int dayOfWeek1) {
cal1.set(Calendar.DAY_OF_WEEK, dayOfWeek);
Intent intent = new Intent(this, RemmemberActivity.class);
pendingIntent = PendingIntent.getActivity(this, 999123266,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
Long alarmTime = cal1.getTimeInMillis();
AlarmManager am = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP,
alarmTime,7*24 * 60 * 60 * 1000,
pendingIntent);
// am.set(AlarmManager.RTC, cal1.getTimeInMillis(), pendingIntent);
}