Restart the service even if app is force-stopped and Keep running service in background even after closing the app How?
Asked Answered
A

7

18

I am trying to run a service in the background. What my app does is when user checks checkbox then service starts and when it is unchecked service is stopped. Which is working perfectly fine. But the problem is when I closed the app from task manager it then also stops the service. What I want is to keep the service running even after it is close from task manager. Then only way to stop that service is by user himself by unckecking the box.

How can I achieve this?

Here is my code

My main activity

public class SampleServiceActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final CheckBox cb = (CheckBox) findViewById(R.id.checkBox1);

    cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {

            if(isChecked) {
                Toast.makeText(getBaseContext(), "Checked", Toast.LENGTH_LONG).show();
                startService(new Intent(getBaseContext(), MyService.class));
            } else {
                Toast.makeText(getBaseContext(), "Unchecked", Toast.LENGTH_LONG).show();
                stopService(new Intent(getBaseContext(), MyService.class));
            }
        }

    });
}
}

My service class

public class MyService extends Service {
Notify n = new Notify();
@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    n.initNotification(getBaseContext(), true);
    return START_STICKY;
}

//method to stop service
public void onDestroy() {
    super.onDestroy();
    n.cancelNotification(getBaseContext());
    Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
}

Update

How can we make this service so that it runs like gtalk service?

Agitate answered 20/5, 2012 at 7:4 Comment(1)
Have you maybe found out anything? I am also looking for a way to start my alarm application after it is force stopped. Example of application that can do that succesfully would be Alarm Clock XtremeSpanish
T
21

I am not sure which 'Task Manager' you are referring to as different ones would act differently, so I am basing my answer on the action when the user goes to Settings-->manage Applications and--> force stops the app the way android has given him.

Assuming that your service is running as part of the process and if the user force-stops your process, you are prevented from ever running the service again until the user manually launches you.This is especially valid from 3.0 and above version ( check for yours). It also seems logical when you think that there is an app which keeps a service started all the time and is annoying the user in some way. So when the user orders a hit ( :) force-stops) on the app, it should not restart the service to continue bugging the user.

For instance, Imagine what would happen if you could create apps which just ate at your processor time by holding a wake lock, and you couldn't kill them. This would be horrible and a huge security disaster.

So, you will not be able to restart your service by any means until the user launches one of your activities.

Also you cannot disable the force-stop button AFAIK. You should take the viewpoint that nothing on the device is yours to control besides your app and (to a limited extent) the resources to which you're granted access.

Finnally, even the gtalk app will bend to your will if you desire to force stop. It will start only when you use Gtalk or other apps which use the gtalk service such as PUSH Gmail ( for phones where gtalk isnt a part of firmware). Also take a look at Android C2DM here:

https://mcmap.net/q/245656/-how-does-whatsapp-service-gets-restarted-even-if-i-force-stop-app

Thaumaturge answered 22/5, 2012 at 18:36 Comment(13)
You make great points, but I don't really get how its not possible. In 4.0 (ICS), Google's calendar app still activates notifications even when I force close it. I would also like to know how to accomplish this. Any ideas?Epithet
@Epithet Have you maybe found out anything? I am also looking for a way to start my alarm application after it is force stopped. Example of application that can do that succesfully would be Alarm Clock XtremeSpanish
some apps have different level of system permissions. google calendar would be a part of firmware or have that permission. It is different from other apps by way of its certificate and permissionsThaumaturge
@Spanish unfortunately it does not look like you can do anything about this. Akhil makes good points, so I just gave up. I essentially set up my app with a BroadcastReceiver rather than a Service, and have an alarm run which runs the BroadcastReceiver. What you can do is have your app run some code when the device is turned on to get your stuff initialized if anything is needed. Otherwise, when the user force closes, its the word of the Android gods to not run it. Best thing I suggest is have the user add your app in their ignore list for task killers.Epithet
This answer is incorrect. See START_REDELIVER_INTENT and START_STICKY.Stevenson
@SofiSoftwareLLC : these constants are used when the run time kills the service due to resource crunch.If the user manually force stops the application in 2.3 and above, the services cant restart automatically.Thaumaturge
@Akhil: As I interpreted, you are saying the service can't be restarted, right? I want to ask if the service is still running, will it stop also?Vesiculate
@PradeepMittal: yes, the service will be stoppedThaumaturge
Do you know which method of service is called when we force stop it? So that we can set a flag on starting of the app to start the service or not..Saxhorn
You can periodically try to restart your service with AlarmManager.Lotion
Alarms are dismissed after a force-stop, in that regard answer is valid. However if you try to force stop apps like GMail, G+, etc, those will be restarted anyway! I believe the account synchronization is a mechanism beyond force-stop. That's one way to keep a background service running at all times.London
@Thaumaturge : you are wrong, i tried with moto g running 5.0.2 os, forcestoped Facebook app, but its service restarted after ~30-50 min., please not, checked this without a wifi/ data connection, so no gcm notification came on this timeSinaloa
i removed the Facebook Account and tried again, i this case also it recreated its service, after some timeSinaloa
L
6

I think this link will help you.
Disable force stop button in manage application

Its disable the Force Stop button in Package Installer setting so, no one can stop your application.

Lashonda answered 2/9, 2013 at 6:44 Comment(2)
Yes it's working Prasahant but can you tell me how can i enable it now and if i want to uninstall then what i have to do ?Cinchonism
@Pankaj: If you want to enable it again then go to Settings -> Security -> Device Administrator -> and deselect the checkbox of your application.Lashonda
S
2

You cannot prevent your service from being killed under all circumstances. However, you can ask the system to restart it. There are two cases: (1) the process dies for some abnormal reason (2) the phone reboots. In the former, START_STICKY or START_REDELIVER_INTENT are used to restart the service. In the latter, you'll need to add a BroadcastReceiver for android.intent.action.BOOT_COMPLETED.

Your code is returning START_STICKY from onStartCommand, so you've chosen one of the service restart paths: "if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service..."

"This mode makes sense for things that will be explicitly started and stopped to run for arbitrary periods of time, such as a service performing background music playback."

You can also use START_REDELIVER_INTENT.

Note that if your service is doing any significant work, it needs to run in a background thread.

http://developer.android.com/reference/android/app/Service.html#START_STICKY

Stevenson answered 22/2, 2013 at 0:14 Comment(0)
W
1

I'm not entirely sure you can prevent your app from being closed by the TaskManager. If you think about it, it makes sense for it to be that way. Imagine that you have an app that fails to respond to user input and also fails to respond to being killed by the Task Manager. Not good. However I found this question which is in a similar vein to yours. Also you can have the system automatically re-start your Service as described here (scroll down on that page a little to just before 'starting a service'

Willette answered 20/5, 2012 at 8:16 Comment(3)
My question is that the app can be closed from the task manager but its service should not. The service, which is started from that app, can only be closed manually by user.Agitate
Or second way could be that the app should not be visible in task manager at active application tab. So it cannot be closed from there. Just like Gtalk. When we install gtalk and once we sign in then it does not appear in active applications tab in task manager. But it runs in the background.Agitate
Well, it's like a task manager on your desktop. It also allows you to kill system apps. So, I don't see a reason why you would try to avoid being getting killed. I mean, Gmail services also allows itself to be killed. I guess you have to live with that.Libertinism
A
1

use my method if you want to start a hidden app for just first time I make a transparent Launcher activity like this

<activity android:name=".MainActivity"
    android:label="@string/app_name"
    android:theme="@style/Theme.Transparent"
    android:excludeFromRecents="true"
    >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

So I make the app hidden in launcher by placing this code in oncreat() [Code]

PackageManager p = getPackageManager();
    ComponentName componentName = new ComponentName(this, MainActivity.class); // activity which is first time open in manifiest file which is declare as <category android:name="android.intent.category.LAUNCHER" />
p.setComponentEnabledSetting(componentName,PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

So I use this code for show app icon on launcher and make it run able on service class that use broadcast receiver boot and in network connection broadcast receiver class too(autostart.java and networkConnectinCheck.java):

PackageManager p = context.getPackageManager();
    ComponentName componentName = new ComponentName(context, MainActivity.class);
    p.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);

Now I can run app for first time by user hands and after this I use my receiver's to lunch app any time.

Achitophel answered 2/9, 2017 at 1:53 Comment(0)
M
0

Let your Service run in a separate process. There is a good tutorial in this blog.

You can specify the android:process attribute in <Service> tag to make your app run within its own process.

<service
android:name="MyServiceName"
android:process="my_process" 
android:icon="@drawable/icon"
android:label="@string/service_name"
>
</service>
Misunderstanding answered 23/5, 2012 at 18:54 Comment(1)
But doesn't the "Force Stop" kill all processes associated with an application?Jarrettjarrid
R
-1

You can try to restart service on onDestroy event of service. Use some flags to find if service is closed by the User or its force closed.

Note that there is not guarantee that onDestroy will be called everytime.

Reunionist answered 25/5, 2012 at 6:30 Comment(1)
There is not guarantee that onDestroy will be called everytime. See this #7237282Misunderstanding

© 2022 - 2024 — McMap. All rights reserved.