Handler+Callback更新UI

今天写了个小测试程序,实现了在其他线程更新UI的功能。

两个按键,一个开始更新生成的数字。另一个停止数字更新。

通过回调callback,在Handler里修改界面上的textview。

代码如下,留将来使用

main.xml

<LinearLayout 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:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/btn_start"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Start" />

        <Button
            android:id="@+id/btn_stop"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Stop" />
    </LinearLayout>

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:gravity="center"
        android:hint="Number"
        android:textSize="30sp" />

</LinearLayout>
MainActivity.java

package com.example.handlerthread.handlerthreaddemo;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {

    private boolean isRunning = false;

    private Button mBtn_Start;
    private Button mBtn_Stop;
    private TextView mTextView;

    private NumberGen mNumberGen;

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

        mBtn_Start = (Button) findViewById(R.id.btn_start);
        mBtn_Start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mNumberGen.startNumberGen();
            }
        });
        mBtn_Stop = (Button) findViewById(R.id.btn_stop);
        mBtn_Stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mNumberGen.stopNumberGen();
            }
        });
        mTextView = (TextView) findViewById(R.id.text);


        mNumberGen = new NumberGen();
        mNumberGen.setOnUpdateUIListener(new NumberGen.OnUpdateUIListener() {
            @Override
            public void OnUpdateUI(int num) {
                mTextView.setText(Integer.toString(num));
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mNumberGen.stopNumberGen();
    }
}
NumberGen.java

package com.example.handlerthread.handlerthreaddemo;

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

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Created by pc on 2014/12/22.
 */
public class NumberGen {

    private static final int UPDATE_TEXTVIEW = 1;

    private NumberGenThread mNumerGenThread;
    private NumberGenHandler mNumberGenHandler;

    public interface OnUpdateUIListener {
        public void OnUpdateUI(int num);
    }

    OnUpdateUIListener mOnUpdateUIListener;

    public void setOnUpdateUIListener(OnUpdateUIListener l) {
        mOnUpdateUIListener = l;
    }

    public NumberGen() {
        mNumberGenHandler = new NumberGenHandler(Looper.getMainLooper());
    }
    private class NumberGenHandler extends Handler {

        NumberGenHandler(Looper mainlooper) {
            super(mainlooper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UPDATE_TEXTVIEW:
                    if (!getStatus()) {
                        return;
                    }
                    int num = msg.arg1;
                    mOnUpdateUIListener.OnUpdateUI(num);
                    break;
            }
        }
    }

    private class NumberGenThread extends Thread {

        private boolean isRunning = true;

        private Random rand;

        NumberGenThread() {
            super("NumberGenThread");
            rand = new Random();
        }

        @Override
        public void run() {
            super.run();
            while (isRunning) {
                try {
                    TimeUnit.MILLISECONDS.sleep(1000);
                } catch (Exception e) {}

                Message msg = mNumberGenHandler.obtainMessage(UPDATE_TEXTVIEW);
                int num = rand.nextInt(9999);
                msg.arg1 = num;
                msg.sendToTarget();
            }
        }

        public void setThreadStatus(boolean running) {
            isRunning = running;
        }

        public boolean getThreadStatus() {
            return isRunning;
        }
    }

    public boolean getStatus() {
        return mNumerGenThread.getThreadStatus();
    }

    public void startNumberGen() {
        stopNumberGen();
        mNumerGenThread = new NumberGenThread();
        mNumerGenThread.setThreadStatus(true);
        mNumerGenThread.start();
    }

    public void stopNumberGen() {
        if (mNumerGenThread != null) {
            mNumerGenThread.setThreadStatus(false);
        }
    }
}

你可能感兴趣的:(Handler+Callback更新UI)