我使用以下代码在上午10:30执行警报,然后继续每8秒执行一次,但问题是,即使时间不是10:30,这段代码也会执行警报管理器。
我已经试过了所有的方法,但是不管什么时候设置,代码都会继续执行警报,
public class MainActivity extends Activity {
private PendingIntent pendingIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Retrieve a PendingIntent that will perform a broadcast */
Intent alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0);
startAt10();
}
public void startAt10() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
/* Set the alarm to start at 10:30 AM */
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 10);
calendar.set(Calendar.MINUTE, 30);
/* Repeating on every 8 seconds interval */
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 8, pendingIntent);
}
}这是我的AlarmReceiver课,
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// For our recurring task, we'll just display a message
Toast.makeText(context, "Welcome Back ! ", Toast.LENGTH_SHORT).show();
}我也在我的AndroidManifest.xml中添加了这个,
<receiver android:name="com.example.test2.AlarmReceiver" android:enabled="true" >
</receiver>如何使它只在上午10:30执行?
发布于 2014-12-14 12:56:30
你的代码是正确的。警报将于上午10:30开始,每8秒重复一次。但是一旦检查你的应用程序运行的设备或模拟器的时间。如果时间已过,则警报立即开始执行。
如果时间没有完成,那么一旦卸载应用程序并再次运行,它可能会工作。
https://stackoverflow.com/questions/27468933
复制相似问题