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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值