您使用 Intent 服务和 Broadcastreceiver 组件,因为这些组件只会持续侦听,即使您关闭应用程序也是如此。
如果您想每 90 秒获取一次信息,请使用警报管理器。
AlarmManager manager = (AlarmManager) (context)
.getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(context, YourAlarmReceuver.class);
//alarmIntent.putExtra("syncData", favoritesArrayList);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(), 90*1000, pendingIntent);
你的接收器类是这样的
public class SyncAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent stIntent = new Intent(context,
YourService.class);
context.startService(stIntent);
}
你的 Intent 服务类是这样的
public class DataSyncService extends IntentService {
public DataSyncService() {
super(DataSyncService.class.getName());
// TODO Auto-generated constructor stub
}
@Override
protected void onHandleIntent(Intent intent) {
//write your logic here
// get the location and update the database
}
}
您应该也实例化警报管理器启动完成。