简体   繁体   English

即使时间错误也会执行AlarmManager

[英]AlarmManager executed even if the time is wrong

I am using the following code to execute the Alarm at 10:30 AM and then keep executing every 8seconds, but the problem is, this code execute the Alarm manager even when the time is not 10:30. 我正在使用以下代码在上午10:30执行警报,然后保持每8秒执行一次,但是问题是,即使时间不是10:30,该代码也会执行警报管理器。

I have tried everything but the code keep executing the Alarm regardless of what time is set, 我已经尝试了所有方法,但是无论设置了什么时间,代码都会继续执行警报,

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);
    }

}

and this is my AlarmReceiver class, 这是我的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();

    }

I have also added this in my AndroidManifest.xml , 我也在我的AndroidManifest.xml添加了它,

<receiver android:name="com.example.test2.AlarmReceiver" android:enabled="true" >
    </receiver>

How to make it to only execute at 10:30AM ? 如何使其仅在上午10:30执行?

Your code is correct. 您的代码是正确的。 The alarm will start at 10:30 am and repeats at every 8 seconds. 警报将从上午10:30开始,并每8秒重复一次。 But once check the time in the device or emulator in which your app is running. 但是一旦检查了运行应用程序的设备或仿真器中的时间。 If the time is already past then the alarm starts executing immediately. 如果时间已经过去,则警报立即开始执行。

If the time is not completed then once uninstall the application and run again it may work. 如果时间未完成,则一旦卸载应用程序并再次运行,它可能会起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM