这是我的代码,我给出了错误发生的注释行(在catch异常中)。有人可以帮忙吗?非常感谢你。 代码:
public class AlarmReceiver extends BroadcastReceiver {
XMLRPCClient client = null;
private DBclass db;
int flagPass = 0;
@Override
public void onReceive(Context context, Intent intent) {
// For our recurring task, we'll just display a message
try{
// Create an object to represent the server.
client = new XMLRPCClient(new URL("...server.php"));
if(intent.getStringExtra("ID").equalsIgnoreCase("ON")){
try {
int flag = 0;
try {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> task = am.getRunningAppProcesses();
for (int i = 0; i < task.size(); i++) {
if (task.get(i).processName.equalsIgnoreCase("com.example.test")) {
flag = 1;
break;
}
}
}catch (Exception ex){
flag = 0;
}
if(flag == 0){
HashMap<String, String> params = new HashMap<String, String>();
params.put("COMMAND", "ACON");
try {
// update buffer
client.call("updateDataCommand", params);
} catch (XMLRPCException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception ex) {
// error here, always catched here
flagPass = 1;
}
if(flagPass == 1){
HashMap<String, String> params = new HashMap<String, String>();
params.put("COMMAND", "ACON");
// program error here (apps forced close), unfortunately...
try {
// update buffer
client.call("updateDataCommand", params);
} catch (XMLRPCException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这是错误消息: java.lang.RuntimeException:无法启动接收器android.os.NetworkOnMainThreadException 在android.app.ActivityThread.handleReceiver(ActivityThread.java:2732) .... 在android.app.ActivityThread.main(ActivityThread.java:5417) ... 引起:android.os.NetworkOnMainThreadException 在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273) at java.net.InetAddress.lookupHostByName(InetAddress.java:431) at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
答案 0 :(得分:0)
当应用程序尝试在其主线程上执行网络操作时,抛出此异常。在AsyncTask或后台线程中运行代码
@Override
public void onReceive(Context context, Intent intent) {
new Thread(new Runnable() {
@Override
public void run() {
//put your code here
}
}).start();
}