当前位置: 代码迷 >> 综合 >> 关于在非UI线程中进行UI操作会出现问题: Can't create handler inside thread that has not called Looper.prepare()
  详细解决方案

关于在非UI线程中进行UI操作会出现问题: Can't create handler inside thread that has not called Looper.prepare()

热度:83   发布时间:2023-12-08 21:53:51.0

Activity,Service属于主线程,在主线程中才能更新UI,如toast等。其他线程中不能直接使用,否则产生 Can't create handler inside thread that has not called Looper.prepare()的错误,这时可以使用Handler来处理,Handler可以在Activity和Service中。

功能:当在非UI线程中调用CallPayment()时,弹出对话框。

public void CallPayment(String a) {

       h.post(pay);

}


Handler h = new Handler(){ 

        public void handleMessage (Message msg) 

        { 

            switch(msg.what

            { 

            case HANDLER_TEST

                confirmPay();

                break

            case HANDLER_OVER

                h.removeCallbacks(pay);

                break

            }

        } 

    };

Runnable pay =new Runnable() {

@Override

public void run() {

// TODO Auto-generated method stub

            Message msg = new Message(); 

            msg.what = HANDLER_TEST

            h.sendMessage(msg); 

}

};

public void confirmPay(){    

        Dialog dialog=new AlertDialog.Builder(DevilsAtTheGateGameActivity.this)

        .setMessage(payStr+"EP? ????????\n??:"+payStr+"?")

        .setPositiveButton(R.string.confirm_pay_yes,new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog,int whichButton) {

                   //DoSomething

               }

           })

          .setNegativeButton(R.string.confirm_pay_no,new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog,int whichButton) {

                    dialog.dismiss();                 

                    Message msg = new Message(); 

                    msg.what =HANDLER_OVER

                    h.sendMessage(msg); 

                }

           }).show();

    }

}


  相关解决方案