0

這裏是我的代碼,我給出了一個註釋行,錯誤發生在哪裏(在catch異常中)。任何人都可以幫忙非常感謝你。 代碼:檢查當前應用程序打開或關閉時的Android alarmreceiver錯誤

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.app.ActivityThread.handleReceiver啓動接收機android.os.NetworkOnMainThreadException (ActivityThread.java:2732) .... at android.app.ActivityThread.main(ActivityThread.java:5417) ... 引起:android.os.NetworkOnMainThreadException at 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

當應用程序嘗試在其主線程上執行聯網操作時,會引發此異常。在的AsyncTask或後臺線程中運行代碼

@Override 
public void onReceive(Context context, Intent intent) { 
    new Thread(new Runnable() { 
     @Override 
     public void run() { 
      //put your code here 
     } 
    }).start(); 
} 
相關問題