开发者

Android: save file to sdcard?

开发者 https://www.devze.com 2023-01-29 14:11 出处:网络
I am attempting to create a program that saves an mp3 to the Android, which can be accessed by ASTRO. I am开发者_高级运维 attempting to save the file to /sdcard/media/audio. Despite the app going thro

I am attempting to create a program that saves an mp3 to the Android, which can be accessed by ASTRO. I am开发者_高级运维 attempting to save the file to /sdcard/media/audio. Despite the app going through without a single error on Logcat/DDMS, the file is nowhere to be found. I added the WRITE_EXTERNAL_STORAGE permission (along with Internet, etc.) so it's not that.

Are there restrictions for apps saving files to the sdcard?

Method called:

public void findSong(View view) throws Exception {
    edittext = (EditText) findViewById(R.id.edittext);          
    searchTerm = edittext.getText().toString();
    String address;         
    address = getMusic(searchTerm);         
    ImageManager img = new ImageManager(); //calls ImageManager (below)         
    img.DownloadFromUrl(address, title + ".mp3"); 
}

The downloading method:

private final String PATH = "/data/data";  //put the downloaded file here

public void DownloadFromUrl(String imageURL, String fileName) {  
//this is the downloader method

try {
    URL url = new URL(imageURL); //you can write here any link
    File file = new File(fileName);
    long startTime = System.currentTimeMillis();
    Log.d("ImageManager", "download begining");
    Log.d("ImageManager", "download url:" + url);
    Log.d("ImageManager", "downloaded file name:" + fileName);

    /* Open a connection to that URL. */
    URLConnection ucon = url.openConnection();

    /* Define InputStreams to read from the URLConnection. */
    InputStream is = ucon.getInputStream();
    BufferedInputStream bis = new BufferedInputStream(is);

    /* Read bytes to the Buffer until there is nothing more to read(-1). */
    ByteArrayBuffer baf = new ByteArrayBuffer(50);
    int current = 0;
    while ((current = bis.read()) != -1) {
        baf.append((byte) current);
    }

   /* Convert the Bytes read to a String. */
   FileOutputStream fos = new FileOutputStream(PATH + file);
   fos.write(baf.toByteArray());
   fos.close();
   Log.d("ImageManager", "download ready in"
       + ((System.currentTimeMillis() - startTime) / 1000)
       + " sec");
   } catch (IOException e) {
       Log.d("ImageManager", "Error: " + e);
   }
}

Any help appreciated.


If the file is an mp3 you should do:

Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));

This will foce an scan and make it available in the media player.

0

精彩评论

暂无评论...
验证码 换一张
取 消