可能的Android线程错误 - 自定义侦听器

时间:2013-07-30 15:17:48

标签: android multithreading listener

请参阅代码:

MainActivity.java:

protected void onCreate(Bundle savedInstanceState) {
...
TestClass tc = new TestClass();
tc.Test(new TestListener() {
    public void onSuccess() {
             //success do something
        }

        public void onFail() {
            //fail do something
        }
    });
}

TestClass:

public class TestClass {

    private static final int MSG_SUCCESS = 1;
    private static final int MSG_FAIL = 0;

    private TestListener listener = null;

    public void Test(TestListener listener) {
        this.listener = listener;
        Log.d("test", "=======" + Thread.currentThread().getId());

        HandlerThread ht = new HandlerThread("MyThread");
        ht.start();

        Thread thread = new Thread(mRunnable);
        thread.run();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_SUCCESS:
                Log.d("test", "on success");
                if (listener != null) {
                    listener.onSuccess();
                }
                break;
            case MSG_FAIL:
                if (listener != null) {
                    listener.onFail();
                }
                break;
            }
        }

    };

    Runnable mRunnable = new Runnable() {

        @Override
        public void run() {
            Log.d("test", "=======" + Thread.currentThread().getId());
            try {
                Log.d("test", "start sleep");
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.d("test", "sleep end");
            mHandler.obtainMessage(MSG_SUCCESS).sendToTarget();
        }

    };
}

TestListener:

public interface TestListener {

    public void onSuccess();
    public void onFail();

}

打印日志:

07-30 15:15:03.565: D/test(2202): =======1
07-30 15:15:03.565: D/test(2202): =======1

Slaver Thread无效?

2 个答案:

答案 0 :(得分:2)

这是问题所在:

thread.run();

在现有线程中正在运行Runnable代码同步。你的意思是:

thread.start();

答案 1 :(得分:0)

首先,你必须展示()你的Toast msgs:

Toast.makeText(getApplicationContext(), "onsuccess", Toast.LENGTH_SHORT).show();

你想开始()你的主题:

thread.start();