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.