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

TFS branch- marked as read only when mapped locally

visual-studio visual-studio-2010 tfs tfs2010

I had branched out from our QA branch on TFS, mapped it locally and tried making changes to the code locally. When trying to save my code changes, it gives me a warning saying that " the file is

How to use Autofac in a 3 layered web application (ASP.NET MVC)?

asp.net-mvc dependency-injection autofac

The examples I can find use a two layer architecture, where the controllers directly use the repository classes in the data access layer. See here or here.

How can I communicate over TCP sockets from JavaScript?

javascript ajax user-interface sockets

I'm thinking about how limiting it is for AJAX apps to have to poll for updates, when what would be ideal is for javascript to be able to set up a real two way connection to the server. I'm wonderi...

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.