我正在尝试制作一个Android应用程序,只下载和保存带有.mp3扩展名的文件。但是它不断下载并保存SD卡上的文件,没有任何扩展名。
我发布了以下代码。
@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);
}
}
}
答案 0 :(得分:1)
省去你正在做的所有事情的麻烦,并使用像http-request这样的库来做到这一点。
示例代码:
File output = new File("/path/to/sd/card/bam.mp3");
HttpRequest.get("http://example.org/file/bam.mp3").receive(output);
我可以看到你已经知道如何获得SD卡路径,所以就这样做。