2

How to prevent android service from destroying?


Asked By Tester

Posted on 4 years ago


Summary :

Unrelated: class names should go UpperCamelCase in Java. service is not only violating that rule, it is also a name that says nothing about the code in it. Use names that talk to the reader. Names communicate intent.

Description:

The code runs okay for about 13 or 14 times (i.e. the timer keeps on running for about 13 or 14 times) but suddenly the service stops and onDestroy is called. Also, during debugging, I have noticed one strange condition: If I delete/comment the onDestroy() method form the code then the service runs always. It never closes on its own. (it only closes upon user input, which is fine)

Here Is My Code :
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.MainThread;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class service extends Service {
private boolean started = false;

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


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("serviceTest", "Service started by user.");
    start();
    return START_STICKY;
}

@Override
public void onDestroy() {

    //Toast.makeText(this, "Service destroyed by user.", Toast.LENGTH_LONG).show();
    Log.i("serviceTest", "Service destroyed by user.");
    stop();

    super.onDestroy();
}
Error Message :

The code runs okay for about 13 or 14 times (i.e. the timer keeps on running for about 13 or 14 times) but suddenly the service stops and onDestroy is called. Also, during debugging, I have noticed one strange condition: If I delete/comment the onDestroy() method form the code then the service runs always. It never closes on its own. (it only closes upon user input, which is fine) Please suggest a solution so that the services do not get killed/ destroyed. Or if the OS/ System kills it, then the service starts again on its own. Thnx



You have to Logged in to make answer !

Login Register

0

Uwis8wuw

The code runs okay for about 13 or 14 times (i.e. the timer keeps on running for about 13 or 14 times) but suddenly the service stops and onDestroy is called. Also, during debugging, I have noticed one strange condition: If I delete/comment the onDestroy() method form the code then the service runs always. It never closes on its own. (it only closes upon user input, which is fine) Please suggest a solution so that the services do not get killed/ destroyed. Or if the OS/ System kills it, then the service starts again on its own. Thnx


0

demo3333

afasfgas