Android-get web Images

Source: Internet
Author: User

Package com.itheima.viewimg;

Import Java.io.InputStream;
Import java.net.HttpURLConnection;
Import java.net.MalformedURLException;
Import Java.net.URL;

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.text.TextUtils;
Import Android.view.View;
Import Android.widget.EditText;
Import Android.widget.ImageView;
Import Android.widget.Toast;

public class Mainactivity extends Activity {

protected static final int SUCCESS = 0;
protected static final int network_error = 1;
protected static final int ERROR = 2;
Private EditText Ed_path;
Private ImageView IV;
Private String path;

This is the little secret.
Private Handler Mhandler = new Handler () {

public void Handlemessage (Message msg) {

Switch (msg.what) {
Case SUCCESS:
Take out the data in the message
Bitmap Bitmap = (Bitmap) msg.obj;
Iv.setimagebitmap (bitmap);
Break
Case NETWORK_ERROR:
Pop Toast Message
System.out.println ("====== network_error");
Toast.maketext (mainactivity.this, "Connection error ....", 0). Show ();
Break
Case ERROR:
Pop-up toast friendly tip message
System.out.println ("====== ERROR");

Toast.maketext (Mainactivity.this, "failed to get resources ....", 0). Show ();
Break

Default
Break
}


};
};

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);

Ed_path = (EditText) Findviewbyid (R.id.ed_path);
IV = (ImageView) Findviewbyid (R.ID.IV);
}

public void Gogetimage (View v) {

Path = Ed_path.gettext (). toString (). Trim ();
int i=1/0;

if (textutils.isempty (path)) {

Toast.maketext (This, "Path has errors ...", 0). Show ();
Return
}

New Thread () {

public void Run () {

try {
URL url = new URL (path);

Android, Google provides a good API to connect to the network

These APIs look exactly the same as you did when you were a child, but the specifics of the implementation in the method are different from the APIs in the JDK that you learned earlier.
//
HttpURLConnection conn = (httpurlconnection) url.openconnection ();

When connecting to the network, there are many uncertainties ...
To provide a user's feelings, a connection time-out is set
Conn.setconnecttimeout (5000);

How to set the request
Conn.setrequestmethod ("GET");

Get the type of data returned
String ContentType = Conn.getcontenttype ();

The length of the data
int length = Conn.getcontentlength ();

System.out.println ("ContentType:" + contentType);
System.out.println ("Length:" + length);

Get the status of the server returned, according to the status code to determine whether the success
int code = Conn.getresponsecode ();

200, 404, 500, 302, 304..

if (code==200) {

The incoming request, which indicates a successful processing, returns the data

Gets the stream data of the returned picture
InputStream in = Conn.getinputstream ();

What if we were to parse it??? --How to parse into a picture display

This is a lot to do, Google engineers have helped us to provide a ready-made class, you can convert a stream of data into a picture

This is already a picture.
Bitmap Bitmap = Bitmapfactory.decodestream (in);

Iv.setimagebitmap (bitmap);

In a child thread, send a message out through the little secret.
Message msg = new Message ();

Internally, the message is judged whether it was created, if it was created, the original is obtained, and then
To change the information of the original MSG, so that the MSG has a new value, avoid the repetition of the creation of the MSG object,
Save on memory overhead
Message msg = Message.obtain ();
msg.what=success;
Msg.obj = bitmap;


Put in the message queue, Messagequerue, there is a circulator looper to remove the message,
And then we'll tell the little secret to deal with it.
Mhandler.sendmessage (msg);

In.close ();
}else{

Notifies the UI to give the user a friendly hint
Toas
Message msg = Message.obtain ();
Msg.what=error;

Mhandler.sendmessage (msg);

}


Here to connect to the network, will consume the user's money, so need to apply for connection network permissions

} catch (Exception e) {
Notifies the UI to give the user a friendly hint

The inside of the code is also updating the UI, and updating the UI cannot be done in a sub-thread
Toast.maketext (mainactivity.this, "Connection error ....", 0). Show ();

Message message = Message.obtain ();
Message.what= Network_error;
Mhandler.sendmessage (message);

E.printstacktrace ();
}

};

}.start ();
API URL class for connecting to a network



}

}

Android-get web Images

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.