我希望我的 android 应用程序在收到来自服务器的响应后暂停一段时间。我正在使用以下代码来尝试暂停我的程序:
private Handler mHandler;
private Runnable mCountUpdater = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
mHandler.postDelayed(this, 15000);
}
};
但无论我以下面提到的任何一种方式调用等待,它都不起作用
1. 放在按钮处理程序中:
btnin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//set the values
grab.onPreExecute("TechID", Build.SERIAL);
grab.onPreExecute("Type", "Checkin");
//set the destination and send the request
grab.execute(new String[]{"http://192.168.1.150/Me/check.php"});
//close the activity
mHandler = new Handler();
mHandler.post(mCountUpdater);
finish();
}
});
2.放入AsynTask的onPostExecute()方法中:
private class GrabURL extends AsyncTask<String, Void, Void>{
//ArrayList object for storing the string pairs
ArrayList<NameValuePair> nameValuePairs;
public GrabURL() {
//constructor of the class
nameValuePairs = new ArrayList<NameValuePair>();
}
protected void onPreExecute(String key, String value) {
//store the pair of values into the ArrayList
nameValuePairs.add(new BasicNameValuePair(key,value));
}
@Override
protected Void doInBackground(String... urls) {
// TODO Auto-generated method stub
//Operation being executed in another thread
try{
//set up the type of HTTPClient
HttpClient client = new DefaultHttpClient();
//set up the location of the server
HttpPost post = new HttpPost(urls[0]);
//translate form of pairs to UrlEncodedFormEntity
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8);
//set up the entity being sent by post method
post.setEntity(ent);
//execute the url and post the values
//client.execute(post);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
line = EntityUtils.toString(resEntity);
} catch (Exception e) {
//catch the exception
line = "Can't connect to server";
}
return null;
}
protected void onPostExecute(Void unused) {
mRespond.setVisibility(View.VISIBLE);
mRespond.setText(line);
btnin.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "Value updated", Toast.LENGTH_SHORT).show();
mHandler = new Handler();
mHandler.post(mCountUpdater);
}
}
是我用来暂停程序的方式不正确还是我把等待功能放在了错误的位置?