Android 6.0 Unable to create directory method on SD card

  • 2021-10-11 19:29:09
  • OfStack

Summary

Today, there is a problem in the development. The project cannot create a directory in SD card of Android6.0 device. The mobile devices under Android6.0 have tested 5.0 and 4.3 devices, which are normal, but they are abnormal in Android6.0.

After troubleshooting, executing the following code cannot create a directory on the 6.0 device


File dir = new File(DbConfig.BASE_PATH);
if (!dir.exists()) {
 dir.mkdirs();
}

Derivative knowledge

On May 29th, 2015, at the Google I/O Developer Conference, Google released Android M and named it "Marshmallow" (Marshmallow). For developers, Android 6.0 (API 23) brought some changes to developers.

Rights management is the biggest change of Android M

Description of change:

Permission management is more elaborate, and from the previous static authorization at installation time to the current dynamic authorization at runtime.

Everyone has been complaining about the authority of Android for a long time, and Android should greatly improve this problem.

The main changes are:

In the system settings, each permission of APP can be controlled separately and grouped according to the content

Normal permissions are still authorized at installation time, while other permissions are authorized at runtime in the system pop-up window, and the purpose of using this permission should be resolved

For developers, permission-related issues need to be handled carefully. When using a certain function, you need to always judge whether you have permission to change it, and ask the user for authorization in an appropriate way.

Now describe the solution processed under 1

1 Permission to initiate reading and writing of device storage space


ActivityCompat.requestPermissions(AppStartActivity.this,new String[]{ android.Manifest.permission.WRITE_EXTERNAL_STORAGE},1);

2 write permission request drop back function


@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
 boolean writeAccepted = false;
 switch (requestCode) {
  case 1:
   writeAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
   break;
 }
}

3 Execute Create Directory Code


if (writeAccepted) {
  String state = Environment.getExternalStorageState();
  if (Environment.MEDIA_MOUNTED.equals(state)) {
   File dir = new File(DbConfig.BASE_PATH);
   if (!dir.exists()) {
   dir.mkdirs();
   }
  }
 }

Related articles: