[英]Fail to pause my android app
我希望我的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);
}
}
是我以前用來暫停程序的方式不正確,還是我將等待功能放在錯誤的位置?
收到服務器的響應后,我不知道要暫停一下了。 順便說一句,“停頓”到底是什么意思? 我無法想象有任何理由暫停應用程序。
您可能希望在服務器響應即將到來時(而不是之后)添加加載程序,並且可能還希望停用或隱藏按鈕。 在這種情況下,您應該在執行grap.execute之前進行更改,並刪除onPostExecute中的更改。
而且,我認為mCountUpdater正在創建一個無限循環。 因此,我將重新考慮該代碼。 考慮一下,Runnable.postDelay絕不會停止應用程序,它只是將某些Runnable的執行延遲了指定的時間,但與此同時,應用程序仍在運行。
如果您能更好地解釋該解決方案的需求,我可能會為您提供更多幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.