Android Handler can read the network in the new thread.

Source: Internet
Author: User

Android Handler can read the network in the new thread.
Method 1:

Create a Thread and call the start method.


Package com. example. android_handle; import java. io. bufferedInputStream; import java. io. inputStream; import URL; import URLConnection; import org. apache. http. util. byteArrayBuffer; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import and Roid. widget. textView; public class MainActivity extends Activity {private Button start; private TextView text; Handler handler = new Handler () {@ Override public void handleMessage (Message msg) {// TODO Auto-generated method stub text. append (msg. obj + "\ n") ;}}; Runnable newTread = new Runnable () {String content; @ Override public void run () {// TODO Auto-generated method stub // network processing // obtain Message completion Message msg = handler. obtainMessage (); // assign the try {URL uri = new URL ("http: //" + "library/hotReading to the arg1 parameter of the message structure. php "); URLConnection ucon = uri. openConnection (); ucon. setConnectTimeout (10000); InputStream is = ucon. getInputStream (); BufferedInputStream bis = new BufferedInputStream (is); ByteArrayBuffer baf = new ByteArrayBuffer (100); int current = 0; while (current = bi S. read ())! =-1) {baf. append (byte) current);} content = new String (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 (new OnClickListener () {@ Override public void onClick (View v) {// TODO Auto-generated method stub Thread t = new Thread (newTread); t. start ();}});}}
Method 2:

Implemented using the logoff class in the android development framework

Logoff is a tool used to add a MessageQueue to a thread and wait cyclically. When there is a message, it will arouse the thread to process the message until the thread ends. Normally, logoff is not used, because for system components such as Activity and Service, Frameworks has initialized the thread (commonly known as the UI thread or main thread) for us and contains a logoff, and the message queue created by logoff, so the main thread will continue to run and process user events until some events (BACK) Exit.

If we need to create a new thread, and this thread needs to be able to process the message events sent by other threads cyclically, or to perform complex interaction with other threads for a long time, in this case, logoff is required to establish a message queue for the thread.

Logoff is also very simple, and there are few methods, the most important of which are four:
Public static prepare ();
Public static mylogoff ();
Public static loop ();
Public void quit ();

The usage is as follows:
1. Call lorule. prepare () in the run () method of each thread to initialize the message queue for the thread.
2. Call lorule. mylorule () to obtain the reference of this lorule object. This is not necessary, but if you need to save the logoff object, it must be after prepare (). Otherwise, the method called on this object may not be effective, such as logoff. quit () won't quit.
3. Add Handler in the run () method to process messages.
4. Add logoff. loop () call to start the thread's message queue and receive messages.
5. When you want to exit the message loop, call logoff. quit (). Note that this method is called on the object. Obviously, the object means to exit the specific logoff. If no other operation is performed in run (), the thread stops running.


package com.example.android_handle;import;import;import;import;import org.apache.http.util.ByteArrayBuffer;import;import android.os.Bundle;import android.os.Handler;import android.os.Looper;import android.os.Message;import android.text.method.ScrollingMovementMethod;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity {    private Button start;    private TextView text;    private Handler handler;    private NewThread thread;    private String s="";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        start = (Button) findViewById(;        text = (TextView) findViewById(;        text.setMovementMethod(ScrollingMovementMethod.getInstance());         handler = new Handler() {            @Override            public void handleMessage(Message msg) {                // TODO Auto-generated method stub                s = s + msg.obj + "\n";                text.setText(s);            }        };        start.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                // TODO Auto-generated method stub                thread = new NewThread();            }        });    }    private class NewThread extends Thread {        private Handler mHandler;        private Looper mLooper;        private String content;        public NewThread() {            start();        }        public void run() {            Looper.prepare();            mLooper = Looper.myLooper();            mHandler = new Handler(mLooper) {                @Override                public void handleMessage(Message msg) {                    // TODO Auto-generated method stub                    Message newMsg = Message.obtain();                    newMsg.obj = msg.obj;                    handler.sendMessage(newMsg);                }            };            try {                URL uri = new URL(""                        + "library/hotReading.php");                URLConnection ucon = uri.openConnection();                ucon.setConnectTimeout(10000);                InputStream is = ucon.getInputStream();                BufferedInputStream bis = new BufferedInputStream(is);                ByteArrayBuffer baf = new ByteArrayBuffer(100);                int current = 0;                while ((current = != -1) {                    baf.append((byte) current);                }                content = new String(baf.toByteArray(), "UTF-8");            } catch (Exception e) {                content = e.toString();            }            Message msg = Message.obtain();            msg.obj = content;            mHandler.sendMessage(msg);            Looper.loop();        }    }}

Related Article

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: 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.