gpt4 book ai didi

android - 我怎样才能保持每 5 秒请求一次页面而不耗尽电池电量?

转载 作者:太空宇宙 更新时间:2023-11-03 13:04:25 25 4
gpt4 key购买 nike

我正在开发的 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<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(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<String> all_sms = getBetweenAll(HTML, "<sms>", "<sms>");
for(int i = 0, size = all_sms.size(); i < size; i++) {
String from = getBetween(all_sms.get(i), "<from>", "</from>");
String to = getBetween(all_sms.get(i), "<to>", "</to>");
String msg = getBetween(all_sms.get(i), "<msg>", "</msg>");
String sent = getBetween(all_sms.get(i), "<sent>", "</sent>");
String HTML1 = "";
HttpClient httpclient1 = new DefaultHttpClient();
HttpPost httppost1 = new HttpPost("http://www.***.***/***/add_sms.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(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) {
}
}
}

}


}

最佳答案

为什么需要每 5 秒检查一次?您最好让服务器向设备推送通知(通过 c2dm),告知何时有更新可用。如果您持续轮询服务器,无论您如何实现,都会耗尽电池电量。

关于android - 我怎样才能保持每 5 秒请求一次页面而不耗尽电池电量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6847526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com