Android应用如何申请权限且不触发异常?
Hey there! Let’s tackle this problem step by step—no more random crash pop-ups, just a smooth permission request that leads users straight to your app’s main screen.
First, let’s nail down why that crash is happening: almost certainly, your app is trying to access a feature that requires permission before the user has granted it. For example, if you’re initializing a camera or location service in onCreate() without checking permissions first, Android will throw a SecurityException, which triggers that crash dialog.
Here’s how to fix this and get the clean flow you want:
1. First, Identify the Exact Crash (Critical Step!)
Before diving into code, open Android Studio’s Logcat tab when the crash happens. Look for red error messages—they’ll tell you exactly what’s causing the crash (e.g., java.lang.SecurityException: Permission denied for a specific permission). This confirms which permission you need to handle properly.
2. Declare Permissions in AndroidManifest.xml
Make sure you’ve added all required permissions to your AndroidManifest.xml (this is mandatory, even for runtime permissions):
<!-- Example for camera permission --> <uses-permission android:name="android.permission.CAMERA" /> <!-- Example for location permission --> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
3. Use Android’s Modern Permission Request API
Google recommends using ActivityResultContracts for permission requests (it replaces the old onRequestPermissionsResult() method, which is deprecated). Here’s a complete implementation:
Step 3.1: Set Up the Permission Launcher
In your startup Activity (e.g., SplashActivity or MainActivity), initialize a permission launcher in onCreate():
// For single permission request private val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { isGranted: Boolean -> if (isGranted) { // Permission granted—navigate to your main Activity startActivity(Intent(this, YourMainActivity::class.java)) finish() // Close the startup Activity so users can't go back to it } else { // Permission denied—you can show a dialog explaining why you need it, // or redirect users to app settings to enable it showPermissionDeniedDialog() } } // For multiple permissions (if you need more than one) private val requestMultiplePermissionsLauncher = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions() ) { permissions -> // Check if all required permissions are granted val allGranted = permissions.values.all { it } if (allGranted) { startActivity(Intent(this, YourMainActivity::class.java)) finish() } else { showPermissionDeniedDialog() } }
Step 3.2: Check Permissions Before Requesting
In onCreate() (or onResume()), first check if the permission is already granted. If not, launch the permission request—don’t access any restricted features until this is done:
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) val requiredPermission = Manifest.permission.CAMERA // Replace with your permission if (ContextCompat.checkSelfPermission( this, requiredPermission ) == PackageManager.PERMISSION_GRANTED ) { // Permission already granted—go straight to main Activity startActivity(Intent(this, YourMainActivity::class.java)) finish() } else { // Permission not granted—show the system permission request dialog requestPermissionLauncher.launch(requiredPermission) } }
4. Avoid Initializing Restricted Features Too Early
Make sure you don’t initialize any components that require permission (like a camera preview, location manager, or file reader) until after the permission is granted. For example, move your camera setup code from onCreate() to the callback where you confirm permission is granted.
5. Handle Permission Denial Gracefully
If the user denies the permission, don’t crash—show a friendly dialog explaining why the permission is needed, and give them an option to open your app’s settings to enable it later:
private fun showPermissionDeniedDialog() { AlertDialog.Builder(this) .setTitle("Permission Required") .setMessage("This app needs camera access to take photos. Please enable it in settings.") .setPositiveButton("Go to Settings") { _, _ -> // Redirect to app settings val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) val uri = Uri.fromParts("package", packageName, null) intent.data = uri startActivity(intent) finish() } .setNegativeButton("Cancel") { dialog, _ -> dialog.dismiss() // Optionally close the app if the permission is critical finish() } .show() }
By following these steps, your app will:
- Check for permissions on startup
- Only show the system permission request dialog (no crash pop-ups)
- Navigate to your main Activity only after permissions are granted
- Handle denial gracefully without crashing
内容的提问来源于stack exchange,提问作者Hatay Berkay Işıkoğlu

