首页 > 代码库 > 下载MP3并放在sdcard中
下载MP3并放在sdcard中
首先在虚拟机中装入虚拟SDCARD,并匹配,然后在manifest.xml中设置对储存卡的读写权限。
mainactivity代码
1 package com.example.downloadtext; 2 3 import android.app.Activity; 4 import android.os.Bundle; 5 import android.os.Environment; 6 import android.util.Log; 7 import android.view.View; 8 import android.widget.Button; 9 import android.widget.Toast;10 11 import java.io.File;12 import java.io.IOException;13 import java.net.HttpURLConnection;14 15 public class MyActivity extends Activity16 {17 /**18 * Called when the activity is first created.19 */20 static String sdcardpath = "/storage/sdcard/";21 Button download;22 23 @Override24 public void onCreate(Bundle savedInstanceState)25 {26 super.onCreate(savedInstanceState);27 setContentView(R.layout.main);28 download = (Button) findViewById(R.id.download);29 download.setOnClickListener(new downloadListener());30 31 32 }33 34 35 class downloadListener implements View.OnClickListener36 {37 @Override38 39 public void onClick(View view)40 { Log.v("button","button has been clicked");41 42 new DownloadThread().start();43 File file = new File(sdcardpath + "song");44 if (file.exists())45 {46 Toast.makeText(MyActivity.this, "download Sucess", Toast.LENGTH_LONG);//toast只能在ui进程中才能显示,所以这些都不能显示47 48 }49 else50 {51 Toast.makeText(MyActivity.this, "download failed", Toast.LENGTH_LONG);52 53 }54 55 }56 57 58 }59 60 class DownloadThread extends Thread61 {62 @Override63 public void run() {64 Log.v("thread","new thread is started");65 Download downloadmp3 = new Download();66 try67 {68 downloadmp3.downloadmp3("http://sc.111ttt.com/up/mp3/276964/2684CCF02022F454B9E67B5D35F9DDF0.mp3");69 }70 catch (IOException e)71 {72 e.printStackTrace();73 }74 Log.v("thread","thread is overed");75 }76 }77 }
Download类
package com.example.downloadtext;import java.io.*;import java.net.HttpURLConnection;import java.net.URL;import java.nio.Buffer;import java.nio.ByteBuffer;/** * Created by Administrator on 2014/8/14. */public class Download { public void downloadmp3(String urlpath)throws IOException { URL url = new URL(urlpath); HttpURLConnection urlconnection = (HttpURLConnection) url.openConnection(); InputStream inputStream = urlconnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); FileOutputStream fos = new FileOutputStream(new File(MyActivity.sdcardpath+"song")); String readed; while((readed =reader.readLine() )!=null) { fos.write(readed.getBytes()); } fos.close(); inputStream.close(); } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。