2017-05-01 53 views
0

我正在創建一個物聯網項目,通過它我可以通過互聯網控制家庭設備和實用程序。在下面的代碼中,當開關被啓用時,它將打開窗簾。我想在這裏做的是禁用按鈕,直到窗簾完全打開需要5秒的時間,因此用戶將無法按下按鈕關閉窗簾直到它完全打開(由於伺服電機)。我已經寫了下面的代碼來完成這個。它使用Timer類。但它根本不禁用開關。任何幫助,將不勝感激。謝謝!定時器在固定時間內不執行按鈕禁用功能

curtain.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
      if (isChecked) { 

       StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() { 
        @Override 
        public void onResponse(String response) { 

         if (response.equals("open")) { 
          Toast.makeText(getApplicationContext(), "Curtain is opening..", Toast.LENGTH_LONG).show(); 
          final long period = 5000; 
          new Timer().schedule(new TimerTask() { 
           @Override 
           public void run() { 
            curtain.setEnabled(false); 
           } 
          }, System.currentTimeMillis(), period); 
           curtain.setEnabled(true); 
         } else { 
          Toast.makeText(getApplicationContext(), "Failed to open", Toast.LENGTH_SHORT).show(); 
         } 

        } 

       }, new Response.ErrorListener() { 
        @Override 
        public void onErrorResponse(VolleyError error) { 
         Toast.makeText(getApplicationContext(), "Connection failed. Please check your internet connection.", Toast.LENGTH_SHORT).show(); 
         error.printStackTrace(); 

        } 
       }) { 
        @Override 
        protected Map<String, String> getParams() throws AuthFailureError { 
         Map<String, String> getData = new HashMap<>(); 
         getData.put("device", "curtain"); 
         getData.put("action", "open"); 
         return getData; 
        } 
       }; 

       IotSingleton.getInstance(MainActivity.this).addToRequestQue(stringRequest); 
      } 

回答

2

如下只需使用Handler

 ... 
     @Override 
     public void onResponse(String response) { 

      if (response.equals("open")) { 
       buttonView.setEnabled(false); 
       new Handler().postDelayed(new Runnable() { 
        @Override 
        public void run() { 
         buttonView.setEnabled(true); 
        } 
       }, 5000); 
      } else { 
       Toast.makeText(getApplicationContext(), "Failed to open", Toast.LENGTH_SHORT).show(); 
      } 

     } 
     ... 

看看它是否適合你......!

+0

感謝您的解決方案。它像一個魅力。爲了學習,你能否描述我在上面的代碼中做了什麼錯誤? –

+0

@SahadNk請在這裏閱讀docuemntation:https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html#schedule(java.util.TimerTask,%20long,%20long) –