You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Kotlin应用升级Target SDK31后在Android12/13真机启动崩溃求助

Fixing Android 12/13 Real Device Crash After Target SDK 31 Upgrade

Hey there, let's break down why your app is crashing on Android 12/13 real devices (but working on emulators and older OS versions) and how to fix it. Your suspicion about the deprecated NetworkInfo API is a solid starting point, but there are a few other Target SDK 31 behavior changes that could be causing this too.

1. Replace Deprecated NetworkInfo API (Critical First Step)

Starting with API 31, ConnectivityManager.getNetworkInfo() and related NetworkInfo methods are fully removed (not just deprecated). While emulators or older devices might tolerate calls to these methods, real Android 12/13 devices will throw a NoSuchMethodError or crash immediately.

Here's a Kotlin replacement to check network connectivity properly for API 21+:

import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build

fun isNetworkAvailable(context: Context): Boolean {
    val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        val network = connectivityManager.activeNetwork ?: return false
        val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return false
        
        return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
               capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
    } else {
        // Fallback for older devices (pre-M)
        val networkInfo = connectivityManager.activeNetworkInfo
        return networkInfo != null && networkInfo.isConnected
    }
}

Make sure you replace all instances of NetworkInfo usage in your code with this (or similar) logic.

2. Fix Target SDK 31 Behavior Changes (Common Crash Triggers)

Even if you fix NetworkInfo, these Android 12+ requirements can still cause crashes:

a. Explicitly Set android:exported for Components

Android 12+ requires all components that can be launched externally (like your main Activity, BroadcastReceivers, Services) to have an explicit android:exported attribute in your AndroidManifest.xml.

For example, your main Activity should look like this:

<activity
    android:name=".MainActivity"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

Check all components in your manifest—especially any Firebase Messaging receivers or custom services—and add android:exported="true" or false depending on whether they need to be accessible outside your app.

b. Fix PendingIntent Flags

Android 12+ mandates that all PendingIntent instances must specify either FLAG_IMMUTABLE or FLAG_MUTABLE. If you're using PendingIntent anywhere (e.g., for notifications, WorkManager tasks, or deep links), update the code to include one of these flags.

Example for a notification PendingIntent:

val pendingIntent = PendingIntent.getActivity(
    context,
    0,
    intent,
    PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)

Use FLAG_MUTABLE only if you need to modify the PendingIntent later—otherwise, stick with FLAG_IMMUTABLE for security.

c. Handle Foreground Service Permissions (If Applicable)

If your app uses foreground services, Android 12+ requires:

  • Adding android.permission.FOREGROUND_SERVICE to your manifest.
  • For Android 13+, requesting the POST_NOTIFICATIONS permission dynamically (since foreground services require a notification).

3. Check Crash Logs for Exact Cause

The most reliable way to pinpoint the crash is to look at the Logcat output from the real device. Filter for FATAL EXCEPTION—this will show you the exact error message (e.g., IllegalArgumentException about PendingIntent flags, or NoSuchMethodError for NetworkInfo).

If you haven't already, connect your real device to Android Studio, run the app, and check Logcat when it crashes. This will eliminate guesswork and let you focus on the root issue.

4. Clean Up Dependencies & Build Config

Your build.gradle has a few minor issues that could cause unexpected behavior:

  • Remove duplicate com.android.application plugin declarations (you have both id 'com.android.application' and apply plugin: 'com.android.application'—keep only the first one).
  • Merge the two defaultConfig blocks into one to avoid conflicting settings.
  • Upgrade outdated dependencies (e.g., Glide to 4.15.1, Material Components to 1.9.0, RecyclerView to 1.3.2) to versions that support Android 12+.

Final Steps

  1. Replace all NetworkInfo usage with the modern connectivity check.
  2. Update your manifest to add android:exported to all required components.
  3. Fix any PendingIntent instances to include the correct flags.
  4. Check Logcat for any remaining crash errors.
  5. Clean and rebuild your project, then test on real Android 12/13 devices.

内容的提问来源于stack exchange,提问作者Hary Hillary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 17:50:23