哪个线程在单独的线程中执行接口侦听器调用的“ @override”方法?

时间:2019-09-19 07:35:32

标签: java android android-fragments interface

我在Fragment中启动线程并使用接口调用,以@Override Fragment中启动线程的方法。此@Override会停止ProgressDialog并更改片段中TextView的文本。

当我在Activity中执行相同操作时,没有问题,但是现在使用片段时,我得到了“只有创建视图的线程才能触摸它的视图”-错误。因此,我使用了getActivity().runOnUiThread(runnable)并将代码发布到MainThread,但是为什么我需要这样做,因为它可以在没有此功能的Activity中工作?我做错了吗?

线程

//interface
private ConnectToDevice connectToDevice;

//C-Tor
public Thread_ConnectToDevice(BluetoothDevice device, ConnectToDevice connectToDevice ) {
    this.mBluetoothDevice = device;
    this.connectToDevice = connectToDevice;
  }
//call
connectToDevice.connectionSuccess(false, null);

片段

//make Thread
 thread_connectToDevice = new Thread_ConnectToDevice(mBluetoothDevice, Fragment_RoutineStartConnection_setPassword.this);
thread_connectToDevice.start();

//CallBack
//Thread Connect Success
  @Override
  public void connectionSuccess(final Boolean bSuccess,final BluetoothSocket mSocket) {
    getActivity().runOnUiThread(new Runnable() {
      @Override
      public void run() {
        if(bSuccess){
          mProgessDialog.setTitle(R.string.tv_Fragmentsetpassword_Connected_CheckPW);
          if(thread_connectedToDevice != null){
            if(thread_connectedToDevice.isAlive()){
              thread_connectedToDevice.interrupt();
            }
          }
          thread_connectedToDevice = new Thread_ConnectedToDevice(mSocket, sTryingDonglePassword);
          thread_connectedToDevice.start();

        }else{
          mProgessDialog.dismiss();
          tv_Fragmentsetpassword_userhint
              .setTextColor(getResources().getColor(R.color.Mercedes_RED, null));
          tv_Fragmentsetpassword_userhint.setText(R.string.tv_Fragmentsetpassword_ConnectionFailed);
        }
      }
    });
  }

我感觉自己将错误的侦听器实例传递给了线程。

根据要求,这是在Activity中以相同的方式实现的回调: 线程

//listener
private Finished_AskingForInformation listener;

//C-Tor
public Td_AskForInformation(
      Finished_AskingForInformation listener) {
    this.listener = listener;
  }

//call
listener.AskingFinished();

活动

//Create and start thread
td_askForInformation = new Td_AskForInformation(this);
    td_askForInformation.start();

//CallBack
@Override
  public void AskingFinished() {
    mProgressDialog.dismiss();
  }

0 个答案:

没有答案