android - 使用asyncTask获取GPS坐标

标签 android android-asynctask gps location google-maps-api-2

我需要获取当前坐标。我尝试下一个,但是没有得到结果。

public class FragmentNear extends SherlockFragment implements
    android.location.LocationListener {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    locationManager = (LocationManager) getActivity().getSystemService(
            Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 0, 0, this);
    v = inflater.inflate(R.layout.fragment_near, null);
    DownloadWebPageTask dw = new DownloadWebPageTask();
    dw.execute("");
    return v;
}

@Override
public void onLocationChanged(Location loc) {
    if (showMFD == 0) { 
    Log.d("myLogs", "-------- onLoChanged " + myLat + " " + myLong);
    myLat = loc.getLatitude();
    myLong = loc.getLongitude();
    Log.d("myLogs", "-------- onLoChangedEnd " + myLat + " " + myLong); 
    }
    }
public void showMFD() {
    showMFD++;
            //my Tasks
            }

private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        Log.d("myLogs", "Background");
        while (myLat==0)
        {

        }
        showMFD();
        return "";
    }
@Override
protected void onPreExecute()
{
super.onPreExecute();

pb = new ProgressDialog(getActivity());
pb.setMessage("Получение данных GPS...");
pb.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pb.show();
}
 @Override
 protected void onPostExecute(String result) {
        pb.dismiss();

}
}


我的逻辑在图片中

最佳答案

使用wifi或经典gps(3g,h +,gprs ...)的跟踪器类示例

public class GPSTracker extends Service implements android.location.LocationListener {
    /**
     * ATTRIBUTES
     */
    private static final String TAG                             = GPSTracker.class.getSimpleName();
    private Context             _context;
    private static GPSTracker   _instance;
    // The minimum distance to change Updates in meters
    private static final long   MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;                                // meters
    // The minimum time between updates in milliseconds
    private static final long   MIN_TIME_BW_UPDATES             = 1000 * 30 * 1;                    // minute
    // Declaring a Location Manager
    protected LocationManager   _locationManager;
    /**
     * PUBLIC ATTRIBUTES
     */
    boolean                     _isGPSEnabled                   = false;
    boolean                     _isNetworkEnabled               = false;
    boolean                     _canGetLocation                 = false;
    public Location             _location;
    double                      _latitude;
    double                      _longitude;

    public GPSTracker() {

        _context = null;
    }

    public static GPSTracker getInstance() {

        if (_instance == null) {
            _instance = new GPSTracker();
        }
        return _instance;
    }

    public void set_context(Context context) {

        this._context = context;
    }

    public Location getLocation(Context context) {

        _context = context;
        try {
            _locationManager = (LocationManager) _context.getSystemService(LOCATION_SERVICE);
            _isGPSEnabled = _locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            _isNetworkEnabled = _locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            if (!_isGPSEnabled && !_isNetworkEnabled) {
                // no network provider is enabled
            }
            else {
                this._canGetLocation = true;
                if (_isNetworkEnabled) {
                    _locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (_locationManager != null) {
                        _location = _locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (_location != null) {
                            _latitude = _location.getLatitude();
                            _longitude = _location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (_isGPSEnabled) {
                    if (_location == null) {
                        _locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (_locationManager != null) {
                            _location = _locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (_location != null) {
                                _latitude = _location.getLatitude();
                                _longitude = _location.getLongitude();
                            }
                        }
                    }
                }
            }
        }
        catch (Exception e) {
            // do nothing
        }
        return _location;
    }

    public void stopUsingGPS() {

        if (_locationManager != null) {
            _locationManager.removeUpdates(GPSTracker.this);
        }
    }

    public double getLatitude() {

        if (_location != null) {
            _latitude = _location.getLatitude();
        }
        return _latitude;
    }

    public double getLongitude() {

        if (_location != null) {
            _longitude = _location.getLongitude();
        }
        return _longitude;
    }

    public boolean canGetLocation() {

        return this._canGetLocation;
    }

    /**
     * Function to show settings alert dialog On pressing Settings button will lauch Settings Options
     */
    public void showSettingsAlert(String title, String msg) {

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(_context);
        alertDialog.setTitle(title);
        alertDialog.setMessage(msg);
        // Settings button
        alertDialog.setPositiveButton("Paramètres", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                _context.startActivity(intent);
            }
        });
        // cancel button
        alertDialog.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

                dialog.cancel();
            }
        });
        // show
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public IBinder onBind(Intent arg0) {

        return null;
    }
}


它与您只需要创建GPSTracker.java然后创建一个对象的网络/ GPS /电话(感谢android)一样快:

//create an instance singleton
GPSTracker tracker = GPSTracker.getInstance();
// you can use this in "if" to test if location is updated ok
gpsTracker.canGetLocation()
//update the location as much as you want with this method
tracker.getLocation(this);
//retreive the location when you need it
Location location = EtablissementApplication._gpsTracker._location


在onDestroy()中,或者当您不想再使用gps时,请不要忘记:

if (tracker != null) {
    tracker.stopUsingGPS();
}

关于android - 使用asyncTask获取GPS坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18446619/

相关文章:

android - 在Android中的 map View 上绘制一定半径的圆

java - 在调试期间显示项目,否则不在 ListView 中显示项目

java - Android AsyncTask 媒体播放器通信

Android 事件总线替代方案

android - 在连接到互联网之前无法获取当前位置 - Android GPS

android - 如何使用 View.OnTouchListener 而不是 onClick

android - 我的用户报告我的应用程序崩溃了——我从来没有在模拟器中看到过这个

带处理程序的 Android AsyncTask

java - 从 JNI 将 LocationManager.addGpsStatusListener 与 Android 一起使用不会导致任何事情发生

android - Android 中的 Google map 将纬度/经度初始化为 0.0(有时...)