I am developing an application which connects to a web service via the internet and gets some information and I've used Async task for this in two activities. Now I want to use the same code in a service class which works with Timer task and on every tick, if the application is not running, it should return some data from web service. I can retrieve data when the app is open, but when I close it, I get "Connection to foo.com is refused"!
I have uses-permission android:name="android.permission.INTERNET" in my Android manifest.
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
//use a handler to run a toast that shows the current timestamp
handler.post(new Runnable() {
public void run() {if(!isAppRunning(getApplicationContext(),getPackageName())) {
new ExecuteTask().execute();
}
}
});
}
};
}
class ExecuteTask extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onCancelled() {
super.onCancelled();
}
@Override
protected String doInBackground(String... params) {
String res1="";
try {
res1 = PostData();
} catch (Exception ex) {
}
return res1;
}
@Override
protected void onPostExecute(String result) {
if (!isCancelled()) {
Log.d("responsed", result);
try {
int Ifrom = result.indexOf("[");
int ITo = result.lastIndexOf("]");
if (Ifrom > -1 && ITo > -1) {
result = result.substring(Ifrom, ITo + 1);
Log.d("test", result);
}
android.util.JsonReader reader = new android.util.JsonReader(new StringReader(result));
reader.setLenient(true);
Type listType = new Type() {
};
listType = new TypeToken<List<Alarms>>() {
}.getType();
List<Alarms> lstAlarms = new ArrayList<Alarms>();
lstAlarms = new Gson().fromJson(result, listType);
//if there is new alarm then show notifications
if(lstAlarms.size()>0)
} catch (Exception ex)
{
}
}
}
}
public String PostData() {
String s = "";
try {
HttpClient httpClient = new DefaultHttpClient();
String Url = "";
Url = settingsWeb.getString("Address", null);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("JsonQuery",Command);
Url += "/SelectJsonAlarms";
HttpPost httppost = new HttpPost(Url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httppost);
s = readResponse(response);
} catch (Exception e) {
return "error";
}
return s;
}
I get the error on this line ==> HttpResponse response = httpClient.execute(httppost);