1

I'm trying to learn Android Service, I'm very noob. I'm creating a service which will run even after the app is destroyed but when I terminate the App, the Service gets terminated too. I'm trying to make a NotificationService, below is my code that I just tried working with Service.

Manifest:

<service
        android:name="com.test.testworks.MyService"
        />

Starting Service via Button Click:

startService(new Intent(this, MyService.class));

Service class MyService.class:

public class MyService extends Service {

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {


    /* 1. *//*ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);

   // This schedule a runnable task every 2 minutes
    scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
        public void run() {

        }
    }, 0, 10000, TimeUnit.SECONDS);*/


    /*  2. *//*final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {
            Toast.makeText(MyService.this, "suiubsibddubsuidv", Toast.LENGTH_LONG).show();
            handler.postDelayed(this, 10000); //now is every 2 minutes
        }
    }, 10000);*/


    return START_STICKY;

}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

} 

I'm checking on my phone where the other Services are running and when I terminate the App, the Service terminates also.

1 Answers1

1

On some phones, you need to add your app explicitly to the list of apps that are allowed to run in the background. Otherwise, Android will not restart your app if it is killed for whatever reason. There should be a settings page which lists installed apps and allows you to add them to this list. It is called "protected apps" on some devices. Especially devices from Xiaomi, LG, Huawei have this feature, but also other phones.

David Wasser
  • 93,459
  • 16
  • 209
  • 274
  • Yes, I'm using Xiami. I'll check and lwt u know about this. Thanks –  Jan 17 '17 at 18:07
  • I just checked for the permission, the app has permission to `Start in Background` but the Service is still terminating. –  Jan 17 '17 at 18:13
  • What version of Android is this? And how do you "terminate the app" – David Wasser Jan 17 '17 at 18:45
  • I'm using Xiami note 3, with android 6. Termination the app means killing the app after pressing home and swipe up to kill. –  Jan 17 '17 at 18:50
  • thanks it worked now. One more thing as u can see I commented out the 2 processes that I'm doing in `onStartCommand` which is calling a server method to check for new data from DB every 5minutes, is it a good practice, if yes which one is good. If no,Please let me know the alternate method for network calls every 5 minutes , I need help from experienced Sir like u. :) –  Jan 17 '17 at 19:10
  • Either of your methods is fine. There isn't any real difference. – David Wasser Jan 18 '17 at 08:34