Android一段时间后自动点击按钮

时间:2016-04-10 17:47:40

标签: android delay sleep wifi-direct

我是初学Android开发者。我正在开发WiFi Direct实施。我的目标是在连接发生后经过一定时间(让我们说10秒钟)后将一台设备与另一台设备断开连接。我想我需要使用performClick()和sleep()函数,但我无法弄清楚如何在我的代码中使用它们。任何帮助将非常感激。我把"要做的事情"评论,我想要这样做。这是我对整个代码的一部分:`@Override     public View onCreateView(LayoutInflater inflater,ViewGroup容器,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;
}`

1 个答案:

答案 0 :(得分:0)

使用处理程序。

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