gpt4 book ai didi

android - 允许在SD卡android上写入

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:01:07 26 4
gpt4 key购买 nike

我在写入 SD 卡时遇到问题,代码如下:(抱歉代码的布局,只是复制过去了)

public class SaveAndReadManager {

private String result;
private String saveFileName = "eventlist_savefile";

public String writeToFile( ArrayList<Event> arrlEvents ){
FileOutputStream fos = null;
ObjectOutputStream out = null;

try{
File root = Environment.getExternalStorageDirectory();

if( root.canWrite() ){
fos = new FileOutputStream( saveFileName );
out = new ObjectOutputStream( fos );
out.writeObject( arrlEvents );

result = "File written";

out.close();
}else{
result = "file cant write";
}
}catch( IOException e ){
e.printStackTrace();
result = "file not written";
}

return result;
}

public boolean readFromFile(){
return false;
}
}

我还没有实现 readFromFile()。问题是 root.canWrite() 一直返回 false。这是 list 文件:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".InfoScreen"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

    <activity android:name=".EventCalendar"
android:label="@string/app_name" />

<activity android:name=".MakeEvent"
android:label="@string/app_name" />

<activity android:name=".ViewEvent"
android:label="@string/app_name" />

</application>
<uses-sdk android:minSdkVersion="8" />

我已经请求写入权限,在我的 avd 上,如果我转到设置 -> SD 卡和手机存储,它会告诉我 SD 卡上有 1 GB 的空间可以写入。请帮忙。

谢谢:)

最佳答案

尝试写入之前先检查 SD 卡的状态。它可能用作共享驱动器、已损坏、已满等。可在此处找到状态列表:http://developer.android.com/reference/android/os/Environment.html

这是获取状态的示例:

String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
mExternalStorageAvailable = mExternalStorageWriteable = false;
}

关于android - 允许在SD卡android上写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3925813/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com