Question: Download pictures of HTTP Network Programming
Public class textwill extends activity {
Private imageview;
Private Bitmap bitmap;
Handler handler = new handler (){
Public void handlemessage (Android. OS. Message MSG ){
If (msg. What = 1 ){
Imageview. setimagebitmap (Bitmap );
}
};
};
/**
* First, I need to know that using a URL to download images is a time-consuming operation,
* A common method to solve time-consuming operations is to create a subthread or an asynchronous task,
* Here I use a subthread.
*
*/
@ Override
Protected void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. activity_main );
// Find the control
Imageview = (imageview) findviewbyid (R. Id. imageview1 );
New thread (New runnable (){
@ Override
Public void run (){
Try {
// Define a URL object
URL url = new URL ("http://p7.qhimg.com/dmt/235_165_/t01b450ad95f830b856.jpg ");
// Open the network input stream corresponding to a URL
Inputstream = URL. openstream ();
// Because the downloaded image is a byte stream, we need to use the in-place Image
// We define a bitmap, that is, bitmap. We also need to use if to judge whether bitmap is null. If bitmap is not empty, we also need to use handler to send a message to the main thread.
// Let the main thread display bitmap
Bitmap = bitmapfactory. decodestream (inputstream );
If (Bitmap! = NULL ){
Handler. sendemptymessage (1 );
}
// Inputstream. Close ();
// Open the output stream corresponding to the mobile phone
Outputstream = openfileoutput ("jiejie.jpg", mode_world_readable );
// Define a byte array and use it as the cache. The size is 1 K;
Byte [] buff = new byte [1024];
// Define an integer hasread to protect the number of read bytes, and use the while loop to determine whether the data size is 0. If the value is greater than 0, write it to the local device.
Int hasread = 0;
While (hasread = inputstream. Read (buff)> 0 ){
Outputstream. Write (buff, 0, hasread );
}
Outputstream. Close ();
Inputstream. Close ();
}
Catch (exception e ){
E. printstacktrace ();
}
}
}). Start ();
}
}
Try to be a Ta!