将坐标发送到服务器10秒

时间:2013-12-06 06:55:46

标签: android gps

我正在创建一个应用程序,每隔10秒就将我的gps坐标发送到服务器。 是)我有的: 活动,启动我的服务。在服务onStart我创建位置管理器:

locationManager = (LocationManager) this
                    .getSystemService(LOCATION_SERVICE);
        Intent i = new Intent(GpsReceiver.GPS_ACTION);
        PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, i, 0);
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        locationManager.requestLocationUpdates(MIN_TIME_BW_UPDATES, MIN_TIME_BW_UPDATES, criteria, pIntent);

我的广播注册活动。

public class GpsReceiver extends BroadcastReceiver {
    public static final String GPS_ACTION = "gps.ACTION";
    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent != null) {
            String key = LocationManager.KEY_LOCATION_CHANGED;
            try {
                Location location = (Location) intent.getExtras().get(key);
            }
            catch(Exception e) {
                e.printStackTrace();
            }
        }
    }
}

现在我需要每隔10秒将我的坐标发送到服务器。

我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

使用scheduleTaskExecutor

public static ScheduledExecutorService scheduleTaskExecutor;

scheduleTaskExecutor = Executors.newScheduledThreadPool(2);

private void startThreadOnce() {

    scheduleTaskExecutor.scheduleAtFixedRate(
            new Runnable() {

                @Override
                public void run() {
                    // Send data here.
                }
            }, 0, 10, TimeUnit.SECONDS); // 0 >> initial delay, 10 >> every x., TimeUnit.SECONDS >> in seconds

}

只打电话startThreadOnce()一次。 run()方法将每10秒执行一次。

将其杀死。删除。

@Override
public void onDestroy() {
    super.onDestroy();
    scheduleTaskExecutor.shutdown();
    scheduleTaskExecutor.shutdownNow();
    scheduleTaskExecutor = null;
}