2014-01-08 75 views
3

我想向BroadcastReceiver的OnReceive事件上的URL發送HTTP POST請求,但我收到異常NetworkOnMainThreadException,如何在OnReceive事件上運行線程。如何在BroadcastReceiver事件上發送HTTP POST請求OnReceive事件

public void onReceive(Context context, Intent intent) { 
    final Bundle bundle = intent.getExtras(); 
    try 
    { 
     if (bundle != null) { 
      final Object[] pdusObj = (Object[]) bundle.get("pdus"); 
      for (int i = 0; i < pdusObj.length; i++) { 
       SmsMessage currentmessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]); 
       String phonenumber = currentmessage.getDisplayOriginatingAddress(); 

       String senderNum = phonenumber; 
       String message = currentmessage.getDisplayMessageBody(); 

       String msg = message.substring(5); 

       Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + msg); 

       int duration = Toast.LENGTH_LONG; 
       Toast toast = Toast.makeText(context, "senderNum: "+ senderNum + ", message: " + msg, duration); 
       toast.show(); 
       sendhttprequest("http://example.com/product", "rl", "12345678");      
      } 
     } 
    } 
    catch (Exception e) { 
     Log.e("SmsReceiver", "Exception smsReceiver" +e); 

    }  

} 

sendhttprequest是用來調用http post請求的函數。

請幫忙。

+1

據我所知,你試圖做一個同步請求,嘗試在AsyncTask中調用該方法,並查看是否有效。 –

+0

你能舉個例子 –

+0

Yu還可以創建一個IntentService並從BroadcastReceiver中調用它。 –

回答

1

這個例子可以幫助你:

public void onReceive(Context context, Intent intent) { 
    final Bundle bundle = intent.getExtras(); 
    try { 
     if (bundle != null) { 
      final Object[] pdusObj = (Object[]) bundle.get("pdus"); 
      for (int i = 0; i < pdusObj.length; i++) { 
       SmsMessage currentmessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]); 
       String phonenumber = currentmessage.getDisplayOriginatingAddress(); 

       String senderNum = phonenumber; 
       String message = currentmessage.getDisplayMessageBody(); 

       String msg = message.substring(5); 

       Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + msg); 

       int duration = Toast.LENGTH_LONG; 
       Toast toast = Toast.makeText(context, "senderNum: "+ senderNum + ", message: " + msg, duration); 
       toast.show(); 
       new NetworkAccess().execute(); // Call AsyncTask     
      } 
     } 
    } 
    catch (Exception e) { 
     Log.e("SmsReceiver", "Exception smsReceiver" +e); 
    }  

    public class NetworkAccess extends AsyncTask<Void, Void, Void>{ 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      // call some loader 
     } 
     @Override 
     protected Void doInBackground(Void... params) { 
      // Do background task 
      sendhttprequest("http://example.com/product", "rl", "12345678"); 
      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 

      super.onPostExecute(result); 
      // dismiss loader 
      // update ui 
     } 
    } 
} 
+0

謝謝老兄,這應該對我有幫助。 –