xml 新建一个ImageView,叫做“show”
流程:
1.新建一个URL类,它是图片的地址
2.用输入流得到URL的地址
3.解析图片为bmp bitmap = BitmapFactory.decodeStream(is);
4.发送Handler到主线程,改变UI
5.结束 is.close();
Java代码:
package com.example.leon.myapplication;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
public class MyActivity extends Activity {
ImageView show;
//downloaded from internet
Bitmap bitmap;
Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
if(msg.what==0x123)
{
show.setImageBitmap(bitmap);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
show = (ImageView)findViewById(R.id.show);
new Thread(new Runnable() {
@Override
public void run() {
try{
URL url = new URL("http://www.baidu.com/search/img/logo.gif");
InputStream is = url.openStream();
bitmap = BitmapFactory.decodeStream(is);
handler.sendEmptyMessage(0x123);
is.close();
//filestream
is = url.openStream();
//Output stream to SDcard
OutputStream os = openFileOutput("baidu.gif",MODE_WORLD_READABLE);
byte[] buff = new byte[1024];
int hasRead = 0;
while( hasRead = is.read(buff)>0)
{
os.write(buff,0,hasRead);
}
is.close();
os.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}).start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}