看看这个简单的代码
public class TimerReceiverSyncInterval extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("TAG", "Sync OnReceive--");
scheduleAlarms(context);
context.startService(new Intent(context, NotificationServiceSyncInterval.class));
}
public static void scheduleAlarms(Context paramContext) {
Calendar calendar = Calendar.getInstance();
String[] splited = mPrefs.getSyncTime().split("\\s+");
if (mPrefs.getSyncTime().contains("Minute")) {
calendar.set(Calendar.MINUTE, Integer.parseInt(splited[0]));
} else if (mPrefs.getSyncTime().contains("Hour")) {
calendar.set(Calendar.HOUR, Integer.parseInt(splited[0]));
}
AlarmManager localAlarmManager = (AlarmManager) paramContext.getSystemService(Context.ALARM_SERVICE);
PendingIntent localPendingIntent = PendingIntent.getService(paramContext, 0,
new Intent(paramContext, NotificationServiceSyncInterval.class), PendingIntent.FLAG_UPDATE_CURRENT);
if (mPrefs.getSyncTime().contains("Minute")) {
localAlarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),
Integer.parseInt(splited[0]) * (60 * 1000), localPendingIntent);
} else if (mPrefs.getSyncTime().contains("Hour")) {
localAlarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),
Integer.parseInt(splited[0]) * (60 * 60 * 1000), localPendingIntent);
}
Log.d("TAG", "Sync------");
}
我在这里拆分小时、分钟,因为我的设置包含 15 分钟、1 小时等,您可以根据需要设置它,例如天、周等
public class NotificationServiceSyncInterval extends IntentService {
public NotificationServiceSyncInterval() {
super("Sync Tracker Online");
}
public NotificationServiceSyncInterval(String paramString) {
super(paramString);
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d("TAG", "Sync Handler call");
// todo
callSync();
}
public static void callSync() {
try {
//Your Sync Code here
} catch (Exception e) {
e.printStackTrace();
}
}
上述类的清单条目
<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" >
</service>
最后在用户选择时间间隔时分配上下文,即 TimerReceiverSyncInterval.scheduleAlarms(this);