I know this is a basic question, I am new to android service. I have done research on Google and StackOverflow. There are many question in stackoverflow related to or similar to my topic, But I couldn't able to get the proper answer and I am being diverted to different topics.
This is the simple test code I am running.
public class Service extends android.app.Service {
private Handler mHandler;
private void ping() {
try {
Log.e("Tag", "Success");
Toast.makeText(getApplicationContext(), "Service Ping", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.e("Error", "In onStartCommand");
e.printStackTrace();
}
scheduleNext();
}
private void scheduleNext() {
mHandler.postDelayed(new Runnable() {
public void run() { ping(); }
}, 3000);
}
public int onStartCommand(Intent intent, int x, int y) {
mHandler = new android.os.Handler();
ping();
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
In this a Toast message pops up and Log message printed for every 3 seconds, It works even when the app is minimized. But when i completely quit the app, There is no Toast or Log printed. In this SO ANSWER in clearly says why Toast message cannot called without the UI. And I cannot print the LOG as the process is being killed.
Basically, I want the service to run in background for every 5 min and need to get the data from online. How should I implement the service? and any example code or tutorials are appreciated?
When you start a Service, by default it runs in the same process as whatever component started it. When the process that component is running in quits, so too does the Service. In order to start a Service in its own process, you need to do the following in the manifest:
<service
android:name=".Service"
android:enabled="true"
android:exported="false"
android:process=":separate_service_process"
android:stopWithTask="false" >
</service>
Putting a colon in front of the label for the android:process
attribute tells the system to start the service in a separate process, and the android:stopWithTask
attribute will tell the system to keep the service alive even when the component that started it stops. See http://developer.android.com/guide/topics/manifest/service-element.html for more information on the manifest settings (the stopWithTask
attribute is part of the ServiceInfo
class).
Now start your service using startService(Intent)
and you should be all set. Good luck!
PS--I'd recommend renaming your Service class to something unique to avoid confusion with the base Service class.