0

我以这种方式在我的应用程序中使用 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();

    }
4

0 回答 0