EDIT2:適用人羣對面谷歌這個問題的絆腳石。 canWrite()
功能有點兒錯誤,似乎不能正常工作。我會建議不要使用它。只是catch
和例外。另外請確保您的手機不在USB Storage
模式下,以便您可以寫入SD卡。最後確保Android設備中的設置沒有寫保護或類似的東西。無法寫入SD卡Android手機上
我似乎有試圖寫我的SD卡我的Android手機上的問題。如果我使用Eclipse進行調試模式或自行運行手機,則無關緊要。我無法寫入SD卡。是,配置權限,如下所示。當使用Android網站上提供的代碼片段時,我將在完成該段後爲兩個布爾值賦予false。我完全不知道爲什麼存儲不可用或不可寫。我從我的Mac彈出SD卡和手機,以確保他們沒有使用它,並且手機可以掛載,但就像我說的,當我不使用Eclipse時,我遇到了同樣的問題。
編輯:使用真正的Android手機將根據有關信息運行4.04。
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
清單:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tinywebteam.gpstracker"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.tinywebteam.gpstracker.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
試圖執行以下mkdirs()
何時拋出異常指定它未能:
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/GPStracker/data/");
if (!dir.exists()) {
if (!dir.mkdirs())
throw new FileNotFoundException("Couldn't make directory.");
}
File fileOut = new File(dir, "GPSTracker_" + ts + ".csv");
if (fileOut.canWrite()) {
FileOutputStream out = new FileOutputStream(fileOut);
out.write(fileStr.getBytes());
out.close();
System.out.println("File written successfully");
} else {
System.out.println("Could not write to file");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
您使用的是真實設備還是仿真器?什麼是'sdCard.getAbsolutePath()'返回? – 2013-04-04 19:43:27
使用真正的Android手機 – MasterGberry 2013-04-04 19:43:43
您的手機是否有外置SD卡?並非所有的事情 - 例如Nexus系列都沒有。 – 2013-04-04 19:45:03