我使用以下代码在上午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执行?
答案 0 :(得分:1)
您的代码是正确的。闹钟将在上午10:30开始,每8秒重复一次。但是,一旦检查运行应用程序的设备或模拟器中的时间。如果时间已经过去,则警报立即开始执行。
如果时间没有完成,那么一旦卸载应用程序并再次运行,它可能会有效。