FabioC
FabioC

Reputation: 462

Android: How to detect a background service when app restarted?

I have an app that creates a never ending background service. The service is started when the app is launched. When the app is killed (e.g. by the user), the service sends a broadcast request that will restart it after it is killed. The question is: when I restart the app, how can I know if the service is already running? Naively I had thought that by restarting the service when the app is re-launched it would have stopped the existing service but this does not happen. The following code shows that if I do this, there are two services running at the same time (the printout in the timer moves from every second to every half a second). Many thanks

public class MainActivity extends AppCompatActivity {
        static Intent mServiceIntent;
        private SensorService mSensorService;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            ctx=this;
            setContentView(R.layout.activity_main);
            mSensorService= new SensorService(getCtx());
            mServiceIntent = new Intent(getCtx(), mSensorService.getClass());
            startService(mServiceIntent);
        }

        Context ctx;

        public Context getCtx() {
            return ctx;
        }



        @Override
        protected void onDestroy() {
            stopService(mServiceIntent);
            Log.i("MAINACT", "onDestroy!");
            super.onDestroy();

        }
    }

public class SensorService extends Service {

    public int counter=0;

    public SensorService(Context applicationContext) {
        super();
        Log.i("HERE", "here I am!");

    }

    public SensorService() {
    }

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


    private Timer timer;
    private TimerTask timerTask;

    long oldTime=0;

    public void startTimer() {
        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask();

        //schedule the timer, to check if the service is there in 25s
        timer.schedule(timerTask, 1000, 1000); //
    }

    /**
     * it sets the timer to check in x seconds if the sensorsService is active. If not it will start the service
     */
    public void initializeTimerTask() {
        timerTask = new TimerTask() {
            public void run() {
                long time= System.currentTimeMillis();
               Log.i("in timer", "in timer ++ "+(time-oldTime)+" ++  "+ (counter++));
                oldTime= time;
            }
        };
    }

    /**
     * not needed
     */
    public void stoptimertask() {
        //stop the timer, if it's not already null
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("EXIT", "ondestroy!");
        Intent broadcastIntent = new Intent("uk.ac.shef.oak.ActivityRecognition.RestartSensor");
        sendBroadcast(broadcastIntent);
        stoptimertask();
    }

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

public class SensorRestarterBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(), "Service Stops! Oooooooooooooppppssssss!!!!");

        context.startService(new Intent(context, SensorService.class));;
    }

}

Upvotes: 2

Views: 1914

Answers (1)

gdaramouskas
gdaramouskas

Reputation: 3747

private boolean isMyServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

And then use

isMyServiceRunning(MyService.class)

Credit

Upvotes: 3

Related Questions