简体   繁体   中英

Getting GPS location in Android

I am trying to get the current GPS-Location via Android, but it doesn't work and shows error. I have also included the runtime permission required but it still doesn't work.

MainActivity.java

public class MainActivity extends AppCompatActivity implements LocationListener {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

    }



}

@Override
public void onLocationChanged(Location location) {
    double latitude=location.getLatitude();
    double longitude=location.getLongitude();

    Log.i("Geo_location","Latitude: "+latitude+" ,Longitude: "+longitude);
}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

}

@Override
public void onProviderEnabled(String s) {

}

@Override
public void onProviderDisabled(String s) {

}

}

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.shaloin.gps">

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>


</application>

The error is: "gps" location provider requires ACCESS_FINE_LOCATION permission. for which I have added the runtime permission as stated in this link Requesting Permissions at Run Time . Please help. Thank you :)

You are not requesting run time permissions correctly.

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
        != PackageManager.PERMISSION_GRANTED
        && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
        != PackageManager.PERMISSION_GRANTED) {
    // TODO: Consider calling
    //    ActivityCompat#requestPermissions
    // here to request the missing permissions, and then overriding
    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
    //                                          int[] grantResults)
    // to handle the case where the user grants the permission. See the documentation
    // for ActivityCompat#requestPermissions for more details.
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

}

Here you are explicitly requesting a location update when the permission IS NOT granted. What you should do however in the if condition is that if the permission is not granted, request permission.

To fix this, cut the line of the locationManager.requestLocationUpdates and paste it outside of the curly brackets.

Then inside the if condition, check for the SDK version, and if it is higher than 23, request the permission.

if (Build.VERSION.SDK_INT >= 23) { // Marshmallow

            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
        }
return;

Finally you need to create a method that will override "onRequestPermissionsResult". Creating a method must be done outside of the onCreate method.

public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

    if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {

        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            // start to find location...

        } else { // if permission is not granted

            // decide what you want to do if you don't get permissions
        }
    }
}

Finally, you need to identify a unique final int variable for each permission, in order to request permissions according to variable value. This is done in the beginning of the class, where you define your instance variables.

final int LOCATION_PERMISSION_REQUEST_CODE = 1252; //Note that the value 1252 is arbitrary. 

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