我可以通过创建时间线程(AsyncTask)来制作Android计时器。
但是,当片段被停止/或销毁并重新启动/重新创建时,
时间线程仍在运行但它无法动态更改屏幕UI并且片段页面已重置。
如果您可以通过创建asyncTask线程来创建计时器,问题是用户离开屏幕并返回后时间不会更新。
如何创建一个能够以任何方式解决问题的Android应用程序?
答案 0 :(得分:0)
首先,你必须创建一个广播接收器,当闹钟时间改变和手机启动时会触发。
的AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver android:name="AlarmBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
</intent-filter>
</receiver>
<receiver android:name="AlertBroadcastReceiver"/>
此广播接收器将触发服务以进行闹钟时间计算,并在闹钟时间结束时处理操作。
public class AlarmBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context, AlarmService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
context.startForegroundService(serviceIntent);
else
context.startService(serviceIntent);
}
}
在服务类中。您应该以毫秒计算闹钟时间并使用Alarm Manager Class进行设置。此外,您应设置PendingIntent以在闹钟时间到来时开始操作。
Intent startIntent = new Intent(getBaseContext(), AlertBroadcastReceiver.class);
startIntent.putExtra("alarm", alarmContent);
startIntent.putExtra("type", "start");
PendingIntent pendingIntentStart = PendingIntent.getBroadcast(getBaseContext(), 0, startIntent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManagerStart = (AlarmManager) getBaseContext().getSystemService(Context.ALARM_SERVICE);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
alarmManagerStart.set(AlarmManager.RTC_WAKEUP, getAlarmTime(alarmArray, "start").getTimeInMillis(), pendingIntentStart);
}
else if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT && Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
alarmManagerStart.setExact(AlarmManager.RTC_WAKEUP, getAlarmTime(alarmArray, "start").getTimeInMillis(), pendingIntentStart);
}
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(getAlarmTime(alarmArrayNd, "start").getTimeInMillis() >= 900000)
alarmManagerStart.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, getAlarmTime(alarmArray, "start").getTimeInMillis(), pendingIntentStart);
else
alarmManagerStart.setExact(AlarmManager.RTC_WAKEUP, getAlarmTime(alarmArray, "start").getTimeInMillis(), pendingIntentStart);
}
在这个例子中,方法getAlarmtime()是一个计算闹钟时间的方法,我创建的警报时间也是意图中的额外内容是任意的,你可以把你想要的任何内容放入其中。
答案 1 :(得分:0)