-1

Tell me, can anyone come across such a problem. Regular service:

    public class ContactChangeService extends Service {

public ContactChangeService() {
}

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

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

    
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,
            0, notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(this, CONTACT_CHANGE_CHANNEL_ID)
            .setContentTitle("itle")
            .setSmallIcon(R.drawable.ic_black_list)
            .setContentText("Message")
            .setContentIntent(pendingIntent)
            .build();

    startForeground(1546644, notification);
 

    return START_STICKY;
}

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

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

This is how the service is started from a fragment:

Intent serviceIntent = new Intent(getContext(), ContactChangeService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    ContextCompat.startForegroundService(getActivity(), serviceIntent);
} else {
    getActivity().startService(serviceIntent);
}

To clearly see how the system works with services, I chose for testing, probably the weakest smartphone with a small amount of RAM, FinePower. One has only to run several applications, the memory in the RAM runs out and the service is killed by the system. But, despite the START_STICKY value in onStartCommand, the service does not start again, even if there is enough RAM again. What could be the problem? Thanks in advance.

1 Answers1

0

There are some devices, especially low-end devices, that will not permit apps to run indefinitely in the background (for battery-saving purposes). These devices do NOT automatically restart services, even if you return START_STICKY from onStartCommand(). Usually on these devices, there is way to manually add your app to a list of "protected apps" or a list of "apps allowed to run in the background". Once you've added your app to this list, Android will automatically restart it, as designed. There is no way to automatically add your app to this list, the user must do it manually. Usually there is a way to do this in the Settings, either under "power management", "Battery management", or "security". I don't know the device you are testing so I cannot tell you exactly where to find the setting.

See the following for more info:

David Wasser
  • 93,459
  • 16
  • 209
  • 274