美好的一天。我学习了有关LocationListener的所有内容并查看了不同的示例 - 但每次在不同设备上进行一些测试都会让我感到不安。 所以,我请你帮忙。 故障设备:三星Galaxy S1,Galaxy fit,htc one v,HTC Incredible S,Pipo Smart S1等等。 NoProblem设备:三星Galaxy S3。帮助:)
目前的实施:
public class LocationListener implements android.location.LocationListener
{
// Current myLocation
private LocationManager mLocationManager = null;
private boolean mLocationEnabled = false;
private volatile Location mLocation;
private LocationListener locationListener;
private volatile boolean locationChanged = false;
//interface implementation Runnable which called UI methods
private LocationRunnable runnable = null;
public LocationListener(Context context, LocationRunnable runnable)
{
this.runnable = runnable;
mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
mLocation = null;
}
public boolean enableMyLocation()
{
mLocationEnabled = true;
List<String> mProviders = mLocationManager.getProviders(true);
if (mProviders.size() > 0)
{
locationListener = this;
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 1, locationListener);
}
//start background process to count 30 secs
new TimeOut().execute();
return false;
}
public void disabledMyLocation()
{
if (mLocationManager != null)
mLocationManager.removeUpdates(this);
}
private class TimeOut extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... params)
{
long sec = System.currentTimeMillis();
//here we count 30 secs and if method onLocationChanged wasn't run before, start runnable here
while (!locationChanged && System.currentTimeMillis() - sec < 30 * 1000)
{}
return null;
}
@Override
protected void onPostExecute(Void p)
{
if (!locationChanged)
{
runnable.setLocation(mLocation);
runnable.run();
}
//cancel update
mLocationManager.removeUpdates(locationListener);
}
}
public void onLocationChanged(Location location)
{
//if location is OK so call UI changing
mLocation = location;
locationChanged = true;
runnable.setLocation(location);
runnable.run();
//cancel update
mLocationManager.removeUpdates(locationListener);
}
}