7

START_STICKY don't work in my device whenever i kill my app then service don't start again, My device name is Redmi Note 3 Pro, but whenever i run same app in android emulator, it restarts the service when i kill the app and service don't stops until i stop it by stopService() method

please help me out

Problem Solved

Done this:

setting >Permissions>Autostart then turned on the Switch of my app, and Done!

I got solution in this link: Solution Link

LEGEND MORTAL
  • 336
  • 3
  • 18

3 Answers3

9

You need to add "android:process=:any_name" in the manifest under the inside the service attributes.

For example,

      <service android:name=".MyService"
        android:process=":MyService"
        android:enabled="true"/>

Below is the code of my Service class.

public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}


@Override
public void onCreate() {
    super.onCreate();
    Log.e("onCreate", "onCreate");
    Toast.makeText(AppController.getInstance(),"Created",Toast.LENGTH_SHORT).show();
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.e("servicedestroy", "servicedestroy");
    Toast.makeText(AppController.getInstance(),"service destroy",Toast.LENGTH_SHORT).show();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Timer t = new Timer();
    t.scheduleAtFixedRate(new TimerTask() {
                              @Override
                              public void run() {

                                  new Handler(Looper.getMainLooper()).post(new Runnable() {
                                      @Override
                                      public void run() {
                                          Toast.makeText(AppController.getInstance(),"Running",Toast.LENGTH_SHORT).show();
                                      }
                                  });


                              }

                          },
            0,
            5000);

    return START_STICKY;
}

@Override
public void onTaskRemoved(Intent rootIntent) {
    Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
    restartServiceIntent.setPackage(getPackageName());

    PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarmService.set(
            AlarmManager.ELAPSED_REALTIME,
            SystemClock.elapsedRealtime() + 1000,
            restartServicePendingIntent);

    super.onTaskRemoved(rootIntent);
}

}

Vivek Bhardwaj
  • 530
  • 5
  • 16
6

On some devices (notably Xiaomi, Huawei, Lenovo) you need to add your app to a list of "protected apps" or "apps that are allowed to run in the background". If your app isn't in the list, Android will NOT automatically restart your Service, even if you have returned START_STICKY from onStartCommand(). This is a "battery saving feature" that unfortunately makes a lot of problems for developers!

Look in the Android settings under Power management, Security or Apps for these settings.

See also:

Please also explain what you mean by "kill my app". If you force close your app, then the Service will NOT be restarted by Android. This is intentional, and it also won't be restarted on the emulator if you force close the app.

David Wasser
  • 93,459
  • 16
  • 209
  • 274
  • 2
    Thanks man it worked i have enabled auto start by **setting >Permissions>Autostart** n ya i got solution in this link: [Solution Link](https://stackoverflow.com/a/39269523/8362967) – LEGEND MORTAL Dec 28 '17 at 14:11
  • What about the foreground service? – Muhammad Babar Mar 21 '21 at 09:49
  • 1
    @MuhammadBabar I don't understand your question. Normally Android won't kill a foreground `Service`, but in this case, I assume that if Android kills your foreground `Service` (for whatever reason), it still won't restart it unless your app is added to this list of apps. – David Wasser Mar 21 '21 at 12:52
  • 1
    @DavidWasser thanks, you answered my question. – Muhammad Babar Mar 21 '21 at 13:17
-1

Code might help you in HourlyService class onStartCommand method returns START_STICKY

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

Inside Activity

 private HourlyService mHourlyService;
private ServiceConnection mServiceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        // We've bound to LocalService, cast the IBinder and get LocalService instance
        LocalBinder binder = (LocalBinder) iBinder;
        mHourlyService = binder.getService();
        mBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        mBound = false;
    }
};

@Override
protected void onStart() {
    super.onStart();
    // Bind to LocalService
    Intent intent = new Intent(this, HourlyService.class);
    bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
}

@Override
protected void onStop() {
    super.onStop();
    unbindService(mServiceConnection);
    mBound = false;
}
Hemanth S
  • 669
  • 6
  • 16