在Android webview上下载.mp3文件

时间:2014-03-10 12:47:01

标签: android webview

我需要帮助。

我有这个活动:

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class WebViewActivity extends Activity {
        private WebView webView;
        public void onCreate(Bundle savedInstanceState) {

                super.onCreate(savedInstanceState);
                setContentView(R.layout.webview);

                webView = (WebView) findViewById(R.id.webView1);
                webView.getSettings().setJavaScriptEnabled(true);
                webView.loadUrl("file:///android_asset/index.html");
        }

}

如何下​​载文件if url = .mp3

1 个答案:

答案 0 :(得分:0)

最好使用异步任务

protected String doInBackground(String... arg0) {
            int count;
            try {
                System.out.println("File Path in doBackground: "+GlobalVariable.getStrPath());
                URL url = new URL(GlobalVariable.getStr());
                HttpURLConnection c = (HttpURLConnection) url.openConnection();
                c.setRequestMethod("GET");
                c.setDoOutput(true);
                c.connect();
                int lenghtOfFile = c.getContentLength();
                String PATH = Environment.getExternalStorageDirectory() + "/foldername/";
                Log.v("appname", "PATH: " + PATH);
                File file = new File(PATH);
                file.mkdirs();

                File outputFile = new File(file, fileName);

                FileOutputStream fos = new FileOutputStream(outputFile);

                InputStream is = c.getInputStream();

                byte[] buffer = new byte[1024];
                long total = 0;
                System.out.println("filesize usibng buffer: "+is.read(buffer));
                while ((count = is.read(buffer)) != -1) {
                    total += count;
//                  publishProgress("" + (long) ((total * 100) / count));
                //  publishProgress("" + (long) ((total) / count));
                    publishProgress("" + (long) ((total) / count));
                    fos.write(buffer, 0, count);
                }
                fos.close();
                is.close();

            } catch (IOException e) {
                Log.d("myappname", "Error: " + e);
            }
            return null;
        }
相关问题