Android: Start Async Task in OnReceive Method

I currently have a Service which manages a Broadcast Receiver. This receiver can be turned off and on.

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)

          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 < 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<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                                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****************************
            }


          };

Answers


Let me answer your question without talking about AsyncTasks: Take a look at

BroadcastReceiver.registerReceiver (BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler)

I found that while I was checking some documentation on BroadcastReceivers and looks like exactly what you need (check this link). One more hint: use it in combination with a HandlerThread.


Need Your Help

Use publications or separate into collections (performance)?

mongodb meteor

I have a collection, in which only two queries are ever called on it.

Get the value of a specific array number in relation to a given value

c# arrays

I am trying to determine what the neighbour bets would be for a given number on a roulette wheel.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.