我的Android应用程序中有一个WakefulBroadcastReceiver,它已成功接收到设备的传入SMS。在此之后,我试图做的是使用Google Volley库向我的Web服务器提交请求。问题在于,Volley是异步完成这个Web请求的。因此,BroadcastReceiver中的“onReceive”方法代码在异步Web请求完成之前完成。我明白,当使用BroadcastReceiver与异步请求时,这是一个问题,但我通过服务(而不是直接在BroadcastReceiver中)发出请求,所以我不明白为什么会发生这种情况。如何在Android中执行来自BroadcastReceiver的异步Web请求
我收到以下NullPointerException异常,这我假设是因为广播接收器的情况下完成的请求之前已经被销毁:
11-04 19:13:43.465 32385-32441/com.niiche.pinch E/Volley﹕ [5542] NetworkDispatcher.run: Unhandled exception java.lang.NullPointerException
java.lang.NullPointerException
at libcore.net.UriCodec.encode(UriCodec.java:132)
at java.net.URLEncoder.encode(URLEncoder.java:57)
at com.android.volley.Request.encodeParameters(Request.java:456)
at com.android.volley.Request.getBody(Request.java:442)
at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:236)
at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:210)
at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:106)
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:96)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:110)
下面是代码WakefulBroadcastReceiver(SmsReceiver):
public void onReceive(Context context, Intent intent) {
//retrieve the SMS PDUs, from the intent extras
Bundle pdusBundle = intent.getExtras();
Object[] pdus = (Object[])pdusBundle.get("pdus");
//create sms message object from the PDU
SmsMessage message = SmsMessage.createFromPdu((byte[])pdus[0]);
Intent service = new Intent(context, SmsIntentService.class);
service.putExtra(SmsIntentService.EXTRA_SMS_MESSAGE, message.getMessageBody());
//start the service, keeping the device awake while it is launching
startWakefulService(context, service);
setResultCode(Activity.RESULT_OK);
}//End method
下面是Int entService(SmsIntentService):
protected void onHandleIntent(Intent intent) {
if (intent != null) {
Bundle extras = intent.getExtras();
if(!extras.isEmpty()){ // has the effect of unparcelling the bundle
String smsMessage = extras.getString(EXTRA_SMS_MESSAGE);
submitVolleyServerRequestAsync(smsMessage);
}//End if
}//End if
// Release the wake lock provided by the WakefulBroadcastReceiver
SmsReceiver.completeWakefulIntent(intent);
}//End method
任何可以在这里提供的援助非常感谢。提前致谢!
我不知道Volley,但是你需要从'IntentService'提供的后台线程同步执行你的HTTP调用**。否则,服务将会完成,你的'WakeLock'将在你的HTTP调用完成之前被释放。 – CommonsWare 2014-11-05 00:30:38