2

After reading a lot of topics on SOF & blog post, I have got the BroadcastReceiver working. But I have noticed sometime it does not work, specially when I am on call. I just want to know, does BroadcastReceiver work if I get SMS in-between the call ? or there is something is wrong in the code.

SmsReceiver.java

public class SmsReceiver extends BroadcastReceiver {

public void onReceive(Context context, Intent intent) {

    Log.d("SmsReceiver Broadcast", "OK");

    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

    if (networkInfo != null && networkInfo.isConnected()) {
        Log.d("Network is connected. Executing TheTask()", "OK");

    new TheTask().execute("http://somedomain.tld/index.php?userId=12345678");

    }

    if (networkInfo == null) {

        Log.d("Network is NOT connected.", "FAIL");
    }

}

class TheTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... arg0) {
        String text = null;
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(arg0[0]);
            HttpResponse resp = httpclient.execute(httppost);
            HttpEntity ent = resp.getEntity();
            text = EntityUtils.toString(ent);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return text;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

        String tocheck = "Some text";
        if(result.contains(tocheck))
        {
            Log.d("string contains some text", result);
        }
    }
}
}

AndroidManifest.xml

        <receiver android:name=".SmsReceiver" android:enabled="true" >
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>

I am using 3G network. It may be due to network disconnects. If so, is there any workaround to execute AsyncTask when my phone again get data network ?

EDIT:

Wrapped the AsyncTask into isConnected. Now if the phone is not connected to Internet & I get SMS the AsyncTask will not be executed. In that situation I want to use ScheduledExecutorService to schedule AsynckTask to be executed 4 times at the interval of 5 minutes within next 20 minutes. I will be highly obliged anyone can help me in this.

Amandeep Singh
  • 276
  • 2
  • 13

1 Answers1

2

I cannot be sure about the disconnects since you haven't provided any stack trace. But I am pretty sure the SMS_RECEIVED broadcast action is being broadcasted system-wide when you receive sms. Now if you do not receive SMS due to bad connection or no connection at all it's perfectly logical for the system not to trigger an SMS_RECEIVED action since no SMS was received.

As for the

is there any workaround to execute AsyncTask when my phone again get data network

you can implement another Broadcast Receiver that will listen for network changes but that doesn't seem such a good idea. You should try and reproduce the problem and check for any exceptions in your stack trace.

is something is wrong in the code.

Your receiver seems to be properly registered in your manifest, the onReceive() method seems to be properly launching the AsyncTask, the doInBackground doesn't seem to have any problem and onPostExecute (although the official example seems to omit any call to super) seems to be just fine.

Conclusion: Try to reproduce the problem and gather data from the stack trace as to what might cause the error (network overhead might be one the causes but that's just speculation).

George Daramouskas
  • 3,720
  • 3
  • 22
  • 51
  • 1
    I am sorry, I am not good in English. I really appreciate your effort for answer. – Amandeep Singh Mar 01 '15 at 14:37
  • I am sorry, I am not good in English. I really appreciate your effort for answering. Here, I am again explaining the problem which I am facing. I am trying to execute AsyncTask whenever I get SMS. The code is working perfectly when my phone's Mobile Data is ON & when in Wi-Fi range. But while driving or inbetween the call, sometimes Mobile Data may be disconnected. In that case I want to postpone the AsyncTask call to execute when my phone comes in Wifi range or get connected to Mobile Data. Ofcourse SMS_RECEIVED is being triggered each and every time a SMS is received. – Amandeep Singh Mar 01 '15 at 14:49
  • 1
    Try using NetworkInfo.isConnected() to see if there's an active network connection: http://developer.android.com/reference/android/net/NetworkInfo.html#isConnected() – Buddy Mar 01 '15 at 15:48
  • Thank you Buddy, I am modifying the code. Will come back with updated code. – Amandeep Singh Mar 01 '15 at 15:51
  • 1
    When your BroadcastReceiver receives the SMS_RECEIVED broadcast you can check whether you have an internet connection. If yes proceed initiating an internet connection. If not, save the info you want to save from the received SMS then use a http://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html to be executed at a later time to re-check for internet connection and re-initiate an internet connection. – George Daramouskas Mar 02 '15 at 08:50
  • Thank you @George D and **Buddy** for posting your valuable comments. From your suggestion, I have wrapped **AsyncTask** into **isConnected** statement. Till now the code is working perfectly while I my phone is connected to WiFi. The only problem which is stopping **AsyncTask** from executing is broken network signal (Mobile Data Connectivity) As suggested by **George D**, I searched a lot about **ScheduledExecutorService** But I could not get how to use it in my code. I am new to Android programming, so any code suggestions will help me a lot. Plz check my updated post – Amandeep Singh Mar 10 '15 at 18:04