更新时间:2023-10-22 22:16:40
每分钟杀死应用程序后,使用广播接收器保持运行计时器:
Use a broadcast receiver to keep running the timer after killing application every minute:
public class TimerReceiverSyncInterval extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
scheduleAlarms(context);
context.startService(new Intent(context, NotificationServiceSyncInterval.class));
Log.d("TAG", "Sync OnReceive");
}
public static void scheduleAlarms(Context paramContext) {
Calendar calendar = Calendar.getInstance();
AlarmManager localAlarmManager = (AlarmManager) paramContext.getSystemService(Context.ALARM_SERVICE);
PendingIntent localPendingIntent = PendingIntent.getService(paramContext, 0,
new Intent(paramContext, NotificationServiceSyncInterval.class), PendingIntent.FLAG_UPDATE_CURRENT);
localAlarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),
(1 * 60000), localPendingIntent);
}
}
在下面的类中,在 TimerReceiverSyncInterval 类中每分钟调用一次的 onHandleIntent 方法中执行您想要的任何操作:
And in the class below, do whatever you want in onHandleIntent method that is called every minute from TimerReceiverSyncInterval class:
public class NotificationServiceSyncInterval extends IntentService {
public NotificationServiceSyncInterval() {
super("Tracker");
}
public NotificationServiceSyncInterval(String paramString) {
super(paramString);
}
@Override
protected void onHandleIntent(Intent intent) {
//ToDo: put what you want to do here
Log.d("TAG", "Handler call");
}
}
在清单文件中创建一个条目:
Make a entry in the manifest file:
<receiver
android:name="com.yourpackage.TimerReceiverSyncInterval"
android:enabled="true" >
<intent-filter android:priority="999" >
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<service android:name="com.yourpackage.NotificationServiceSyncInterval" />
最后像这样从 MainActivity 注册广播接收器:
And finally register the broadcast receiver from MainActivity like this:
TimerReceiverSyncInterval.scheduleAlarms(this);