0

再会。我了解了有关 LocationListener 的所有信息,并查看了不同的示例——但每次在不同设备上进行的一些测试都让我感到不安。所以,我请你帮忙。故障设备:三星 Galaxy S1、Galaxy fit、htc one v、HTC Incredible S、Pipo Smart S1 等。无问题设备:三星 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);
    }

}
4

0 回答 0