gpt4 book ai didi

java - 无法在Android代码中的Alarm OnReceive方法上执行select.php

转载 作者:行者123 更新时间:2023-12-01 12:27:10 24 4
gpt4 key购买 nike

我在android应用程序中有MainActivity.java

因为我有 setRepeatingAlarm() ,它在每 120sec 后执行一次,并执行 select.php 来检查表中是否可用的名称。

public void setRepeatingAlarm() {
Intent intent = new Intent(MainActivity.this, TimeAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);

am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+120000,
(120000), pendingIntent);
}

广播接收器:

public class TimeAlarm extends BroadcastReceiver {

public void onReceive(Context context, Intent intent) {
//get select query data
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.myweb.com/select.php");

HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
if(is != null) {
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);

Notification noti = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("mytestapp")

.setContentTitle("mytestapp")
.setContentText("Please check new update!")
.setContentIntent(contentIntent)
//At most three action buttons can be added
.setAutoCancel(true).build();
int notifyID =0;
notificationManager.notify(notifyID, noti);
}

is.close();
} catch(Exception e) {

}
}
}

but i'm unable to execute HttpResponse response = httpclient.execute(httppost); goes into catch block . not getting any error details :(

select.php 给出类似 {"name":"mynametest"} OR null

的输出

请告诉我这里出了什么问题

最佳答案

根据我对您的问题的评论 - 您可以将网络代码移至 IntentService 中,然后只需从您的 BroadcastReceiver 启动它即可。 IntentService 中的所有工作均由运行 onHandleIntent(...) 方法的工作线程处理,因此在其中执行网络任务是安全的。

IntentService:

public class MyIntentService extends IntentService {

// You must have a parameter-less ctor for an IntentService
public MyIntentService() {
super("MyIntentService");
}

public MyIntentService(String name) {
super(name);
}

@Override
protected void onHandleIntent(Intent intent) {

// This method is run on a separate worker thread so it's
// safe to put all of your network code here

}
}

BroadcastReceiver onReceive(...) 方法中当前的所有内容复制到您的 onHandleIntent(...) 方法中IntentService 并将其替换为启动服务的代码,如下所示...

public class TimeAlarm extends BroadcastReceiver {

public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, MyIntentService.class);
context.startService(i);
}
}

关于java - 无法在Android代码中的Alarm OnReceive方法上执行select.php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26238354/

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