0

请看代码:

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

测试类:

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();
        }

    };
}

测试监听器:

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没有效果??

4

2 回答 2

2

这就是问题:

thread.run();

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

thread.start();
于 2013-07-30T15:21:47.273 回答
0

首先,您必须显示()您的 Toast 消息:

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

你想 start() 你的线程:

thread.start();
于 2013-07-30T15:25:21.687 回答