我想在我的应用程序中显示内部存储的所有视频文件名称。
Environment.getExternalStorageDirectory:我试过这个。 另外首先我检查ExternalStorageState是否为null。
我的设备没有任何SD卡存在。那么如何处理? P.S我正在使用Moto G(第2版)设备。
我试过了: -
How to display files in listView?
How to get android device with Internal Downloader folder path
答案 0 :(得分:0)
这是我可以访问内部存储文件的尝试。
https://developer.android.com/training/permissions/requesting.html
从上面的链接中我获得了有关使用权限的重要信息 api level> 23所以存在权限问题,因为我无法访问内部存储目录。
最终代码: -
public class MainActivity extends Activity {
ListView lv;
private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.list);
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
} else {
ArrayList<String> filesinfolder = GetFiles("/sdcard/");
ArrayAdapter<String> adapter
= new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
filesinfolder);
lv.setAdapter(adapter);
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
ArrayList<String> filesinfolder = GetFiles("/sdcard/");
ArrayAdapter<String> adapter
= new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
filesinfolder);
lv.setAdapter(adapter);
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
public ArrayList<String> GetFiles(String directorypath) {
ArrayList<String> Myfiles = new ArrayList<String>();
File f = new File(directorypath);
f.mkdirs();
File[] files = f.listFiles();
if (files.length == 0) {
return null;
} else {
for (int i = 0; i < files.length; i++)
Myfiles.add(files[i].getName());
}
return Myfiles;
}
}