最近自己写插件时,总是发现packageManager.getPackageArchiveInfo 返回为null,但是自己权限都打开,加载路径也是正确的,到底是为什么呢?

packageInfo =packageManager.getPackageArchiveInfo(path,
                    PackageManager.GET_ACTIVITIES );

原来path写法有问题,之前的写法:

路径为:/storage/emulated/0/DCIM/plugin-debug.apk

Environment.getExternalStorageDirectory()+"/DCIM/plugin-debug.apk"

可是上面的写法在Android9.0 之后就废弃了(为了提高用户隐私,不建议直接访问共享/外部存储设备),并且不再返回可访问的文件。

那怎么写呢,官方推荐使用:

getExternalFilesDir(null).getPath()+"/plugin-debug.apk";

修改之后,返回值就不为null了。

路径为:/storage/emulated/0/Android/data/com.example.insert/files/plugin-debug.apk

getExternalFilesDir()内部参数

  1. 该方法用于获得外部存储,地址为/storage/emulated/0/Android/data/packageName/files
  2. 该方法可传一个String类型的参数,用于在父路径下创建子文件夹,没有该文件夹会自动创建
  3. 使用方法:
    String path=context.getExternalFilesDir(null).getAbsolutePath();
    File file=new File(path);
    //输出:path:/storage/emulated/0/Android/data/packageName/files
    
    String path2=context.getExternalFilesDir("UniApp").getAbsolutePath();
    File file2=new File(path2);
    //path:/storage/emulated/0/Android/data/packageName/files/UniApp
    //如uniapp文件夹没有,则会自动创建
    
    String path3=context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
    File file3=new File(path3);
    //path:/storage/emulated/0/Android/data/packageName/files/Download
    
    
    String path4=context.getExternalFilesDir("").getAbsolutePath()+"/hhhhhh";
    File file4=new File(path4);
    //path:storage/emulated/0/Android/data/packageName/files/hhhhhh
    //如果没有“hhhhhh”文件夹,则file4.exists()==false;
    

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐