Android Handler two ways to read the network in a new thread

Source: Internet
Author: User
Tags message queue

Method One:

Create a thread, and then call the Start method.

Instance:

 PackageCom.example.android_handle;ImportJava.io.BufferedInputStream;ImportJava.io.InputStream;ImportJava.net.URL;ImportJava.net.URLConnection;ImportOrg.apache.http.util.ByteArrayBuffer;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.TextView; Public  class mainactivity extends Activity {    PrivateButton start;PrivateTextView text; Handler Handler =NewHandler () {@Override         Public void Handlemessage(Message msg) {//TODO auto-generated method stubText.append (Msg.obj +"\ n");    }    }; Runnable Newtread =NewRunnable () {String content;@Override         Public void Run() {//TODO auto-generated method stub            //Network processing            //Get a message knot firstMessage msg = Handler.obtainmessage ();//Assign a value to the ARG1 parameter of the message structure            Try{URL URI =NewURL ("http://112.74.78.53/scut-lib/"+"library/hotreading.php");                URLConnection Ucon = Uri.openconnection (); Ucon.setconnecttimeout (10000);                InputStream is = Ucon.getinputstream (); Bufferedinputstream bis =NewBufferedinputstream (IS); Bytearraybuffer BAF =NewBytearraybuffer ( -);intCurrent =0; while(current = Bis.read ())! =-1) {Baf.append (byte) (current); } content =NewString (Baf.tobytearray (),"UTF-8"); }Catch(Exception e) {content ="Error";            } msg.obj = content;        Handler.sendmessage (msg); }    };@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        Start = (Button) Findviewbyid (R.id.start);        Text = (TextView) Findviewbyid (R.id.text); Start.setonclicklistener (NewOnclicklistener () {@Override             Public void OnClick(View v) {//TODO auto-generated method stubThread T =NewThread (Newtread);            T.start ();    }        }); }}
Method Two:

Use the Looper class in the Android development framework to achieve

Looper is used to add a message queue (MessageQueue) to a thread, and the loop waits for a tool that evokes the thread to process the message when there is a message until the thread ends. Looper is not normally used, because for system components such as Activity,service, frameworks has initialized the thread (commonly known as the UI thread or the main thread) for us, with a looper in it, and a message queue created by Looper, So the main thread runs all the time, handling user events until some event (back) exits.

If we need to create a new thread, and this thread is able to loop through the message events from other threads, or if it requires a long-term, complex interaction with other threads, then we need to use Looper to create a message queue for the thread.

The use of Looper is also very simple, its method is less, the most important there are four:
public static prepare ();
public static mylooper ();
public static loop ();
public void Quit ();

Here's how to use it:
1. At the beginning of the run () method of each thread, call Looper.prepare (), which is the message queue that is initialized for the thread.
2. Then call Looper.mylooper () to get a reference to this Looper object. This is not necessary, but if you need to save the Looper object, it must be after prepare (), otherwise the method called on this object does not necessarily have an effect, such as looper.quit () will not exit.
3. Add handler in the Run () method to process the message
4. Add the Looper.loop () call, which allows the thread's message queue to start running and can receive messages.
5. When you want to exit the message loop, call Looper.quit () Note that this method is to be called on the object, it is clear that the object means to exit the specific looper. If no other action is in run (), the thread will also terminate.

Instance:

 PackageCom.example.android_handle;ImportJava.io.BufferedInputStream;ImportJava.io.InputStream;ImportJava.net.URL;ImportJava.net.URLConnection;ImportOrg.apache.http.util.ByteArrayBuffer;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Looper;ImportAndroid.os.Message;ImportAndroid.text.method.ScrollingMovementMethod;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.TextView; Public  class mainactivity extends Activity {    PrivateButton start;PrivateTextView text;PrivateHandler Handler;PrivateNewthread thread;PrivateString s="";@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        Start = (Button) Findviewbyid (R.id.start);        Text = (TextView) Findviewbyid (R.id.text);         Text.setmovementmethod (Scrollingmovementmethod.getinstance ()); Handler =NewHandler () {@Override             Public void Handlemessage(Message msg) {//TODO auto-generated method stubs = s + msg.obj +"\ n";            Text.settext (s);        }        }; Start.setonclicklistener (NewOnclicklistener () {@Override             Public void OnClick(View v) {//TODO auto-generated method stubThread =NewNewthread ();    }        }); }Private  class newthread extends Thread {        PrivateHandler Mhandler;PrivateLooper Mlooper;PrivateString content; Public Newthread() {start (); } Public void Run() {looper.prepare ();            Mlooper = Looper.mylooper (); Mhandler =NewHandler (Mlooper) {@Override                 Public void Handlemessage(Message msg) {//TODO auto-generated method stubMessage newmsg = Message.obtain ();                    Newmsg.obj = Msg.obj;                Handler.sendmessage (NEWMSG); }            };Try{URL URI =NewURL ("http://112.74.78.53/scut-lib/"+"library/hotreading.php");                URLConnection Ucon = Uri.openconnection (); Ucon.setconnecttimeout (10000);                InputStream is = Ucon.getinputstream (); Bufferedinputstream bis =NewBufferedinputstream (IS); Bytearraybuffer BAF =NewBytearraybuffer ( -);intCurrent =0; while(current = Bis.read ())! =-1) {Baf.append (byte) (current); } content =NewString (Baf.tobytearray (),"UTF-8"); }Catch(Exception e)            {content = e.tostring ();            } Message msg = Message.obtain ();            Msg.obj = content;            Mhandler.sendmessage (msg);        Looper.loop (); }    }}

Android Handler two ways to read the network in a new thread

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.