android中的AlarmManager for BroadcastReciever

时间:2015-09-08 21:26:16

标签: java android service broadcastreceiver alarmmanager

我一直在尝试使用AlarmManager重复一个动作但是,它工作正常一次,然后在20秒后不会一次又一次地重复。

userSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);};

BroadcastReciever安排Alaram:

module.exports = mongoose.model('User', userSchema);

我的加载服务的广播接收器:

public class CheckingService extends Service {
    private static final String APP_TAG = "com.test";

    @Override
    public IBinder onBind(final Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(final Intent intent, final int flags,
                              final int startId) {
        Log.d(APP_TAG, "event received in service: " + new Date().toString());
        Toast.makeText(CheckingService.this, "TEST", Toast.LENGTH_SHORT).show();
        return Service.START_NOT_STICKY;
    }


 }

在我使用启动的最后一个AndroidManifest.xml中

public class SchedulerReciever extends BroadcastReceiver {
    public SchedulerReciever() {
    }

    private static final String APP_TAG = "com.test";

    private static final int EXEC_INTERVAL = 20 * 10;

    @Override
    public void onReceive(final Context ctx, final Intent intent) {
        Log.d(APP_TAG, "onReceive() called");
        AlarmManager alarmManager = (AlarmManager) ctx
                .getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(ctx, MyBraoadCastReciever.class); // explicit
        // intent
        PendingIntent intentExecuted = PendingIntent.getBroadcast(ctx, 0, i,
                PendingIntent.FLAG_CANCEL_CURRENT);
        Calendar now = Calendar.getInstance();
        now.add(Calendar.SECOND, 2);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                now.getTimeInMillis(), EXEC_INTERVAL, intentExecuted);
    }
}

1 个答案:

答案 0 :(得分:0)

您的EXEC_INTERVAL设置为200毫秒而不是20 * 1000(20秒)。

此外,如果您使用setRepeating,最好使用自手机启动以来的相对时间AlarmManager.ELAPSED_REALTIME_WAKEUP,而不是创建日历,您只需拨打SystemClock.elapsedRealtime()或使用可选的偏移量2s SystemClock.elapsedRealtime() + 2000

所以你的设置重复应该是这样的:

alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + 2000, EXEC_INTERVAL, intentExecuted);