I am building an app that is gonna do request to server repeatedly and I want this task to run in background so that it won't stop even if the app is closed by the user. I mean I want something like what SocialMedia App does for its notification system.
This is what I've been trying.... app is gonna stops working... what I am doing wrong in this code?
public class MyService extends Service{
private boolean isRunning = false;
@Override
public void onCreate() {
Toast.makeText(this, "Service onCreate", Toast.LENGTH_SHORT).show();
isRunning = true;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service onStartCommand", Toast.LENGTH_SHORT).show();
// Creating new thread for my service
// Always write your long running tasks in a separate thread, to avoid ANR
new Thread(new Runnable() {
@Override
public void run() {
httpRequest();
if(isRunning){}
}
}).start();
return Service.START_STICKY;
}
public void httpRequest(){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mydomain/getData.php");
try {
String MyName = "Muhammad Sappe";
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("action", MyName));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
//This is the response from a php application
String reverseString = response;
Toast.makeText(this, "result : "+reverseString, Toast.LENGTH_SHORT).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onDestroy() {
isRunning = false;
}
}