Note that there are some explanatory texts on larger screens.

plurals
  1. POAndroid: Start Async Task in OnReceive Method
    text
    copied!<p>I currently have a Service which manages a Broadcast Receiver. This receiver can be turned off and on.</p> <p>At the moment the OnReceive is triggered when a SMS is received. It then uploads the SMS to a server. The code works fine, but I heard from 3.0 above network connections need to be ran on Async task. Even if this isn't the case I would like to move the upload to another thread, so the upload task can't block the UI thread. (I have tired to move the Service to an IntentService, this causes the broadcast Receiver leak)</p> <pre><code> SMSBR = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { //START OF ONRECIVER************************ Bundle extras = intent.getExtras(); String strMessage = ""; if ( extras != null ) { Object[] smsextras = (Object[]) extras.get( "pdus" ); for ( int i = 0; i &lt; smsextras.length; i++ ) { SmsMessage smsmsg = SmsMessage.createFromPdu((byte[])smsextras[i]); String strMsgBody = smsmsg.getMessageBody().toString(); String strMsgSrc = smsmsg.getOriginatingAddress(); strMessage += "SMS from " + strMsgSrc + " : " + strMsgBody; Log.d("Message", "is "+strMessage); //*************************************************************** InputStream is = null; try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://mayar.abertay.ac.uk/~1001077/insert.php"); ArrayList&lt;NameValuePair&gt; nameValuePairs = new ArrayList&lt;NameValuePair&gt;(); nameValuePairs.add(new BasicNameValuePair("DeviceNumber", telephonyManager.getLine1Number().toString())); nameValuePairs.add(new BasicNameValuePair("SenderNumber", strMsgSrc)); nameValuePairs.add(new BasicNameValuePair("Message", strMsgBody)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); Log.d("is = ", is.toString()); Log.d("In SMS", "Sender success"); if (Looper.getMainLooper().getThread() == Thread.currentThread()) { Log.d("Message upload Running", "on UI"); } else { Log.d("Message upload NOT running", "on UIx"); } }catch (Exception e){ Log.e("Log_tag", "Error in http sms " + e.toString()); Log.d("In SMS", "Sender NOT success"); } //**************************************************************** } } //END OF ON RECEIVE**************************** } }; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload