如何在运行时请求位置权限
在您的代码中,您正确检查位置权限并处理没有权限的情况的确。但是,要在运行时实际请求权限,您需要使用 ActivityCompat.requestPermissions。
这是更正后的 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) }
其中 PERMISSION_REQUEST_CODE 是一个整数常量,您可以定义以轻松引用权限请求。
附加注意事项
<manifest ...> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> </manifest>
以上是如何在Android中请求运行时位置权限?的详细内容。更多信息请关注PHP中文网其他相关文章!