欢迎访问移动开发之家(rcyd.net),关注移动开发教程。移动开发之家  移动开发问答|  每日更新
页面位置 : > > > 内容正文

Android不同版本兼容性适配方法教程,

来源: 开发者 投稿于  被查看 5279 次 评论:22

Android不同版本兼容性适配方法教程,


目录
  • Android 6
  • Android 7
  • Android 8
  • Android 9
  • Android 10
    • 定位权限
    • 分区存储
  • Android 11
    • 强制执行分区存储
    • 位置权限

Android 6

运行时权限动态申请,这里推荐郭霖的开源库:https://github.com/guolindev/PermissionX

Android 7

在Android 7.0系统上,禁止向你的应用外公开 file:// URI,如果一项包含文件 file:// URI类型的Intent离开你的应用,应用失败,并出现 FileUriExposedException异常,如调用系统相机拍照。若要在应用间共享文件,可以发送 content:// URI类型的Uri,并授予URI 临时访问权限,使用FileProvider类。

使用FileProvider的大致步骤如下:

1.在res下创建xml目录,在此目录下创建file_paths.xml文件,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <!-- 内部存储,等同于Context.getFilesDir,路径:/data/data/包名/files目录-->
    <files-path
        name="DocDir"
        path="/" />
    <!-- 内部存储,等同于Context.getCacheDir,路径:/data/data/包名/cache目录-->
    <cache-path
        name="CacheDocDir"
        path="/" />
    <!--外部存储,等同于Context.getExternalFilesDir,路径:/storage/sdcard/Android/data/包名/files-->
    <external-files-path
        name="ExtDocDir"
        path="/" />
    <!--外部存储,等同于Context.getExternalCacheDir 路径:/storage/sdcard/Android/data/包名/cache-->
    <external-cache-path
        name="ExtCacheDir"
        path="/" />
</paths>

2.在manifest中注册provider

        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.unclexing.exploreapp.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <!--exported:要为false,为true则会报安全异常。grantUriPermissions为true,表示授予URI临时访问权限-->
            <meta-data
                android:name="androidx.core.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>

3.使用FileProvider

            val file = File(
                getExternalFilesDir(null),
                "/temp/" + System.currentTimeMillis() + ".jpg"
            )
            if (!file.parentFile.exists()) {
                file.parentFile.mkdirs()
            }
            //通过FileProvider创建一个content类型的Uri
            val imageUri = FileProvider.getUriForFile(
                this,
                "com.unclexing.exploreapp.fileprovider", file
            )
            val intent = Intent()
            //表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.action = MediaStore.ACTION_IMAGE_CAPTURE
            //将拍摄的照片保存到特定的URI
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
            startActivity(intent)

Android 8

Android 8.0 引入了通知渠道,允许为要显示的每种通知类型创建用户可自定义的渠道,用户界面将通知渠道称之为通知类别。

    private fun createNotification() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            //如果要分组,groupId要唯一
            val groupId = "group1"
            val group = NotificationChannelGroup(groupId, "advertisement")
            notificationManager.createNotificationChannelGroup(group)
            //channelId唯一
            val channelId = "channel1"
            val notificationChannel = NotificationChannel(
                channelId,
                "promote information",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            //将渠道添加进组,必须先创建组才能添加
            notificationChannel.group = groupId
            notificationManager.createNotificationChannel(notificationChannel)
            //创建通知
            val notification = Notification.Builder(this, channelId)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher))
                .setContentTitle("A new notice")
                .setContentText("Likes and follows")
                .setAutoCancel(true)
                .build()
            notificationManager.notify(1, notification)
        }
    }

Android 8.0以后不允许后台应用启动后台服务,需要通过startForegroundService()指定为前台服务,应用有五秒的时间来调用该 Service 的 startForeground() 方法以显示可见通知。 如果应用在此时间限制内未调用startForeground(),则系统将停止 Service 并声明此应用为 ANR。

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val intent = Intent(this, UncleService::class.java)
                startForegroundService(intent)
            }
class UncleService : Service() {
    override fun onCreate() {
        super.onCreate()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            val channel =
                NotificationChannel("channelId", "channelName", NotificationManager.IMPORTANCE_HIGH)
            manager.createNotificationChannel(channel)
            val notification = Notification.Builder(this, "channelId")
                .build()
            startForeground(1, notification)
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        stopForeground(true)
    }
    override fun onBind(p0: Intent?): IBinder? {
        return null
    }
}

别忘了在manifest添加权限

<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

Android 9

在Android 9中的网络请求中,不允许使用http请求,要求使用https。

解决方案:

在 res 下新建一个xml目录,然后创建一个名为:network_config.xml 文件

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

然后在Mainfiests appliction标签下配置该属性

android:networkSecurityConfig="@xml/network_config"

这是一种简单粗暴的方法,为了安全灵活,我们可以指定http域名,部分域名时使用http

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">csdn.example.com</domain>
    </domain-config>
</network-security-config>

Android 10

定位权限

用户可以更好地控制应用何时可以访问设备位置,当在Android 10上运行的应用程序请求位置访问时,会通过对话框的形式给用户进行授权提示,此时有两种位置访问权限:在使用中(仅限前台)或始终(前台和后台)

新增权限 ACCESS_BACKGROUND_LOCATION

如果你的应用针对 Android 10并且需要在后台运行时访问用户的位置,则必须在应用的清单文件中声明新权限

  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

分区存储

在Android 10之前的版本上,我们在做文件的操作时都会申请存储空间的读写权限。但是这些权限完全被滥用,造成的问题就是手机的存储空间中充斥着大量不明作用的文件,并且应用卸载后它也没有删除掉。为了解决这个问题,Android 10 中引入了分区存储的概念,通过添加外部存储访问限制来实现更好的文件管理。但是应用得不彻底,因为我们可以在AndroidManifest.xml中添加android:requestLegacyExternalStorage="true"来请求使用旧的存储模式,以此来做简单粗暴地适配。但是我不推荐这样做,因为Android 11强制执行分区存储机制,此配置已经将会失效,所以还得老老实实地做下适配,直接看下面Android 11的适配吧。

Android 11

无需存储权限即可访问的有两种,一是App自身的内部存储,一是App自身的自带外部存储。

对于存储作用域访问的区别就体现在如何访问除此之外的目录内的文件。

强制执行分区存储

共享存储空间存放的是图片、视频、音频等文件,这些资源是公用的,所有App都能够访问它们。共享存储空间里存放着图片、视频、音频、下载的文件,App获取或者插入文件的时候怎么区分这些类型呢?这个时候就需要MediaStore。比如想要查询共享存储空间里的图片文件:

        val cursor = contentResolver.query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            null,
            null,
            null,
            null
        )

MediaStore.Images.Media.EXTERNAL_CONTENT_URI 意思是指定查询文件的类型是图片,并构造成Uri对象,Uri实现了Parcelable,能够在进程间传递。

既然不能通过路径直接访问文件,那么如何通过Uri访问文件呢?Uri可以通过MediaStore或SAF获取。但是,需要注意的是:虽然也可以通过文件路径直接构造Uri,但是此种方式构造的Uri是没有权限访问文件的。

现在我们来读取/sdcard/目录下的一个文本文件NewTextFile.txt,由于它不属于共享存储空间的文件,是属于其它目录的,因此不能通过MediaStore获取,只能通过SAF获取。

    private fun openSAF() {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        //指定选择文本类型的文件
        intent.type = "text/plain"
        startActivityForResult(intent, 1)
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1 && data != null) {
            val uri = data.data
            startRead(uri!!)
        }
    }
    private fun startRead(uri: Uri) {
        try {
            val inputStream = contentResolver.openInputStream(uri)
            val readContent = ByteArray(1024)
            var len: Int
            do {
                len = inputStream!!.read(readContent)
                if (len != -1) {
                    Log.d(tag, "file content:${String(readContent).substring(0, len)}")
                }
            } while (len != -1)
        } catch (e: Exception) {
            Log.d(tag, "Exception:${e.message}")
        }
    }

由此可以看出,属于"其它目录"下的文件,需要通过SAF访问,SAF返回Uri,通过Uri构造InputStream即可读取文件。

下面,我们再来写入内容到该文件中,还是需要通过SAF拿到Uri,拿到Uri后构造输出流。

    private fun writeForUri(uri: Uri) {
        try {
            val outputStream = contentResolver.openOutputStream(uri)
            val content = "my name is Uncle Xing"
            outputStream?.write(content.toByteArray())
            outputStream?.flush()
            outputStream?.close()
        } catch (e: Exception) {
            Log.d(tag, "Exception:${e.message}")
        }
    }

SAF好处是:系统提供了文件选择器,调用者只需指定要读写的文件类型,比如文本类型、图片类型、视频类型等,选择器就会过滤出相应文件以供选择,使用简单。

位置权限

Android 10请求ACCESS_FINE_LOCATION或 ACCESS_COARSE_LOCATION表示在前台时拥有访问设备位置信息的权限。在请求弹框还能看到始终允许,Android 11中,取消了始终允许选项,默认不会授予后台访问设备位置信息的权限。Android 11将后台获取设备位置信息抽离了出来,通过ACCESS_BACKGROUND_LOCATION权限后台访问设备位置信息的权限,需要注意的一点是,请求ACCESS_BACKGROUND_LOCATION的同时不能请求其它权限,否则系统会抛出异常。官方给出的建议是先请求前台位置信息访问权限,再请求后台位置信息访问权限。

到此这篇关于Android不同版本兼容性适配方法教程的文章就介绍到这了,更多相关Android兼容性适配内容请搜索3672js教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持3672js教程!

您可能感兴趣的文章:
  • Android高版本API方法如何在低版本系统上做兼容性处理浅析
  • Android 兼容性问题:java.lang.UnsupportedOperationException解决办法
  • Android中转场动画的实现与兼容性处理
  • Android 高版本API方法在低版本系统上的兼容性处理
  • Android应用的Material设计的布局兼容性的一些要点总结

用户评论