I try to get files from external storage by this program:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.textView);
StringBuilder builder = new StringBuilder();
File specFile = Environment.getExternalStorageDirectory();
builder.append(Environment.getExternalStorageState() + "\n");
if (specFile.exists()) {
builder.append(specFile);
if (specFile.list() != null) {
String[] files = specFile.list();
for (int i = 0; i < files.length; i++) {
builder.append(files[i] +"\n");
}
} else {
builder.append(" exist but empty\n");
}
}
builder.append("/storage/emulated/0/Android exist: " + new File("/storage/emulated/0/Android").exists());
textView.setText(builder);
}
}
This permissions was added:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
It works good in emulator, but in the real phone it returns null when I try to get list. It also can normally find dirs in storage.
Problem resolved by adding this code:
int requestCode = 0;
if (Build.VERSION.SDK_INT >= 23) {
if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, requestCode);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.