I created a service and want to run this service always until my phone restarts or force closed. The service should run in background.
Sample code of created service and start services:
Start the service:
Intent service = new Intent(getApplicationContext(), MyService.class);
getApplicationContext().startService(service);
The service:
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO do something useful
HFLAG = true;
//smsHandler.sendEmptyMessageDelayed(DISPLAY_DATA, 1000);
return Service.START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO for communication return IBinder implementation
return null;
}
}
Manifest declaration:
<service
android:name=".MyService"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
</service>
Is it possible to run this service always as when the application pauses and anything else. After some time my application goes pause and the services also go pause or stop. So how can I run this service in background and always.
"Is it possible to run this service always as when the application pause and anything else?"
Yes.
In the service onStartCommand method return START_STICKY.
Start the service in the background using startService(MyService) so that it always stays active regardless of the number of bound clients.
Create the binder.
Define a service connection.
Bind to the service using bindService.
For your service you may want a notification to launch the appropriate activity once it has been closed.
You need to modify the manifest to launch the activity in single top mode.
Note that if the system needs the resources and your service is not very active it may be killed. If this is unacceptable bring the service to the foreground using startForeground.
In order to start a service in its own process, you must specify the following in the xml declaration.
Here you can find a good tutorial that was really useful to me
http://www.vogella.com/articles/AndroidServices/article.html
Hope this helps
You can implement
startForeground
for the service and even if it dies you can restart it by usingSTART_STICKY
onstartCommand()
. Not sure though this is the right implementation.