一定时间后自动单击按钮 Android

Clicking a button automatically after a certain time Android

我是初学者 Android 开发人员。我正在研究 WiFi Direct 实施。我的目标是在连接发生后一定时间后(比如 10 秒)断开一台设备与另一台设备的连接。我想我需要使用 performClick() 和 sleep() 函数,但我不知道如何在我的代码中使用它们。任何帮助将非常感激。我把 "THINGS TO DO" 评论放在我想做的地方。这是我为此编写的整个代码的一部分:` @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    mContentView = inflater.inflate(R.layout.device_detail, null);

    Button btn_connect = (Button) mContentView.findViewById(R.id.btn_connect);
    btn_connect.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            //startTime = System.currentTimeMillis();
            startTime = System.nanoTime();

            WifiP2pConfig config = new WifiP2pConfig();
            config.deviceAddress = device.deviceAddress;
            config.wps.setup = WpsInfo.PBC;
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }

            progressDialog = ProgressDialog.show(getActivity(), "Press back to cancel",
                    "Connecting to :" + device.deviceAddress, true, true

            );
            ((DeviceActionListener) getActivity()).connect(config);

        }
    });


    Button btn_disconnect = (Button) mContentView.findViewById(R.id.btn_disconnect);
    btn_disconnect.setOnClickListener(new View.OnClickListener() {
        @Override
                public void onClick(View v) {
                    //THINGS TO DO:
                    //i) PASS 10 SECONDS
                    //ii) COME HERE AND MAKE THE PROGRAM CLICK HERE BY ITSELF.
                    ((DeviceActionListener) getActivity()).disconnect();
                    Log.d("ShowWhenDiscon", "It is disconnected!!!! ");
                }
            });

    mContentView.findViewById(R.id.btn_start_client).setOnClickListener(
            new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // Allow user to pick an image from Gallery or other
                    // registered apps
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("image/*");
                    startActivityForResult(intent, CHOOSE_FILE_RESULT_CODE);
                }
            });

    return mContentView;
}`

使用处理程序。

handlerTimer.postDelayed(new Runnable(){
    public void run() {
      // do something here

      // You mentioned to click a button, which needs to be run from the UI Thread. 
      // Use runOnUiThread() for this 


  }}, 20000);

参考文献:

runOnUiThread

handler