繁体   English   中英

在SD卡{Android应用}上将文件另存为Mp3

[英]Save File as Mp3 on Sd card { Android app}

我正在尝试制作一个仅以.mp3扩展名下载和保存文件的android应用程序,但是它一直在不使用任何扩展名的情况下继续下载和保存sdcard上的文件。

我在下面发布了代码。

@SuppressWarnings("deprecation")
private LinearLayout.LayoutParams LP_FW = new LinearLayout.LayoutParams(
        LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
private LinearLayout.LayoutParams LP_WW = new LinearLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

private String fileName;
private String path;
private boolean openFlag;

private static final int DOWNLOAD = 1;
private static final int DOWNLOAD_FINISH = 2;
private String mSavePath;
private int progress;
private boolean cancelUpdate ;

private Context mContext;
private ProgressBar mProgress;
private Dialog mDownloadDialog;
private TextView textView;
private final String[][] type_amp = {{ ".mp3", "audio/x-mpeg" } };

@Override
public boolean execute(String action, JSONArray args,
        CallbackContext callbackContext) throws JSONException {
    init(args.getString(0),args.getString(1),args.getBoolean(2));
    showDownloadDialog();
    return super.execute(action, args, callbackContext);
}

private void init(String path,String fileName,boolean openFlag){
    this.mContext = this.cordova.getActivity();
    this.path = path;
    this.fileName = fileName;
    this.openFlag = openFlag;
    this.cancelUpdate = false;
}


private void showDownloadDialog() {
    AlertDialog.Builder builder = new Builder(mContext);
    builder.setTitle("Downloading Music");
    LinearLayout layout = new LinearLayout(mContext);
    layout.setLayoutParams(LP_FW);
    layout.setGravity(Gravity.CENTER);
    layout.setOrientation(LinearLayout.VERTICAL);
    mProgress = new ProgressBar(mContext, null,
            android.R.attr.progressBarStyleHorizontal);
    mProgress.setLayoutParams(LP_FW);
    layout.addView(mProgress);
    textView = new TextView(mContext);
    textView.setLayoutParams(LP_WW);
    layout.addView(textView);
    builder.setView(layout);
    builder.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    cancelUpdate = true;
                }
            });
    mDownloadDialog = builder.create();
    mDownloadDialog.show();
    downloadFile();
}


@SuppressLint("DefaultLocale")
private String getOpenType(File file) {
    String type = "*/*";
    String fName = file.getName();
    int dotIndex = fName.lastIndexOf(".");
    if (dotIndex < 0) {
        return type;
    }
    String end = fName.substring(dotIndex, fName.length()).toLowerCase();
    if (end == "")
        return type;
    for (int i = 0; i < type_amp.length; i++) {
        if (end.equals(type_amp[i][0]))
            type = type_amp[i][1];
    }
    return type;
}


private void openFile() {
    File file  = new File(mSavePath,fileName);
    if (!file.exists()) {
        return;
    }
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setDataAndType(Uri.parse("file://" + file.toString()),
            getOpenType(file));
    try {
        mContext.startActivity(i);
    } catch (Exception e) {
        Toast.makeText(mContext, "无法打开" + file.getName(),
                Toast.LENGTH_SHORT).show();
    }

};

private Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
        case DOWNLOAD:
            mProgress.setProgress(progress);
            textView.setText(progress + "%");
            break;
        case DOWNLOAD_FINISH:
            if(openFlag){
                openFile();
            }
            break;
        default:
            break;
        }
    }

};


private void downloadFile() {
    new DownloadFileThread().start();

}
class DownloadFileThread extends Thread {
    @Override
    public void run() {
        try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                conn.connect();
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();

                FileOutputStream fos = getOutStream(fileName);
                int count = 0;
                byte buf[] = new byte[1024];
                do {
                    int numread = is.read(buf);
                    count += numread;
                    progress = (int) (((float) count / length) * 100);
                    mHandler.sendEmptyMessage(DOWNLOAD);
                    if (numread <= 0) {
                        mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                        break;
                    }
                    fos.write(buf, 0, numread);
                } while (!cancelUpdate);
                fos.close();
                is.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 
        mDownloadDialog.dismiss();
    }

}

@SuppressWarnings("deprecation")
@SuppressLint("WorldReadableFiles")
private FileOutputStream getOutStream(String fileName) throws FileNotFoundException{
    if (Environment.getExternalStorageState().equals(
            Environment.MEDIA_MOUNTED)) {
        String sdpath = Environment.getExternalStorageDirectory()
                + "/";
        mSavePath = sdpath + "download";
        File file = new File(mSavePath);
        if (!file.exists()) {
            file.mkdir();
        }
        File saveFile = new File(mSavePath, fileName);
        return new FileOutputStream(saveFile);
    }else{
        mSavePath = mContext.getFilesDir().getPath();
        return mContext.openFileOutput(fileName , Context.MODE_WORLD_READABLE);
    }
}

 } 

省去您正在做的所有事情的麻烦,并使用诸如http-request之类的库来执行此操作。

样例代码:

File output = new File("/path/to/sd/card/bam.mp3");
HttpRequest.get("http://example.org/file/bam.mp3").receive(output);

我可以看到您已经知道如何获取SD卡路径,因此只需执行此操作即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM