我使用了一个教程并得出了这个在模拟器中工作的结果,但它在真正的 Android 设备上停止工作。
此处给出了代码,并设置了所需的所有其他 Android 权限;互联网和写入外部设备已设置。
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class main extends Activity {
private final String PATH = "/mnt/sdcard/Pictures/";
TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.textView1);
DownloadFromUrl(PATH + "dwnldimg.png");
ImageView iv = (ImageView) findViewById(R.id.imageView1);
Bitmap bmp = BitmapFactory.decodeFile(PATH + "dwnldimg.png");
iv.setImageBitmap(bmp);
}
public void DownloadFromUrl(String fileName) {
try {
URL url = new URL("http://192.168.1.4/evilempire.jpg"); //you can write here any link
File file = new File(fileName);
long startTime = System.currentTimeMillis();
tv.setText("Starting download......from " + url);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();;
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
tv.setText("Download Completed in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
} catch (IOException e) {
tv.setText("Error: " + e);
}
}
}