在安卓系统中如何在没有GPS的情况下确定当前位置

7
我希望开发一个应用程序,打开应用程序后它将显示我的设备的当前位置。我想在不使用GPS的情况下完成这项任务。我已经编写了代码,但在打开地图时,它会显示美国的位置,而我希望它显示我的当前位置(即印度普纳)。请问如何获取我的近似正确位置?
以下是我的代码:
protected void onCreate(Bundle arg0) {
    // TODO Auto-generated method stub
    super.onCreate(arg0);
    setContentView(R.layout.main);

    LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

      LocationListener locListener = new LocationListener(){
          public void onLocationChanged(Location loc)
          {

            loc.getLatitude();
            loc.getLongitude();

            String Text = "My current location is: " +
            "Latitud = " + loc.getLatitude() +
            "Longitud = " + loc.getLongitude();

            Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
          }

我已经在清单文件中添加了所有必需的权限,如Internet、粗略和精确位置。 - PrasadM
3个回答

11

这里是一个用于获取当前位置的MyLocation监听器,不需要使用GPS,而是使用网络提供商

public class MyLocationListener extends Service implements LocationListener {

    private static final String TAG = "MyLocationListener";

    private Context context = null;
    private Location location = null;
    private LocationManager locationManager = null;

    boolean isNetworkEnabled = false;
    boolean canGetLocation = false;

    public double latitude = 0.0;
    public double longitude = 0.0;

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    public MyLocationListener(Context ctx) {
        Log.v(TAG + ".MyLocationListener",
                "MyLocationListener constructor called");
        this.context = ctx;
        getLocationValue();
    }

    public Location getLocationValue() {
        Log.v(TAG + ".getLocationValue", "getLocationValue method called");

        try {
            locationManager = (LocationManager) context
                    .getSystemService(LOCATION_SERVICE);

            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (isNetworkEnabled) {

                // Toast.makeText(context, "Net", 1).show();
                Log.v(TAG + ".getLocationValue", "Network provider enabled");
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        Log.v(TAG, "Co-ordinates are: " + latitude + " "+ longitude);

                    }
                }

            } else {
                showSettingsAlert();
            }

        } 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) {
            locationManager.removeUpdates(MyLocationListener.this);
        }
    }

    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }
        return latitude;
    }

    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }
        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(context);

        alertDialog.setTitle("GPS Settings");
        alertDialog
                .setMessage("GPS is not enabled. Do you want to go to settings menu?");

        alertDialog.setPositiveButton("Settings",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(
                                Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        context.startActivity(intent);
                    }
                });
        alertDialog.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
        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 intent) {
        return null;
    }

}

每当您需要当前位置坐标时,只需调用上面的代码即可

MyLocationListener mylistner = new MyLocationListener(context);
        double lat = mylistner.latitude;
        double lon = mylistner.longitude;

它将在未启用GPS的情况下弹出“SettingsAlert”! - zionpi
这里的Service类有什么用处? - Alvi

4
你应该请求“mlocManager”进行定位,并设置其监听器:
public void getCurrentLocation()
{
    if (mlocManager != null) {
        mlocManager .requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER, 0, 0, locListener );
        mlocManager .requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 0, 0, locListener );
    }

}

1

我并没有觉得LocationListener有什么用处,但是为了防止空指针异常,还是需要将其放入代码中。

// Set the criteria of what to look for
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_LOW);

// This will find the location of the device via your network, but give user option to use GPS if needed
String locationprovider = mlocManager.getBestProvider(criteria,
            true);

mLoc = mlocManager.getLastKnownLocation(locationprovider);
if (mLocation != null)
{
    String Text = "My current location is: " +
    "Latitud = " + mLoc.getLatitude() +
    "Longitud = " + mLoc.getLongitude();
} else
{
    String Text = "No location found."
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接