How to Request Location Permission at Runtime
In your code, you correctly check for the location permissions and handle the case where permissions are not granted. However, to actually request the permissions at runtime, you need to use ActivityCompat.requestPermissions.
Here's your corrected MainActivity:
public class MainActivity extends AppCompatActivity implements LocationListener { // ... (rest of your code) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_CODE); } else { // Permissions already granted // ... } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == PERMISSION_REQUEST_CODE) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) { // Permissions granted // ... } else { // Permissions denied // ... } } } // ... (rest of your code) }
Where PERMISSION_REQUEST_CODE is an integer constant you can define to easily reference the permission request.
Additional Considerations
<manifest ...> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> </manifest>
The above is the detailed content of How to Request Runtime Location Permissions in Android?. For more information, please follow other related articles on the PHP Chinese website!