import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;
public class LocationService extends Service {
private LocationDatabaseHelper mLocationDatabaseHelper;
private LocationModel mLocationModel;
private Date mDate;
private Handler mHandler = new Handler();
private Timer mTimer = null;
private int mCount = 0;
public static final long NOTIFY_INTERVAL = 30 * 1000;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
// cancel if already existed
if (mTimer != null) {
mTimer.cancel();
} else {
// recreate new
mTimer = new Timer();
}
mLocationModel = LocationModel.getInstance();
// schedule task
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
}
@Override
public void onDestroy() {
mTimer.cancel();
}
private class TimeDisplayTimerTask extends TimerTask implements LocationListener {
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
//I send message to draw map here
sendMessage();
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
TimeDisplayTimerTask.this);
}
});
}
@Override
public void onLocationChanged(Location location) {
// I get location and do work here
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
private void sendMessage() {
Intent intent = new Intent("my-event");
intent.putExtra("message", "data");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
我想要的是每30秒获取一次用户位置,但是此代码无法正常运行。它的位置非常快(我想每秒)。
我尝试以这种方式获取位置信息,因为它可以在启动我的应用程序后立即获取我的当前位置。我之前曾尝试过getLastKnowLocation,但是它给了我最后一个已知的位置,该位置离我的位置很远。
请告诉我如何解决此问题。谢谢!
在requestLocationUpdates方法中,第二个参数是位置更新之间的最小时间间隔(以毫秒为单位),因此您只需要执行以下操作:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30 * 1000, 0, TimeDisplayTimerTask.this);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句