Android as - processing of obtaining read and write permissions for different targetsdk versions

Chun Jie 2022-05-14 15:03:11 阅读数:616


Android as

As the title , Trying to use only native Android as When the compiler implements the voice recording function , It's directly used when it was packed to unity jar The code of the package , And then I found the package app Unable to realize the function of voice recording , An error is reported. There is no permission to read and write files

So Baidu took a look , It is found that different Android versions packaged will deal with the read and write permissions of files differently
stay 29 Before , It can be used directly environment.getExternalStorageDirectory().getAbsolutePath() This method to get the file path
however 29 Not anymore . First, in the configuration file AndroidManifest.xml Add in

Then you have to apply for permission dynamically ( I won't talk about this if I mentioned it earlier )

/** * android 6.0 The above needs dynamic application authority */
public void initPermission(Context context) {

String permissions[] = {
PackageManager pm = getActivityByContext(context).getPackageManager();
boolean permission_readStorage = (PackageManager.PERMISSION_GRANTED ==
pm.checkPermission("android.permission.RECORD_AUDIO", "com.DefaultCompany.vad"));
boolean permission_network_state = (PackageManager.PERMISSION_GRANTED ==
pm.checkPermission("android.permission.ACCESS_NETWORK_STATE", "com.DefaultCompany.vad"));
boolean permission_internet = (PackageManager.PERMISSION_GRANTED ==
pm.checkPermission("android.permission.INTERNET", "com.DefaultCompany.vad"));
boolean permission_writeStorage = (PackageManager.PERMISSION_GRANTED ==
pm.checkPermission("android.permission.WRITE_EXTERNAL_STORAGE", "com.DefaultCompany.vad"));
if (!(permission_readStorage && permission_writeStorage && permission_network_state && permission_internet)) {


getActivityByContext(context).requestPermissions(permissions, 0x01);
public class GetActivity {

public static Activity getActivityByContext(Context context){

while(context instanceof ContextWrapper){

if(context instanceof Activity){

return (Activity) context;
context = ((ContextWrapper) context).getBaseContext();
return null;

Then the function to get the file path also changes
To get context, Get the file path through this class
Then the package will not report an error

Here's why it was packed to unity He didn't report a mistake at the time of , Obviously because through unity The packaged version of Android is lower than 29, So you can use it directly environment… The function to get the file path , But it's native here app The Android version set in is higher than 29 Of , So it needs special treatment ~

版权声明:本文为[Chun Jie]所创,转载请带上原文链接,感谢。