安卓系统:下载到SD时出现问题



我开发了一个应用程序,用户可以在其中从服务器下载.mp3文件。并预定义了一个mnt/sdcard/foldername路径,用于保存此类文件。我曾在HTC、LG运行过我的程序,三星运行得很完美,但当我在三星galaxy s2运行同一程序时,遇到了无法在mnt/sdcard/foldername中写入(存储)的问题,并尝试了

 Environment.getExternalStorageDirectory().getAbsolutePath()

但它显示给定路径中的下载文件名,每个文件属性为零字节。有解决这个问题的办法吗?

SG2通常没有sd卡,而是使用内部闪存作为"外部"存储。我用这个代码解决了这个问题:

    private File initCacheDir() {
        String sdState = android.os.Environment.getExternalStorageState();
            File imageCacheDir;
            if (sdState.equals(android.os.Environment.MEDIA_MOUNTED)) {
                File sdDir = android.os.Environment.getExternalStorageDirectory();      
                imageCacheDir = new File(sdDir, "Android/data/" + App.PACKAGE_NAME + "/files/imageCache");
            }
            else
                imageCacheDir = context.getCacheDir();
            if(!imageCacheDir.exists())
                 imageCacheDir.mkdirs();        
            return imageCacheDir;
}

请注意,这段代码为您提供了缓存目录的位置,该目录通常位于sd卡上的Android/data文件夹中。

您可以在此处找到如何使用SG2解决此问题的更多详细信息:如何在三星和所有其他设备上获得正确的外部存储?

尝试这个

 if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
        cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"yourfile");
    else
        cacheDir=context.getCacheDir();
    if(!cacheDir.exists())
        cacheDir.mkdirs();

我终于找到了代码

public void download(String urlToDownload){
URLConnection urlConnection = null;
try{
    URL url = new URL(urlToDownload);
    //Opening connection of currrent url
    urlConnection = url.openConnection();
    urlConnection.connect();
    //int lenghtOfFile = urlConnection.getContentLength();

String PATH = Environment.getExternalStorageDirectory() + "/1/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "file.mp3");
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = url.openStream();

byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
    fos.write(buffer, 0, len1);
}
fos.close();
is.close();
System.out.println("downloaded"+urlToDownload);
}catch (Exception e) {
    // TODO: handle exception
    e.printStackTrace();
}
}

来源:链接

最新更新