3

I want to send a HTTP POST request to a URL on OnReceive event of BroadcastReceiver, but I'm getting the exception NetworkOnMainThreadException, How to run a thread on OnReceive event.

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 is the function which is used to call http post request.

Please help.

Able Alias
  • 3,824
  • 11
  • 58
  • 87

2 Answers2

4

Remember that the BroadcastReceiver could be killed by the system once the onReceive() returns. That means any work offloaded to an asynctask/thread is not guaranteed to be finished. Consider calling BroadcastReceiver:goAsync() to keep the process alive for at most 10 sec. Read more here: http://developer.android.com/reference/android/content/BroadcastReceiver.html#goAsync()

pareshgoel
  • 981
  • 8
  • 12
  • It's actually up to 30 seconds if the sending intent doesn't use the FLAG_RECEIVER_FOREGROUND flag. https://developer.android.com/reference/android/content/BroadcastReceiver#goAsync() – Florian Walther Feb 17 '19 at 18:38
1

This example might help you:

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();   
                new NetworkAccess().execute(); // Call AsyncTask                
            }
        }
    }
    catch (Exception e) {
        Log.e("SmsReceiver", "Exception smsReceiver" +e);
    }       

    public class NetworkAccess extends AsyncTask<Void, Void, Void>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // call some loader 
        }
        @Override
        protected Void doInBackground(Void... params) {
            // Do background task
            sendhttprequest("http://example.com/product", "rl", "12345678");
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

            super.onPostExecute(result);
            // dismiss loader 
            // update ui 
        }
    }
}
orhankutlu
  • 820
  • 8
  • 20
Faraz Ahmed
  • 1,245
  • 1
  • 14
  • 24