Android HandlerThread使用方法

Android HandlerThread使用方法

使用场景:可以实现后台线程,比如网络请求操作,操作完成后再通过ui线程中的Handler来更新UI。

  • activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/main_test_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <Button
        android:layout_alignParentBottom="true"
        android:id="@+id/main_test_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="测试"/>
</RelativeLayout>

  • MainActivity.java:
package com.abc.hellohandlerthread;

import android.os.Bundle;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.format.Time;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    private MyHandlerThread myHandlerThread = null;
    private Button mTestBtn;
    private TextView mTestTV;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTestBtn = (Button)findViewById(R.id.main_test_btn);
        mTestTV = (TextView)findViewById(R.id.main_test_tv);

        mTestBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Message msg = new Message();
                msg.what = 1;
                myHandlerThread.sendMessage(msg);
//                mHandler.sendMessage(msg);
            }
        });

        myHandlerThread = new MyHandlerThread("background thread.");
        myHandlerThread.setmMainHandler(mHandler);
    }

    final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 2) {
                Bundle bundle = msg.getData();
                String threadID = bundle.getString("id");
                String threadName = bundle.getString("name");
                Time time = new Time();
                time.setToNow();

                String timeStr = time.format3339(true);

                StringBuilder sb = new StringBuilder("id:").append(threadID)
                        .append("\nname:").append(threadName).append("\n")
                        .append("time:").append(timeStr);
                mTestTV.setText(sb.toString());
            }
        }
    };

    @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;
    }
    
}

  • MyHandlerThread.java:
package com.abc.hellohandlerthread;

import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;

/**
 * Created by dev on 11/25/13.
 */
public class MyHandlerThread {
    private HandlerThread mHandlerThread = null;
    private MyHandler mHandler = null;
    private Handler mMainHandler = null;

    public MyHandlerThread(String threadName) {
        super();

        mHandlerThread = new HandlerThread(threadName);
        mHandlerThread.start();

        mHandler = new MyHandler(mHandlerThread.getLooper());
    }

    public void setmMainHandler(Handler handler) {
        this.mMainHandler = handler;
    }

    public void sendMessage(Message msg) {
        mHandler.sendMessage(msg);
    }

    class MyHandler extends Handler {
        MyHandler() {
        }

        MyHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Message toMainMsg = mMainHandler.obtainMessage();
            toMainMsg.what = 2;
            Bundle bundle = new Bundle();
            String threadID = String.valueOf(Thread.currentThread().getId());
            String threadName = Thread.currentThread().getName();

            bundle.putString("id", threadID);
            bundle.putString("name", threadName);
            toMainMsg.setData(bundle);

            mMainHandler.sendMessage(toMainMsg);
        }
    }
}


你可能感兴趣的:(android,handlerthread)