[英]How to speed up the response time of a button that uses an http Client
我目前正在開發一個有關可以使用以太網屏蔽控制arduino的android程序的項目,其主要目標是打開/關閉家用設備。 android程序具有定義的按鈕,這些按鈕根據設備的當前狀態而變化。 該項目已接近完成,但唯一的問題是某些按鈕在被按下時的響應時間有所延遲,而有些則沒有。 這個項目非常重要,所以請幫助我。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myhome_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
kitchenLight = (ToggleButton) findViewById(R.id.kitchenLight);
kitchenLight.setOnClickListener(this);
livingLight = (ToggleButton) findViewById(R.id.livingLight);
livingLight.setOnClickListener(this);
garageLight = (ToggleButton) findViewById(R.id.garageLight);
garageLight.setOnClickListener(this);
diningLight = (ToggleButton) findViewById(R.id.diningLight);
diningLight.setOnClickListener(this);
}
public void commandArduino(String url) {
try {
HttpClient httpClient = new DefaultHttpClient();
httpClient.execute(new HttpGet(url));
} catch (Exception e) {
}
}
@Override
public void onClick(View v) {
if (kitchenLight.isChecked()) {
commandArduino("http://192.168.1.102/?lighton1");
} else {
commandArduino("http://192.168.1.102/?lightoff1");
}
if (livingLight.isChecked()) {
commandArduino("http://192.168.1.102/?lighton2");
} else {
commandArduino("http://192.168.1.102/?lightoff2");
}
if (garageLight.isChecked()) {
commandArduino("http://192.168.1.102/?lighton3");
} else {
commandArduino("http://192.168.1.102/?lightoff3");
}
if (diningLight.isChecked()) {
commandArduino("http://192.168.1.102/?lighton4");
} else {
commandArduino("http://192.168.1.102/?lightoff4");
}
}
這是一個問題,因為您是在應用程序的UI線程上發出HTTP請求。 通常,您不想在UI線程上執行任何同步/阻塞IO,因為這會使您的應用程序無響應,並可能觸發可怕的“應用程序無響應”對話框。
Android以AsyncTask類的形式提供了針對此問題的簡單解決方案。 在您的情況下,您甚至不必擔心參數或結果,因為您似乎可以解決並忘記HTTP請求,並且只需將HttpGet
實例傳遞給AysncTask
的構造函數即可。
首先,您可以像下面這樣定義AsycnTask
的子類:
public static class CommandArduino extends AsyncTask<Void, Void, Void> {
private HttpUriRequest mRequest;
public CommandArduino( HttpUriRequest request ){
mRequest = request;
}
protected Void doInBackground( Void... ignore ){
new DefaultHttpClient().execute( mRequest );
return null;
}
}
然后,您可以將您的commandArduino
方法替換為:
new CommandArduino(new HttpGet(url)).execute();
關於此示例要注意的一件事是使用Void類來表明我們不在乎參數,進度或結果。 通常,您會做一些事情,例如使這些類型參數成為<URL, Integer, Integer>
類的東西<URL, Integer, Integer>
以便您可以傳遞URL
,使用Integers
顯示進度,以及獲取HTTP狀態代碼作為Integer
(或類似的方式) )。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.