为什么listOfFiles为null?
Android说,那listOfFiles如果为null,那么我做错了什么? 我试图改变getPath getAboletePath,但它是一样的。 而且,我试图访问/存储/(而SD_PATH是/存储/模拟/ 0),我有一个2个文件夹的列表:模拟和自我,这两个都是无法访问。为什么listOfFiles为null?
public class MainActivity extends AppCompatActivity {
private static final String SD_PATH = Environment.getExternalStorageDirectory().getPath();
...
File home = new File(SD_PATH);
File[] listOfFiles = home.listFiles();
if(listOfFiles != null && listOfFiles.length > 0){
for (File file : home.listFiles()){
songs.add(file.getName());
}
}
这里是我的AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.unimusic">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
这同样的事情已经烧到了我的过去。
引述文档
在在Android 6.0(API级别23)开始,用户授予权限的应用程序应用程序运行时,而不是当他们安装应用程序。
(见here)
从文件系统读取的是,现在必须在运行时才能使用请求的权限之一。如果您的目标是SDK 23或更高版本,这只是一个问题。所以如何解决:
该文档显示了一个示例(请参阅原始的here),我修改了您的用例(我没有运行此代码,但它应该是一个很好的起点)。您可能想要为onCreate()
请求需要权限的活动(在您的案例中为MainActivity
)。
// Ask for the read external storage permission
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE))
{
// Provide an additional rationale to the user if the permission was not granted
// and the user would benefit from additional context for the use of the permission.
// Display a SnackBar with a button to request the missing permission.
Snackbar.make(layout,
"External storage is needed in order to {YOUR EXPLANATION HERE}",
Snackbar.LENGTH_INDEFINITE).setAction("OK", new View.OnClickListener()
{
@Override
public void onClick(View view)
{
// Request the permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
}).show();
}
else
{
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
}
它的工作,但现在我有requestPermissions一个新的错误。应用程序只是崩溃与一个错误包安装程序崩溃(像这样的smth,有一些翻译错误,因为我使用的是俄语) –
好吧,谢谢,我的错。我认为如果我要求权限,它不需要预先添加到AndroidManifest.xml中:D –
您定位的是哪个版本的API? – curob
minSdk是15,目标sdk是23 –
尝试将目标SDK更改为22.如果这有效,那么我会写一个描述为什么以及如何解决它的答案。 – curob