php 等5秒钟继续,android – 如何每5秒钟继续请求一个页面而不是杀死电池?
我正在開發的我的Android應用程序需要每5秒在我的服務器上請求一個頁面,但我擔心這將是一個大電池消費者,有沒有更簡單的方法?我目前的方法是每5秒循環一次的服務:
protected void onHandleIntent(Intent intent) {
while (true){
long endTime = System.currentTimeMillis() + 5*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.***.***/***/request_sms.php");
String HTML = "";
try {
List nameValuePairs = new ArrayList(2);
nameValuePairs.add(new BasicNameValuePair("id", "1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HTML = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {} catch (IOException e) {}
if(HTML.indexOf("[NO TEXTS]") > 0) {
} else {
Vector all_sms = getBetweenAll(HTML, "", "");
for(int i = 0, size = all_sms.size(); i < size; i++) {
String from = getBetween(all_sms.get(i), "", "");
String to = getBetween(all_sms.get(i), "", "");
String msg = getBetween(all_sms.get(i), "", "");
String sent = getBetween(all_sms.get(i), "", "");
String HTML1 = "";
HttpClient httpclient1 = new DefaultHttpClient();
HttpPost httppost1 = new HttpPost("http://www.***.***/***/add_sms.php");
try {
List nameValuePairs = new ArrayList(2);
nameValuePairs.add(new BasicNameValuePair("from", from));
nameValuePairs.add(new BasicNameValuePair("to", to));
nameValuePairs.add(new BasicNameValuePair("msg", msg));
nameValuePairs.add(new BasicNameValuePair("sent", sent));
httppost1.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response1 = httpclient1.execute(httppost1);
HTML1 = EntityUtils.toString(response1.getEntity());
HN.post(new DisplayToast(HTML1));
} catch (ClientProtocolException e) {} catch (IOException e) {}
}
}
} catch (Exception e) {
}
}
}
}
}
解決方法:
基本上,您在服務器上注冊用戶設備,并且可以設置服務器以將通知推送到用戶設備.然后,您可以將客戶端更改為僅在服務器通知存在新數據時發出請求.
這應該很好,因為您幾乎不需要經常提出請求.你一定會以這種方式節省電池壽命.
標簽:android,request,http,sync,httpclient
來源: https://codeday.me/bug/20190903/1795612.html
總結
以上是生活随笔為你收集整理的php 等5秒钟继续,android – 如何每5秒钟继续请求一个页面而不是杀死电池?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: rhel6上使用udev配置oracle
- 下一篇: Oracle 安装完怎么用,oracle