我想向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請求的函數。
請幫忙。
據我所知,你試圖做一個同步請求,嘗試在AsyncTask中調用該方法,並查看是否有效。 –
你能舉個例子 –
Yu還可以創建一個IntentService並從BroadcastReceiver中調用它。 –