2

I know that is a well known subject, but I have tried lot of things. I have an simple application, dedicated to a specific user, application has an mainActivity which is displaying some status on screen and it's starting two services, one is making request from a server (at every 5 minutes) and one which is sending sms and replay to server (at every ten minutes).

The application is running on a Samsung pocket 2 with Android 4.4.2, this device is used only for this application. While the device is connected to ADB the services are working just fine, but if I disconnect the phone and let it running normally, the services are killed repeatable and restarted after a while. The messaged are send with very much delay. I would be thankful for any suggestions.

Here is my code:

Main activity:

public class MainActivity extends Activity {

private TextView _internet;
private TextView _signal;
private TextView _server;
private BroadcastReceiver receiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    init();

    IntentFilter intentFilter = new IntentFilter(Constants.SS);

    receiverWorker();
    registerReceiver(receiver, intentFilter);

    startService(new Intent(this, RefreshDBService.class));
    startService(new Intent(this, SmsService.class));


}

private void receiverWorker() {
    receiver  = new BroadcastReceiver() {

        public void onReceive(Context arg0, Intent arg1) {
            checkState();
        }};

}

public void refreshButonClicked(View v) {
    checkState();
}`

Here is my first service:

public class RefreshDBService extends Service {

private Thread _backgroundWork;
private ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(1);
private DataBaseOperations _dataSource;

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

    _dataSource = new DataBaseOperations(this);

    _backgroundWork = new Thread(new Runnable() {
        @Override
        public void run() {

            if(Checks.checkInternetConnection(getApplicationContext())){
                if(ServerOperations.isServerAvailable(getApplicationContext())){

                    String inputData = ServerOperations.makeRequest(Constants.GET_DATA_ROUTE, ServerOperations.getMessagesFromServer(getApplicationContext()));

                    ArrayList<DataSmsObj> dataFromServer=null;
            if(inputData!=null && !inputData.isEmpty()){
                dataFromServer = ServerOperations.fromJsonToObjects(inputData);

                if(dataFromServer.size()>0){
                    _dataSource.open();
                    _dataSource.insertDataFromServer(dataFromServer);
                    _dataSource.close();
                }
            }
            System.out.println("check server for messages in pending status,  received -> "+ dataFromServer.size());

        }else{
            System.out.println("no server");
            sentErrorToUI(Constants.NO_SERVER);
        }
    }else{
        System.out.println("no internet");
        sentErrorToUI(Constants.NO_INTERNET);
    }


}
    });
}


public int onStartCommand(Intent intent, int flags, int startId) {  
    scheduleTaskExecutor.scheduleWithFixedDelay(_backgroundWork, 0, Constants.NEXT_CYCLE/2, TimeUnit.MINUTES);
    return START_REDELIVER_INTENT;
}

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

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

private void sentErrorToUI(String message){
    Intent intent = new Intent(Constants.SS);
    intent.putExtra(Constants.SS, message);
    System.out.println("trimit" +message);
    sendBroadcast(intent);
}

}

And this is the second one:

public class SmsService extends Service {

private Thread _backgroundWork;
private ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(1);

private DataBaseOperations _dataSource;

@Override
public void onCreate() {
    super.onCreate();
    _dataSource = new DataBaseOperations(this);

    _backgroundWork = new Thread(new Runnable() {
        @Override
        public void run() {

            sendFeedbackToServer();             

            List<DataSmsObj> dataToSent =  new ArrayList<DataSmsObj>();
            _dataSource.open();
                dataToSent = _dataSource.getDataToSent();
            _dataSource.close();

            System.out.println("messages to sent: "+ dataToSent.size());
            for (int i = 0; i < dataToSent.size(); i++) {

                //here the messages are send, the code is to long to put it here, but if is need i can do it afterwards 

            }   
        }
    });
}

public int onStartCommand(Intent intent, int flags, int startId) {  
    scheduleTaskExecutor.scheduleWithFixedDelay(_backgroundWork, 0, Constants.NEXT_CYCLE, TimeUnit.MINUTES);
    return START_REDELIVER_INTENT;
}

@Override
public void onDestroy() {
    super.onDestroy();
    scheduleTaskExecutor.shutdownNow();

public IBinder onBind(Intent intent) {
    return null;
}
halfer
  • 19,824
  • 17
  • 99
  • 186
J.P
  • 25
  • 3
  • i have tried restarting the service by calling startService from onDestroy but that doesnt work too. – J.P Apr 22 '17 at 08:54
  • Any error you get in Log ? – Vikrant Apr 22 '17 at 08:55
  • no errors, i have only the printed messages by me with delays. – J.P Apr 22 '17 at 08:58
  • i don't get the point why when is connected to ADB is running perfectly – J.P Apr 22 '17 at 09:02
  • If we just forget a min about the particular device , have you tested on other android device ? and with different android version ? - Just a attempt for testing , so that problem can be understood in detail . Cause as you say things work well while on adb , is kind of weired ! . Does When mobile goes in stand by it is killing those services ? – Vikrant Apr 22 '17 at 09:05
  • yes, i tested also on another devices one with Android 5.0 and one with 4.1, the same behavior. i choose the 4.4.2 version because this OS version does not have the SMS limit per hour. Yes the problem appear when the device is in stand by. but again, even if the phone is locked/stand by/the application is in background and is connected to the ADB is working. – J.P Apr 22 '17 at 09:10

3 Answers3

0

Your devices will sleeps if it is unplugged from computer . So, the solutions : Use startForeground method to prevent service to be killed and/or use AlarmManager in order to charge event.

It is possible to use start_stiky flag but it just restarts the process if it killed by system.

Vyacheslav
  • 26,359
  • 19
  • 112
  • 194
0

Android kills service based on priority stack.

Android: keeping a background service alive (preventing process death)

What is START_STICKY,START_NOT_STICKY and START_REDELIVER_INTENT Service

Above links might help you.

Community
  • 1
  • 1
mnp343
  • 329
  • 1
  • 6
0

If you are using a background Service with a scheduled task, it could be killed by the system. The only way to prevent the killing is a foreground Service. Quoting the documentation:

A foreground service is a service that the user is actively aware of and is not a candidate for the system to kill when low on memory.

You have to call the method startForeground() inside your Service using a Notification to show it. For further information you can check: https://developer.android.com/guide/components/services.html#Foreground

By the way, I recommend you to use the new JobScheduler api above api 21. https://developer.android.com/reference/android/app/job/JobScheduler.html

Giorgio Antonioli
  • 15,771
  • 10
  • 45
  • 70