public class MainActivity extends Activity {
ImageView imageView ;
String uil = "http://192.168.56.1:8080/webroot/sna.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)findViewById(R.id.pic);
/*FileOutputStream out;
try {
out = this.openFileOutput("sna.jpg", Context.MODE_WORLD_READABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.write("QWER".getBytes());
out.close();*/
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onclick (View v){
//int id = v.getId();
Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getAbsolutePath()+"/sna.jpg");
Log.i("tag", ""+Environment.getExternalStorageDirectory().getAbsolutePath()+"/picture1.jpg");
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)&&bitmap!=null) {
imageView.setImageBitmap(bitmap);
}else {
MyAsyncTask myAsyncTask = new MyAsyncTask(imageView);
myAsyncTask.execute(uil);
}
/*
MyAsyncTask myAsyncTask = new MyAsyncTask(imageView);
myAsyncTask.execute(uil);*/
}
}
public class MyAsyncTask extends AsyncTask<String, Integer, Bitmap> {
ImageView iv ;
Bitmap bitmap ;
public MyAsyncTask(ImageView imageView) {
super();
iv = imageView;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
@Override
protected Bitmap doInBackground(String... params) {
//客户端对象
HttpClient client = new DefaultHttpClient();
//
HttpGet get = new HttpGet(params[0]);
try {
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
//流用完就会制空
InputStream inputStream = response.getEntity().getContent();
//bitmap = BitmapFactory.decodeStream(inputStream);
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/sna.jpg");
Log.i("tag", ""+Environment.getExternalStorageDirectory().getAbsolutePath()+"/picture.jpg");
FileOutputStream out;
try {
out = new FileOutputStream(file);
byte[] date = new byte[1024];
int length = 1;
while ((length = inputStream.read(date))!=-1) {
out.write(date,0,length);
}
out.flush();
out.close();
bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getAbsolutePath()+"/sna.jpg");
inputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
if (result!=null) {
iv.setImageBitmap(result);
}
super.onPostExecute(result);
}
}