简体   繁体   中英

Android GPS Location of the User

I need to get the Users Location for my app so that i can display the directions on Google Maps based on two Lat and Long.

If the Users GPS is switched off it should ask the user if he wants to switch on the GPS and should be able to take him the Settings to switching it on.

i am trying the following but it takes me directly to the settings i wonder how to let the user ask if he wants to be taken away.

Is there any Library that does this efficiently i would prefer using it to get the Lat and Long of the user.

If you're asking how to ask the user if he's interested in being navigated to the setting page, in order to turn location services on - I would recommend simply presenting a Dialog. Here's an example from my project :

// Presents dialog screen - location services
private void askLocationDialog(){
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

    alertDialogBuilder.setTitle(R.string.snoox_use_location_services_dialog);

    // set dialog message
    alertDialogBuilder.setMessage(R.string.would_you_like_to_turn_your_location_services_on_)
    .setCancelable(false)
    .setPositiveButton(R.string.ok,new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int id) {
            // opens the setting android screen
            Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(settingsIntent);
        }
    })
    .setNegativeButton(R.string.no,new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int id) {
            dialog.cancel();
        }
    });

    // create alert dialog
    alertDialogBuilder.create().show();
}

if you're interested in a full example I found this post helpful: How do I find out if the GPS of an Android device is enabled

You will need to do several things.

Firstly, to incorporate Google Maps, your complete reference is available here .

In simple steps:

1 Follow the steps here : this will help add a simple google maps to your screen.

2 To be able to get your own location you will need to use the LocationListener and LocationManager in android. To do this, first implement the LocationListener in your activity.

public class LocationActivity extends Activity implements LocationListener

3 Then you need to instantiate a few settings in your onCreate() method

     @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Get the location manager
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // Define the criteria how to select the provider
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);

    // Initialize the location fields
    if (location != null) {
      System.out.println("Provider " + provider + " has been selected.");
      onLocationChanged(location);
    } 
  }

4 You need to be able to request for regular location updates. Include this in your onResume() method.

@Override
  protected void onResume() {
    super.onResume();
    locationManager.requestLocationUpdates(provider, 400, 1, this);
  }

5 If the app falls into the pause cycle, these updates shouldn't need to come.

@Override
  protected void onPause() {
    super.onPause();
    locationManager.removeUpdates(this);
  }

6 Your location listener implementation from step 2 requires that you have an onLocationChanged listener, implement it:

@Override   
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
}

7 Add these two methods to be notified of the provider of your location setting - the GPS or the Network.

public void onProviderDisabled(String arg0) {
    Toast.makeText(this, "Disabled provider " + provider,
                Toast.LENGTH_SHORT).show();
}

public void onProviderEnabled(String arg0) {
    Toast.makeText(this, "Enabled new provider " + provider,
                Toast.LENGTH_SHORT).show();
}

8 Now we need to link this up to your google maps. I will show you one example of using the google maps API to be able to generate a market to show your current location. The other usages can be inferred from the API.

First create private fields in your code:

private GoogleMap mMap;
Marker m;

9 Add these in your onCreate method - this instantiates your default marker position as 0,0 latitude and longitude.

mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
                .getMap();
m = mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0))
                .title("Position"));

10 In your onLocationChanged method, we need to refresh this marker as location changes. So add:

m.setPosition(new LatLng(lat, lng));
m.setTitle("Your Position");

// Move the camera instantly to marker with a zoom
// of 15.
                            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 15));

This will be a simple way of updating the marker with your position, and should be a good intro to your Google Maps and location API in android.

To detect if GPS is on or not you can use the answer provided by @Dror :) Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM