我复制了一个 GPSTracker.java
的课程public class GPSTracker extends IntentService implements LocationListener {
public static final String PREFS_NAME = "LocationTrackerPreferences";
private static final int DELTA_MINUTES = 1000 * 60; // * 1 = 1 min
private static final String TAG = "TAG";
// The minimum distance to change Updates in meters
// private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10
// meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 1 // 10 meters
// The minimum time between updates in milliseconds
// private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1
// minute
private static final long MIN_TIME_BW_UPDATES = 1000 * 10; // 10 milisecond
// Declaring a Location Manager
protected LocationManager locationManager;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
/**************
*
*/
private Context mContext;
public GPSTracker() {
super("GPSTracker");
}
public GPSTracker(Context context) {
super("GPSTracker");
Log.i(TAG, ">> object created");
this.mContext = context;
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
}
public void startUpdatingLocation() {
Log.i(TAG, ">> startUpdatingLocation");
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
canGetLocation = !(!isNetworkEnabled && !isGPSEnabled);
if (isGPSEnabled) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
getLocation(null);
}
public void stopLocationUpdates() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
Log.i(TAG, "Stopped Updates");
}
}
public Location getLocation(Location l) {
//Log.i(TAG, ">> getLocation >> 1");
long minTime = new Date().getTime() - DELTA_MINUTES; // The last 5
// minutes
Location bestResult = l;
long bestTime = Long.MAX_VALUE;
float bestAccuracy = Float.MAX_VALUE;
List<String> matchingProviders = locationManager.getAllProviders();
Log.i(TAG, "matchingProviders= " + matchingProviders);
boolean isFirstTime = true;
int counter = 0;
for (String provider : matchingProviders) {
Location location = locationManager.getLastKnownLocation(provider);
Log.i(TAG, counter + " in ForLoop provider = " + provider);
if (location != null) {
float accuracy = location.getAccuracy();
long time = location.getTime();
Date date = new Date(time);
Log.i(TAG, counter + " accuracy = " + accuracy + " time:" + date);
if (isFirstTime) {
Log.i(TAG, "FirstTime");
isFirstTime = false;
bestResult = location;
bestAccuracy = accuracy;
bestTime = time;
continue;
}
Date datemin = new Date(minTime);
Date datebesttime = new Date(bestTime);
Log.i(TAG, counter + " minTime= " + datemin
+ ", bestTime= " + datebesttime
+ ", bestAccuracy= " + bestAccuracy);
if ((time > minTime && accuracy < bestAccuracy)) {
Log.i(TAG, "in If");
bestResult = location;
bestAccuracy = accuracy;
bestTime = time;
} else if (time < minTime && bestAccuracy == Float.MAX_VALUE
&& time > bestTime) {
Log.i(TAG, "in else");
bestResult = location;
bestTime = time;
}
counter++;
}
}
if (bestResult != null) {
SharedPreferences.Editor locationPref = mContext.getSharedPreferences(OOPSv2.PREF_LOCATION, MODE_APPEND).edit();
locationPref.putString(OOPSv2.DATA_LONGITUDE, "" + bestResult.getLongitude());
locationPref.putString(OOPSv2.DATA_LATITUDE, "" + bestResult.getLatitude());
locationPref.commit();
Log.e(TAG, "Location : " + bestResult.getLongitude() + " : " + bestResult.getLatitude() + " SAVED....");
}
location = bestResult;
return bestResult;
}
/**
* Function to get latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
System.out.println("LAT ==" + latitude);
}
// return latitude
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
System.out.println("LONG ==" + longitude);
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* @return boolean
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
getLocation(location);
Log.i(TAG, "onLocationChanged");
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
我创建了另一项服务,其中一个计时器将每10秒执行一次以获取新位置:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
/** I AM GETTING ERROR HERE...... **/
GPSTracker tracker = new GPSTracker(VisitPlaceEveryHour.this);
tracker.startUpdatingLocation(); // This Line Giving Error
if (tracker.canGetLocation()) {
}
}
}
}
FATAL EXCEPTION: Timer-0
Process: com.koops.platina.sales, PID: 12267
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.location.LocationManager$ListenerTransport$1.<init>(LocationManager.java:227)
at android.location.LocationManager$ListenerTransport.<init>(LocationManager.java:227)
at android.location.LocationManager.wrapListener(LocationManager.java:864)
at android.location.LocationManager.requestLocationUpdates(LocationManager.java:877)
at android.location.LocationManager.requestLocationUpdates(LocationManager.java:464)
at com.salesman.utils.GPSTracker.startUpdatingLocation(GPSTracker.java:71)
at com.salesman.syncdata.VisitPlaceEveryHour$1.run(VisitPlaceEveryHour.java:92)
at java.util.Timer$TimerImpl.run(Timer.java:284)
如何调用该方法获取更新位置?还有其他办法吗?
注意:我已经看到了StackOverflow的所有解决方案,但没有找到 任何解决方案都贴在这里,善良。
谢谢。