android各版本的兼容问题

本文主要讨论了在Android 7.0和8.0版本中关于自动安装的改动以及开启服务的新规定。在Android 7.0的自动安装上有所调整,而Android 8.0不仅增加了权限需求,还要求使用startForegroundService()代替startService()来开启前台服务,以避免电量优化导致的影响。同时,8.0版本中不正确使用startForegroundService()会引发错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自动安装

在Android7.0自动安装做出了修改,android8.0增加了权限

//以前
 Intent intent = new Intent();
 intent.setAction(Intent.ACTION_VIEW);
 intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
 startActivity(intent);
 
//android 7.0需要用到共享文件provider的方式,不能识别file://需要将其转为uri
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri contentUri = FileProvider.getUriForFile(context, "com.zjhc.jxzq.jxzq.fileprovider", file);
 intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
 startActivity(intent);
 
//AndroidManifist.xml中配置
<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.zjhc.jxzq.jxzq.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
   <meta-data
         android:name="android.support.FILE_PROVIDER_PATHS"
         android:resource="@xml/file_paths" />
 </provider>

//res下新建xml目录,新建file_paths.xml文件
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path path="apk" name="app-release"/>
</paths>
注意:保存路径需要新建apk目录,Environment.getExternalStorageDirectory()对应external-path

//android8.0需要写入权限
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
//权限校验
  boolean b =getPackageManager().canRequestPackageInstalls();
  if(!b){
       Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + getPackageName()));
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
 	}
 	
 	

开启服务

android 8.0开启前台服务,正对startService()更改成使用startForegroundService()。
现场保活时,系统对电量进行了进一步的优化,如果不考虑点亮可以尝试将应用加入电量优化的白名单

  if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.O){
            PowerManager powerManager = (PowerManager) activity.getSystemService(POWER_SERVICE);
            boolean hasIgnored = powerManager.isIgnoringBatteryOptimizations(activity.getPackageName());
            //  判断当前APP是否有加入电池优化的白名单,如果没有,弹出加入电池优化的白名单的设置对话框。
            if (!hasIgnored) {
                Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                intent.setData(Uri.parse("package:" + activity.getPackageName()));
                activity.startActivity(intent);
            }
        }

8.0使用startForegroundService需要配一个Notification,不然报Context.startForegroundService() did not then call Service.startForeground()错误

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值