1. 程式人生 > >AlarmManager定時器傳送一個延時廣播

AlarmManager定時器傳送一個延時廣播

AlarmUtil.java

public static final String ACTION_TIME_OVER = "com.spt.carengine.time.over";

    public static void startTimer(Context context, String action, long time) {
        Intent intent = new Intent(action);
        PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent,
                0);
        AlarmManager alarm = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        alarm.setExact(AlarmManager.RTC_WAKEUP, time, sender);
    }
    
    public static void cancelTimer(Context context, String action) {
        Intent intent = new Intent(action);
        PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent,
                0);

        AlarmManager alarm = (AlarmManager) context
                .getSystemService(context.ALARM_SERVICE);
        alarm.cancel(sender);
    }

呼叫的地方 注意了一定要用當前系統時間 加上等待的時間
    long current = System.currentTimeMillis();
                long value = current + 60000; // 24 * 60 * 60 *1000
                AlarmUtil.startTimer(MainActivity.this,
                        AlarmUtil.ACTION_TIME_OVER, value);// 24 * 60 * 60 *1000
呼叫方法跟普通廣播差不多 先註冊再在onreceive中實現
註冊:
 registerNaviBroadcast(MainActivity.this,
                        AlarmUtil.ACTION_TIME_OVER);
private void registerNaviBroadcast(Context context, String action) {
        IntentFilter filter = new IntentFilter();
        filter.addAction(action);
        context.registerReceiver(mReceiver, filter);
    }
廣播接收實現
 private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) {
                return;
            }
            String action = intent.getAction();
            Log.d("MapFactoryTest", "onReceive action: "+action);
            switch (action) {
                case AlarmUtil.ACTION_TIME_OVER:
                 //..............
                    break;
            }
        }
    };