【问题标题】:Android: Send user location to the server every 15 minutes only if the location has been changed?Android:仅当位置已更改时,才每 15 分钟将用户位置发送到服务器?
【发布时间】:2014-10-15 14:50:00
【问题描述】:

我的应用向用户提供与位置相关的通知,这意味着我需要尽可能实时地了解用户的位置,并且不会对电池造成太大压力。我进行了一些研究并创建了以下选项列表

  • partial Wakelock:让屏幕超时但 CPU 继续执行任务。但我只想每 n 秒调用一次我的后台代码,检查位置更新,如果位置发生更改,然后将其发送到服务器。
  • AlarmManager:我可以用它来设计重复任务,但不确定它是否会无限期地在后台运行,是否会被用户故意杀死。

只要应用程序安装在用户的手机上,我希望每隔 n 秒调用一次我的后台代码。我正在寻找理论答案而不是实际代码,因为我需要了解我在做什么。

【问题讨论】:

标签: android location


【解决方案1】:

你可以如下使用Service类,

public class StartService extends Service {

Timer timer = new Timer();
private final int TIME_INTERVAL = 10000;
GPSTracker GPSTracker;
Double latitude  ;
Double longitude ;



@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
    GPSTracker = new GPSTracker(StartService.this);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    doTimerThings();
    return super.onStartCommand(intent, flags, startId);
}

private void doTimerThings() 
{
    timer.scheduleAtFixedRate(new TimerTask() {

        @SuppressLint("DefaultLocale")
        @TargetApi(Build.VERSION_CODES.GINGERBREAD)
        @Override
        public void run() {



            latitude = GPSTracker.getLatitude();
            longitude = GPSTracker.getLongitude();

            // you get the lat and lng , do your server stuff here-----

            System.out.println("lat------ "+latitude);
            System.out.println("lng-------- "+longitude);
        }

    }, 0, TIME_INTERVAL);

}




@Override
public void onDestroy() {
    super.onDestroy();
}


}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-23
    • 2012-01-27
    • 1970-01-01
    • 2017-12-28
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多