我想从服务器下载图像,将其保存在SD卡上并显示。 我写了那段代码,但它不起作用 - 没有错误,但我只看到黑屏而不是图像。
public class Main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyTask mt = new MyTask();
mt.execute();
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File("/sdcard/askeroid/logos/1_mobile.png");
intent.setDataAndType(Uri.fromFile(file), "image/*");
startActivity(intent);
}
}
class MyTask扩展了AsyncTask {
@Override
protected Void doInBackground(Void... params) {
try{
URL url = new URL("http://ed.sadko.mobi/logo/logo_1mobile.png");
URLConnection connection = url.openConnection();
connection.connect();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/askeroid/logos/1_mobile.png");
output.flush();
output.close();
input.close();
} catch(Exception e){e.printStackTrace();}
return null;
}
}
答案 0 :(得分:1)
在转到下一个活动之前,您不会等待下载结束。
我建议您使用AsyncTask
- 使用doInBackground
下载图片,然后在onPostExecute
开始下一个活动。
类似的东西:
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
@Override protected Long doInBackground(Void ... urls) {
// download the image
}
@Override protected void onPostExecute(Void result) {
// start new activity...
}
};
task.execute();
另请注意,SD卡的路径可能因设备而异。看看here,看看如何正确访问它。