Android版本适配

387 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第19天,点击查看活动详情

Android 12

Splash Screen

Android12新增了系统默认的App启动页,如果我们没有进行适配,SplashScreen就会使用主题的windowBackground和启动器图标。如果原本使用android:windowBackground 实现了启动页,那么就会被默认的启动页样式替换。

新的启动页中的显示元素可完全由开发者自定义:

<style name="Theme.SplashScreen.Test" parent="Theme.SplashScreen">
    <item name="windowSplashScreenBackground">#FFFFFF</item>
    <item name="windowSplashScreenAnimatedIcon">@drawable/splash_anim_icon</item>
    <item name="windowSplashScreenIconBackgroundColor">#FFF</item>
    <item name="windowSplashScreenAnimationDuration">1000</item>
    <item name="android:windowSplashScreenBrandingImage">@drawable/brand_img</item>
    <item name="postSplashScreenTheme">@style/Theme.Android12_Splash</item>
</style>
  • windowSplashScreenBackground 指定启动画面背景颜色。
  • windowSplashScreenAnimatedIcon 指定启动画面icon图标,可以是图片、帧动画等。
  • windowSplashScreenAnimationDuration 指定icon动画在关闭之前显示的时长,最长时间为1000毫秒。
  • windowSplashScreenBrandingImage 指定启动画面底部的 Brand 图片
  • postSplashScreenTheme 指定Splash退出后的主题

然后将该主题应用到启动页Activity。

<activity
    android:name=".SplashActivity"
    android:theme="@style/Theme.SplashScreen.Test">
    //.....
</activity>

在启动页Activity中初始化SplashScreen,必须放在setContentView()方法之前。

class SplashActivity : BaseActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val mSplashScreen = installSplashScreen()
        setContentView(R.layout.activity_splash)
    }
}

android:exported

android:exported属性是设置Activity是否可由其他应用的组件启动,若为false,则只能由同一应用的组件或使用同一用户ID的不同应用启动。

Android12的平台上,如果 Activity 、 Service 或 Receiver 使用 intent-filter ,并且未显式声明 android:exported 的值,App 将会无法安装。

位置信息

在Android12(TargetSDK=31)上,如果应用请求ACCESS_FINE_LOCATION权限,还必须请求ACCESS_COARSE_LOCATION权限,如果仅请求 ACCESS_FINE_LOCATION,则系统会忽略该请求。

PendingIntent 的可变性

在 Android 12 中创建 PendingIntent 的时候,需要显示的声明是否可变,需要设置PendingIntent.FLAG_MUTABLE 或 PendingIntent.FLAG_IMMUTABLE 标志,如果在没有使用这两个标志创建PendingIntent对象,系统会抛出参数非法异常。

PendingIntent pendingIntent = PendingIntent.getActivity(context, REQUEST_CODE, intent, PendingIntent.FLAG_IMMUTABLE);

MAC 地址

Android 12 进一步限制了所有非系统应用对设备的 MAC 地址的访问。普通APP获取到的要么是空值,要么是无意义的占位值。