Reputation: 27
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;
}
}
Upvotes: 0
Views: 633
Reputation: 568
The sync adapter component in your app encapsulates the code for the tasks that transfer data between the device and a server. Based on the scheduling and triggers you provide in your app, the sync adapter framework runs the code in the sync adapter component. Here is the proper doc you must go through.
Upvotes: 0
Reputation: 2904
You should check this. GCM might be what you are looking for.
If you want to implement it manually. You can use BroadcastReceiver.
Hope this helps :)
Upvotes: 0
Reputation: 101
You can write a service doc link: http://developer.android.com/guide/components/services.html
and have that service poll your server repeatedly,but this approach is particularly bad and will consume unnecessary battery.
You can implement the notification other way around that is push notification(GCM) doc link: https://developers.google.com/cloud-messaging/ can then on getting the notification you can poll your server in app.
Upvotes: 2