【问题标题】:Possible Android Thread Bug - Custom Listener可能的 Android 线程错误 - 自定义侦听器
【发布时间】:2013-07-30 15:17:47
【问题描述】:

请看代码:

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

奴隶线程没有作用?

【问题讨论】:

    标签: android multithreading listener


    【解决方案1】:

    这就是问题所在:

    thread.run();
    

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

    thread.start();
    

    【讨论】:

      【解决方案2】:

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

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

      你想开始()你的线程:

      thread.start();
      

      【讨论】:

        猜你喜欢
        • 2012-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多