php 等5秒钟继续,android – 如何每5秒钟继续请求一个页面而不是杀死电池?
我正在開(kāi)發(fā)的我的Android應(yīng)用程序需要每5秒在我的服務(wù)器上請(qǐng)求一個(gè)頁(yè)面,但我擔(dān)心這將是一個(gè)大電池消費(fèi)者,有沒(méi)有更簡(jiǎn)單的方法?我目前的方法是每5秒循環(huán)一次的服務(wù):
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) {
}
}
}
}
}
解決方法:
基本上,您在服務(wù)器上注冊(cè)用戶設(shè)備,并且可以設(shè)置服務(wù)器以將通知推送到用戶設(shè)備.然后,您可以將客戶端更改為僅在服務(wù)器通知存在新數(shù)據(jù)時(shí)發(fā)出請(qǐng)求.
這應(yīng)該很好,因?yàn)槟鷰缀醪恍枰?jīng)常提出請(qǐng)求.你一定會(huì)以這種方式節(jié)省電池壽命.
標(biāo)簽:android,request,http,sync,httpclient
來(lái)源: https://codeday.me/bug/20190903/1795612.html
總結(jié)
以上是生活随笔為你收集整理的php 等5秒钟继续,android – 如何每5秒钟继续请求一个页面而不是杀死电池?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: rhel6上使用udev配置oracle
- 下一篇: 动态规划算法php,php算法学习之动态