获取与AsyncTask的GPS坐标 [英] Get gps coordinates with asyncTask

查看:184
本文介绍了获取与AsyncTask的GPS坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要让我的当前坐标。我尝试下,但没有得到结果。

 公共类FragmentNear扩展SherlockFragment工具
    android.location.LocationListener {
@覆盖
公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,
        捆绑savedInstanceState){
    的LocationManager =(的LocationManager)getActivity()。getSystemService(
            Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,0,0,这一点);
    V = inflater.inflate(R.layout.fragment_near,​​NULL);
    DownloadWebPageTask DW =新DownloadWebPageTask();
    dw.execute();
    返回伏;
}@覆盖
公共无效onLocationChanged(位置LOC){
    如果(showMFD == 0){
    Log.d(myLogs,-------- onLoChanged+ myLat ++ myLong);
    myLat = loc.getLatitude();
    myLong = loc.getLongitude();
    Log.d(myLogs,-------- onLoChangedEnd+ myLat ++ myLong);
    }
    }
公共无效showMFD(){
    showMFD ++;
            //我的任务
            }私有类DownloadWebPageTask扩展的AsyncTask<弦乐,太虚,字符串> {
    @覆盖
    保护字符串doInBackground(字符串的URL ...){
        Log.d(myLogs,背景);
        而(myLat == 0)
        {        }
        showMFD();
        返回;
    }
@覆盖
在preExecute保护无效()
{
super.on preExecute();PB =新ProgressDialog(getActivity());
pb.setMessage(ПолучениеданныхGPS ...);
pb.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pb.show();
}
 @覆盖
 保护无效onPostExecute(字符串结果){
        pb.dismiss();}
}

我的逻辑是在图片


解决方案

跟踪器类的一个示例使用WiFi或GPS经典(3G,H +,GPRS ...)

 公共类GPSTracker扩展服务实现android.location.LocationListener {
    / **
     *格式的属性
     * /
    私有静态最后弦乐TAG = GPSTracker.class.getSimpleName();
    私人语境_context;
    私有静态GPSTracker _instance;
    //最小距离改变米的更新
    私有静态最后长MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; //米
    //毫秒更新之间的最短时间
    私有静态最后长MIN_TIME_BW_UPDATES = 1000 * 30 * 1; //分钟
    //声明一个位置管理
    受保护的LocationManager _locationManager;
    / **
     * public属性
     * /
    布尔_isGPSEnabled = FALSE;
    布尔_isNetworkEnabled = FALSE;
    布尔_canGetLocation = FALSE;
    公共场所_location;
    双_latitude;
    双_longitude;    公共GPSTracker(){        _context = NULL;
    }    公共静态GPSTracker的getInstance(){        如果(_instance == NULL){
            _instance =新GPSTracker();
        }
        返回_instance;
    }    公共无效SET_CONTEXT(上下文的背景下){        this._context =背景;
    }    公共场所的getLocation(上下文的背景下){        _context =背景;
        尝试{
            _locationManager =(的LocationManager)_context.getSystemService(LOCATION_SERVICE);
            _isGPSEnabled = _locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            _isNetworkEnabled = _locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            如果(!_isGPSEnabled&放大器;&安培;!_isNetworkEnabled){
                //没有启用网络供应商
            }
            其他{
                this._canGetLocation = TRUE;
                如果(_isNetworkEnabled){
                    _locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES,这一点);
                    Log.d(网络,网络);
                    如果(_locationManager!= NULL){
                        _location = _locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        如果(_location!= NULL){
                            _latitude = _location.getLatitude();
                            _longitude = _location.getLongitude();
                        }
                    }
                }
                //如果GPS功能的获得纬度/长期使用GPS服务
                如果(_isGPSEnabled){
                    如果(_location == NULL){
                        _locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES,这一点);
                        Log.d(GPS已启用,GPS功能的);
                        如果(_locationManager!= NULL){
                            _location = _locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            如果(_location!= NULL){
                                _latitude = _location.getLatitude();
                                _longitude = _location.getLongitude();
                            }
                        }
                    }
                }
            }
        }
        赶上(例外五){
            // 没做什么
        }
        返回_location;
    }    公共无效stopUsingGPS(){        如果(_locationManager!= NULL){
            _locationManager.removeUpdates(GPSTracker.this);
        }
    }    公共双getLatitude(){        如果(_location!= NULL){
            _latitude = _location.getLatitude();
        }
        返回_latitude;
    }    公共双getLongitude(){        如果(_location!= NULL){
            _longitude = _location.getLongitude();
        }
        返回_longitude;
    }    公共布尔canGetLocation(){        返回this._canGetLocation;
    }    / **
     *功能,以显示设置警告对话框在pressing设置按钮将劳克设置选项
     * /
    公共无效showSettingsAlert(字符串名称,弦乐味精){        AlertDialog.Builder alertDialog =新AlertDialog.Builder(_context);
        alertDialog.setTitle(职称);
        alertDialog.setMessage(MSG);
        //设置按钮
        alertDialog.setPositiveButton(参数应用,新DialogInterface.OnClickListener(){
            公共无效的onClick(DialogInterface对话,诠释它){                意向意图=新意图(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                _context.startActivity(意向);
            }
        });
        //取消按钮
        alertDialog.setNegativeButton(更改或取消,新DialogInterface.OnClickListener(){
            公共无效的onClick(DialogInterface对话,诠释它){                dialog.cancel();
            }
        });
        // 显示
        alertDialog.show();
    }    @覆盖
    公共无效onLocationChanged(地点){    }    @覆盖
    公共无效onProviderDisabled(字符串提供商){    }    @覆盖
    公共无效onProviderEnabled(字符串提供商){    }    @覆盖
    公共无效onStatusChanged(字符串提供商,INT地位,捆绑演员){    }    @覆盖
    公众的IBinder onBind(意向为arg0){        返回null;
    }
}

这是快如网络/ GPS /电话(感谢机器人),你只需要创建GPSTracker.java然后一个对象:

  //创建一个实例单
GPSTracker跟踪= GPSTracker.getInstance();
//你可以使用这个如果测试如果位置更新OK
gpsTracker.canGetLocation()
//用这种方法尽可能多的,只要你想更新的位置
tracker.getLocation(本);
// retreive的位置,当你需要它
地点= EtablissementApplication._gpsTracker._location

:当您不想要使用GPS了,不要忘记

在的onDestroy()或

 如果(跟踪!= NULL){
    tracker.stopUsingGPS();
}

i need to get my current coordinates. i try next, but it is does not get result.

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();

}
}

My logic is in the picture

解决方案

An example of tracker class to use wifi or classic 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;
    }
}

It is as fast as the network/gps/phone (thanks android) you just need to create GPSTracker.java then an object :

//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

In onDestroy() or when you don't want to use the gps anymore don't forget :

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

这篇关于获取与AsyncTask的GPS坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆