android各版本的兼容问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31433525/article/details/82889293

自动安装

在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){
       ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, 1000);
 	}

开启服务

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()错误

猜你喜欢

转载自blog.csdn.net/qq_31433525/article/details/82889293