Android LocationManager 为纬度和经度提供 0.0

Android LocationManager gives 0.0 for latitude and longitude

我有一个 LocationManager,可以在单击按钮时从 android 设备获取 gps 经度和纬度。我的问题是它总是给我 0.0 我不知道这有什么问题。我给了它 MyLocation.java 和 AndroidManifest.xml 的权限我也检查了是否有 gps 信号。

MyLocation.java

public class MyLocation extends Service implements LocationListener {

private final Context mContext;

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

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public MyLocation(Context context) {
    this.mContext = context;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                        || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                }
                if (locationManager != null) {
                    if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                            || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    }
                    if (location != null) {
                        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                                || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                            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) {
        e.printStackTrace();
    }

    return location;
}

/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 * */
public void stopUsingGPS(){
    if(locationManager != null){
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            locationManager.removeUpdates(MyLocation.this);
        }
    }
}

/**
 * Function to get latitude
 * */
public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog
 * On pressing Settings button will lauch Settings Options
 * */
public void showSettingsAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    // Showing Alert Message
    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;
}

}

tablelayout.java

public class tablelayout extends Activity implements View.OnClickListener {
Button btn, btn2;
MyLocation myLocation;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.bundle2);
            /* create button */
    btn=(Button)findViewById(R.id.Button01);
    btn.setOnClickListener(this);
            /* delete button */
    btn2=(Button)findViewById(R.id.Button02);
    btn2.setOnClickListener(this);
}

public void onClick(View view){
    if (view == btn) {
        TableLayout tl = (TableLayout) findViewById(R.id.TableLayout01);
        TableRow tr = new TableRow(this);

            /* get date */
        SimpleDateFormat dtformat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        Date mydate = new Date();
        String dateString = dtformat.format(mydate);
        TextView dt = new TextView(this);
        dt.setText(dateString);
        dt.setGravity(Gravity.CENTER_HORIZONTAL);

            /* get time */
        SimpleDateFormat tmformat = new SimpleDateFormat("HH:mm", Locale.getDefault());
        Date mytime = new Date();
        String timeString = tmformat.format(mytime);
        TextView tm = new TextView(this);
        tm.setText(timeString);
        tm.setGravity(Gravity.CENTER_HORIZONTAL);

            /* drop-down list */

        String[] species = getResources().getStringArray(R.array.speciesList);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,species);
        AutoCompleteTextView autoComplete = new AutoCompleteTextView(this);
        autoComplete.setAdapter(adapter);
        autoComplete.setThreshold(1);
        autoComplete.setDropDownWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        autoComplete.setTextSize(10);
        int options = autoComplete.getImeOptions();
        autoComplete.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI|EditorInfo.IME_ACTION_DONE|EditorInfo.IME_FLAG_NO_FULLSCREEN);

            /* GPS location */

        TextView latitudeTv = new TextView(this);
        TextView longitudeTv = new TextView(this);

        // create class object
        myLocation = new MyLocation(tablelayout.this);

        // check if GPS enabled
        if (myLocation.canGetLocation()) {

            Double latitude =myLocation.getLatitude();
            Double longitude =myLocation.getLongitude();

            latitudeTv.setText(latitude.toString());
            longitudeTv.setText(longitude.toString());
        } else {
            // can't get location
            // GPS or Network is not enabled
            // Ask user to enable GPS/network in settings
            myLocation.showSettingsAlert();
        }

            /* user input */
        EditText et3 = new EditText(this);
        et3.setImeOptions(options|EditorInfo.IME_FLAG_NO_EXTRACT_UI|EditorInfo.IME_ACTION_DONE);
        et3.setInputType(InputType.TYPE_CLASS_NUMBER);
        EditText et4 = new EditText(this);
        et4.setImeOptions(options|EditorInfo.IME_FLAG_NO_EXTRACT_UI|EditorInfo.IME_ACTION_DONE);

        tr.addView(dt);
        tr.addView(tm);
        tr.addView(autoComplete);
        tr.addView(latitudeTv);
        tr.addView(longitudeTv);
        tr.addView(et3);
        tr.addView(et4);
        tl.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
    }
    if (view == btn2) {
        TableLayout tl = (TableLayout) findViewById(R.id.TableLayout01);
        int rowNumber = tl.getChildCount();
        tl.removeViews(rowNumber-1,1);
    }
    }

}

AndroidManifest.java

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

此问题与懒惰的 gps 传感器和延迟有关。所以你有 2 个解决方案基于你的需要

1- 在您的 onclicklistener 之外启动并实例化您的 myLocation class(例如在 oncreate 中)。所以当你点击你的按钮时,你的 phone 传感器有一段时间与卫星同步。

2- 在你的 activity(之前)和 myLocation 中的 onLocationChanged 方法中启动你的 myLocation,将位置参数发送到另一个 class 中的静态变量(例如:sharingGps)。所以你可以从每个 activity 和 classes

的 sharingGps 中获取你的位置