HandlerThread null异常 - Android

时间:2015-02-25 01:06:35

标签: android message-queue android-handler android-looper android-handlerthread

我在我的应用程序中使用ThreadHandler,

public class MessageThread extends HandlerThread {
    Handler mHandler;

    public MessageThread() {
        super("Message Thread");
    }

    public void queueProcessMessage(msgObject mObj) {

        mHandler.obtainMessage(PROCESS_MESSAGE, mObj).sendToTarget();

    }

    @Override
    protected void onLooperPrepared() {

       Commons.logIt("OnLoopPrep");

        mHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {

                switch (msg.what) {


                    case PROCESS_MESSAGE:
                        process_message((msgObject) msg.obj);
                        break;
                    default:

                        break;

                }
            }
        };
    }

   process_message(msgObject obj) {
        //Do stuff
   }

}

我在onCreate()中初始化它,就像这样,

public void onCreate(Bundle savedInstanceState) {

    MessageThread mThread = new MessageThread();
    mThread.start();
    mThread.getLooper();
    if (mThread != null)
        mThread.queueProcessMessage(Object);// this is the line the compiler is pointing at.
}

它工作正常,问题是我需要添加其他东西,我必须开始另一个活动等待结果所以我必须初始化/使用它,如下所示onActivityResult在onCreate之前被调用,当我开始结果的活动,这次我收到错误

java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Message android.os.Handler.obtainMessage(int, java.lang.Object)' on a null object reference

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == IMAGE_ACTIVITY_REQUEST_CODE) {

        if (resultCode == Activity.RESULT_OK) {
           MessageThread mThread = new MessageThread();
           mThread.start();
           mThread.getLooper();

           mThread.queueProcessMessage(new msgObject("stuff"));
        }  

    }
  }

看起来线程没有初始化,我在这里缺少什么?

编辑1,

在讨论了这个问题之后,看起来处理器初始化需要花费一些时间,我这样做了,它很难看但是它有效,我应该怎么做?

    public void queueProcessMessage(msgObject mObj) {
         while (mHandler == null)
            Log.i(TAG, "Not init yet"); //It keeps on looping here
        mHandler.obtainMessage(PROCESS_MESSAGE, mObj).sendToTarget();

    }

0 个答案:

没有答案