簡體   English   中英

即使時間錯誤也會執行AlarmManager

[英]AlarmManager executed even if the time is wrong

我正在使用以下代碼在上午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執行?

您的代碼是正確的。 警報將從上午10:30開始,並每8秒重復一次。 但是一旦檢查了運行應用程序的設備或仿真器中的時間。 如果時間已經過去,則警報立即開始執行。

如果時間未完成,則一旦卸載應用程序並再次運行,它可能會起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM