Android service keeps running indefinitely - android

I'm trying to create a service in android which i want to keep running in background indefinitely. So I tried to create one like :
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, mssg, Toast.LENGTH_SHORT).show();
}
public int onStartCommand(Intent intent, int flags,int startid) {
Toast.makeText(this, mssg, Toast.LENGTH_LONG).show();
Log.d("Start:", "Service running");
// my code here
return START_STICKY;
}
But when I run this code, the toast messages and logs are only shown once , so does it mean service runs only first time. If it is running again n again which API of it is being called repeatedly ?
Thanks,
shadow.

Running a Service indefinitely and running the same piece of code again and again are two very different things. The piece of code you provided will allow the service to be running the background as long as the Android system doesn't decide to stop it.
Not sure what functionality you are looking to implement, but i suggest you read up on what exactly a Service is used for and what your requirements are.

i suggest you change return START_STICKY;
with return START_NOT_STICKY;
as details given in documentation here.

Related

Reasons why a service could be stopped in android

If I have an app that does not have any activities, just one BOOT_COMPLETED broadcast receiver and the simplest service. The receiver will just start the service and the service will just ran the following code:
public class ScreenStateService extends Service {
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
}
}
As as I understand, the service would ran until the end of time or until one of the following scenarios occurr:
Low memory: The system is running low on memory so it decides to stop the service.
ANR
The user manually stops the application or disables it.
In 1 and 2 the system would start the service again, after memory is no longer low or after the error is handled. In the case of 3 it wont be started again.
The question is: is the above right? Are there any other cases where the service would be stopped by an outside source? Please specify if it would be started again automatically if there are any.

keeping a service running after shutting down the app

i'm trying to create an app that communicates with my localhost and search in a database.
I already make the connection and find the data, but i need to stay connected and send a notification if there's any changes in the table, but I can't figure it out how to keep the connection even when I close the app, because it closes everything, even the service.
The service doesn't stay open.
This is my Class:
public class SensorService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this,"Starting",Toast.LENGTH_SHORT).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
boolean bandera = true;
Toast.makeText(this, "Checking data...", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
stopService(new Intent(this,SensorService.class));
startService(new Intent(this,SensorService.class));
}
#Override
public void onDestroy() {
startService(new Intent(this,SensorService.class));
}
}
Every time I close the app, the service execute one more time and no more.
If you want the service to continue running after the app is closed, you need to call the startForeground(int, Notification) method from within the service. Android limits you to running longer running services in the background only as long as a notification is displayed to the user letting them know that a service is running (like a music player or a downloading service).
This is an intentional design constraint to ensure developers do not start services in the background that run indefinitely without the user being aware. Supply your own notification (can be anything) and you should be able to run the service in the background.
For more detailed information on this method, read it at: startForeground(int, Notification)
You can use onTaskRemoved and restart the service if needed.
#Override
public void onTaskRemoved(Intent rootIntent){
super.onTaskRemoved(rootIntent);
//restart your service
}
Please note that if you use onTaskRemoved, start your service as not sticky so it won't be restarted.
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
return START_NOT_STICKY;
}

ANDROID : Reboot android device when my service killed/crashed

I have seen the default behaviour of many services, that they are restarted when killed by system or user.
Is it possible that if my service is killed or crashed the android device is rebooted instead of my service itself being restarted.
If so, then have android provided some mechanism that we can use to achieve the above.
First of all, it is really very bad pattern to reboot device on service destroy.
Anyways, you can achieve this using below code
public class demoService extends Service
{
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
}
#Override
public void onDestroy() {
super.onDestroy();
// this won't restart your phone instead it will ask for action
Intent i = new Intent("android.intent.action.ACTION_REQUEST_SHUTDOWN");
i.putExtra("android.intent.extra.KEY_CONFIRM", true);
startActivity(i);
}
}

Stop the Service after the Vibrating the Phone in android?

I am trying to learn service in android.My goal is like that i will pass a LatLng Object to the service then service will do something with that and when the work will be finished then it will buzz the phone for sometime and stop.Finally the service will be finished.Now I have some query on that:
I will call the service from my app and user can close my app though
service is not finished.will service do the job initiated by my app or
it will also finish??
What i studied take me here that service will continue to execute and one thing i don't have to return anything back to activity who has initiated the service.I have written some code.Can anyone help me out??
public class MapService extends Service {
private boolean isRunning = false;
#Override
public void onCreate() {
Log.i(TAG, "Service onCreate");
isRunning = true;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Service onStartCommand");
//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() {
//here i will do my work
if(isRunning){
Log.i(TAG, "Service running");
}
}
//Stop service once it finishes its task
stopSelf();
}
}).start();
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
Log.i(TAG, "Service onBind");
return null;
}
#Override
public void onDestroy() {
isRunning = false;
Log.i(TAG, "Service onDestroy");
}
}
Will it work if user closes the app??
Yes this service will run even if user will close app.It is also possible if android system demands memory service will be stopped but it will restart again
as you have set your flag START_STICKY in your onStartCommand.
On Android KitKat and above(4.4+), the service will be stopped if user swipe kills the application and it won't be restarted by the system. See this discussion(1). If the application was stopped by Android system itself (for low resources), the service will be restarted after a while(use START_STICKY flag).
On Android 4.3 and below, service will be restarted irrespective of whether application was stopped by system or user(use START_STICKY flag).
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// We want this service to continue running until it is explicitly stopped, so return sticky.
return START_STICKY;
}

ANR when I am starting a service

I am using a service to download heavy files from the web.but when the files are being downloaded I am unable to interact with the app. What is the best way for this .
I am downloading files that are about 10 MB and I want the user to interact with app while the files are downloaded
Please find the my service code.
public static class MyService extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public MyService(){
super();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
System.out.println("service started");
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
//Toast.makeText(Description.this, "Downloading content...", Toast.LENGTH_LONG);
GetShowsInfo(downloadEpisodeMedia(episode_id));
RequestDownloads();
File cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"Folder Name");
listf(cacheDir,files);
mediaPlayerflag=true;
//progressBarLayout.setVisibility(LinearLayout.VISIBLE);
nowPlayingEpisode=categoryName;
//NowPlayingEpisode.setText("Now Playing "+episodeArrayList.get(position).getName());
textView_MediaPlayer.setText(nowPlayingEpisode);
//textView_EpisodeCount.setText(episodeCount);
playOnebyOneMedia();
// StoreInfo(GetCategories());
//StoreDescription(GetDescription());
return START_STICKY;
}
#Override
public void onDestroy() {
System.out.println("service stopped");
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
I think you are performing very large operations on the UI thread like downloading files..ANR comes when the UI thread perform the long running operations..try to do it with using AsynchTask or threads..then you can avoid ANR..
check this link for download file in AsynchTask example..AsynckTask example
You can use IntentService instead of Service. IntentService uses a separate thread to handle intents. So it wont block your main thread. onStartCommand method of your service runs in main thread and blocks it for too long time and causes ANR.

Categories

Resources