Android - 每次变化时做某事的最佳方法是什么?

时间:2017-03-16 09:40:09

标签: android alarmmanager timed

我希望每一分钟都能做一些事情,例如当时间从10:38变为10:39时我想做点什么。

这样做的最佳方式是什么?

3 个答案:

答案 0 :(得分:2)

您需要通过广播接收器收听TIME_TICK

IntentFilter timeTickIntentFilter = new IntentFilter(Intent.ACTION_TIME_TICK);
registerReceiver(YourReceiver, timeTickIntentFilter);

答案 1 :(得分:2)

请使用AlarmManager

void startSchedulerAlarm() {
    int oneMinute = 1 * (60 * 1000); //Trigger Every 1 Minute
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.setAction(AlarmReceiver.alaramIntent);
    PendingIntent alarmIntent = PendingIntent.getBroadcast(context, AlarmReceiver.alarmIntentCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), oneMinute, alarmIntent);

}

void stopSchedulerAlarm() {
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.setAction(AlarmReceiver.alaramIntent);
    PendingIntent alarmIntent = PendingIntent.getBroadcast(context, AlarmReceiver.alarmIntentCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    alarmManager.cancel(alarmIntent);
}

为清单中的警报创建一个接收器:

    <receiver       
        android:name="{YOUR_PACKAGE_NAME}.AlarmReceiver"
        android:enabled="true"
        android:process=":remote">
        <intent-filter>
            <action android:name="{YOUR_PACKAGE_NAME}.alarmIntent"/>
        </intent-filter>
    </receiver> 

公共类AlarmReceiver扩展了BroadcastReceiver {

public static final String alaramIntent = "{YOUR_PACKAGE_NAME}.alarmIntent";
public static final int alarmIntentCode = 000054310;

private String TAG = AlarmReceiver.class.getSimpleName();

   @Override
   public void onReceive(Context context, Intent intent) {
        //Do something Here
   }
}

答案 2 :(得分:0)

在后台继续运行服务,继续检查指定的时间,假设你想在晚上10点将手机转为静音模式。所以服务应该继续检查是否时间是晚上10点,当它是时,执行代码将手机转为静音模式