我试图使用Android模拟器从服务器下载图像。似乎下载工作正常,但我无法获取下载的图像。我收到此错误:
Unable to decode stream: java.io.FileNotFoundException: /storage/sdcard/downloadedfile.jpg: open failed: ENOENT (No such file or directory)
这是我用过的代码:
public class DownloadActivity extends Activity {
// button to show progress dialog
Button btnShowProgress;
// Progress Dialog
private ProgressDialog pDialog;
ImageView my_image;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0;
// File url to to download
private static String file_url = `"http://10.0.2.2:8080/TestAndroid/DownloadServlet/Desert.jpg";`
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// show progress bar button
btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
// Image view to show image after downloading
my_image = (ImageView) findViewById(R.id.my_image);
/**
* Show Progress bar click event
* */
btnShowProgress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
}
});
}
/**
* Showing Dialog
* */
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream
// OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
long startTotalTime = System.currentTimeMillis();
long passedTime =0;
long previosTime=0;
while ((count = input.read(data)) != -1) {
total += count;
long endtTime = System.currentTimeMillis();
long passed;
passedTime =endtTime - startTotalTime;
// passed=passedTime -previosTime ;
// previosTime = passed ;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
Log.i("log_lenghtOfFile",lenghtOfFile+"" );
Log.i("log_total",total+"" );
Log.i("log_ourcentage",(int)((total*100)/lenghtOfFile)+"" );
Log.i("log_passed_time",passedTime +"" );
calculDebitdescendant( total, lenghtOfFile);
// Log.i("log_Debit",passedTime +"" );
// writing data to file
// output.write(data, 0, count);
}
long endTotalTime = System.currentTimeMillis();
Log.i("log_Total_passed_time",endTotalTime-startTotalTime +"" );
// flushing output
// output.flush();
// closing streams
// output.close();
input.close();
} catch (Exception e) {
Log.e("Error***: ", e.getMessage());
}
return null;
}
public void calculDebitdescendant(long bytesAvailable,long TotalSize){
long bytesAvailable1 = bytesAvailable;
long TotalSize1 = TotalSize;
Log.i("bytesAvailable",bytesAvailable1 +"fonction");
Log.i("log_ourcentage",(int)(((TotalSize1-bytesAvailable1 )*100)/TotalSize1 )+"% " );
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
Log.i("imagePath", imagePath);
// setting downloaded into image view
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
}
PS:模拟器的SD卡不包含该图像,我放了所有权限。 如果有人知道错误的来源,请告诉我。谢谢。
答案 0 :(得分:1)
我编辑了代码,我可以从服务器下载图片到模拟器的SD卡。我只是启用写入(我把它们放在评论中)
public class DownloadActivity extends Activity {
// button to show progress dialog
Button btnShowProgress;
// Progress Dialog
private ProgressDialog pDialog;
ImageView my_image;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0;
// File url to to download
// private static String file_url = "http://192.168.1.106:8080/TestAndroid/DownloadServlet/Desert.jpg";
private static String file_url = "http://10.0.2.2:8080/TestAndroid/DownloadServlet/Desert.jpg";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// show progress bar button
btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
// Image view to show image after downloading
my_image = (ImageView) findViewById(R.id.my_image);
/**
* Show Progress bar click event
* */
btnShowProgress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
}
});
}
/**
* Showing Dialog
* */
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
long startTotalTime = System.currentTimeMillis();
long passedTime =0;
long previosTime=0;
while ((count = input.read(data)) != -1) {
total += count;
long endtTime = System.currentTimeMillis();
long passed;
passedTime =endtTime - startTotalTime;
// passed=passedTime -previosTime ;
// previosTime = passed ;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
Log.i("log_lenghtOfFile",lenghtOfFile+"" );
Log.i("log_total",total+"" );
Log.i("log_ourcentage",(int)((total*100)/lenghtOfFile)+"" );
Log.i("log_passed_time",passedTime +"" );
calculDebitdescendant( total, lenghtOfFile);
// Log.i("log_Debit",passedTime +"" );
// writing data to file
output.write(data, 0, count);
}
long endTotalTime = System.currentTimeMillis();
Log.i("log_Total_passed_time",endTotalTime-startTotalTime +"" );
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error***: ", e.getMessage());
}
return null;
}
public void calculDebitdescendant(long bytesAvailable,long TotalSize){
long bytesAvailable1 = bytesAvailable;
long TotalSize1 = TotalSize;
Log.i("bytesAvailable",bytesAvailable1 +"fonction");
Log.i("log_ourcentage",(int)(((TotalSize1-bytesAvailable1 )*100)/TotalSize1 )+"% " );
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
Log.i("imagePath", imagePath);
Log.i("isExternalStorageWritable", isExternalStorageWritable() + "true" );
// setting downloaded into image view
my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}
}
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
Log.i("isExternalStorageWritable", "true" );
return true;
}
return false;
}
}