1

I am trying to create a service that runs on the background, checks information and give notifications when needed. I have tried several examples on the internet which are basically the same, but I don't get them to work.

I have a service and a BroadcastReceiver. When I start the app, the service is created and a time logs at each tick. So, this works fine. At the onDestroy I have set up a new intent which I send with the "sendBroadcast(...)". The BroadcastReceiver-class has a override on onReceive, which should log a simple text. But I never see the text.

The service

public class ServiceNoDelay extends Service {
    public int counter = 0;
    Context context;

    public ServiceNoDelay(Context applicationContext) {
        super();
        context = applicationContext;
        Log.i("HERE", "here service created!");
    }

    public ServiceNoDelay() {
    }

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

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

        Log.i("EXIT", "ondestroy!");

        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction("com.custom.package.RestartSensor");
        sendBroadcast(broadcastIntent);
        stoptimertask();


        Log.i("EXIT", "Broadcast send!");
    }

    private Timer timer;
    private TimerTask timerTask;

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

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

        //schedule the timer, to wake up every 1 second
        timer.schedule(timerTask, 1000, 1000); //
    }

    public void initializeTimerTask() {
        timerTask = new TimerTask() {
            public void run() {
                Log.i("in timer", "in timer ++++  " + (counter++));
            }
        };
    }

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

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

The BroadcastReceiver

public class SensorRestarterBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(), "Service Stops! Oops!!!!");
        context.startService(new Intent(context, ServiceNoDelay.class));

    }
}

The manifest-part

<service
            android:name=".ServiceNoDelay"
            android:enabled="true" />
        <receiver
            android:name=".SensorRestarterBroadcastReceiver"
            android:enabled="true"
            android:exported="true"
            android:label="RestartServiceWhenStopped">
            <intent-filter>
                <action android:name="com.custom.package.RestartSensor" />
            </intent-filter>
        </receiver>

The part of code I call in the MainActivity

ServiceNoDelay mSensorService = new ServiceNoDelay(getApplicationContext());
        Intent mServiceIntent = new Intent(getApplicationContext(), mSensorService.getClass());
        startService(mServiceIntent);

I expect that logcat will display "Service Stops! Oops!!!!" when the app closes, so I can reactivate the service again.

If I am looking a the wrong path to show notifications after the app is closed; I am open to suggestions.

1 Answers1

0

There several things you need to do, 1. If you need to Keep service running in Background then Create a Foreground service. 2. Turn Off Doze mode 3. or follow this link to run service in the background

Or here in your code, you can call onTaskRemoved and add a alarm to start service again

 @Override
public void onTaskRemoved(Intent rootIntent) {
    Log.e("FLAGX : ", ServiceInfo.FLAG_STOP_WITH_TASK + "");

    Intent restartServiceIntent = new Intent(getApplicationContext(),
            this.getClass());
    restartServiceIntent.setPackage(getPackageName());

    Intent intent = new Intent(getApplicationContext(), this.getClass());

    intent.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() + 2000,
            restartServicePendingIntent);

    super.onTaskRemoved(rootIntent);
}

Add permission in manifest

<uses-permission android:name="android.permission.SET_ALARM"/>
Amin Pinjari
  • 2,129
  • 3
  • 25
  • 53
  • I followed you link and most examples and code make my app crash. Is there a possibility you have a link to a working example? –  Apr 17 '19 at 15:04
  • I have implemented the onTaskRemoved. I see it gets fired. But nothing happens after that... Am I missing something? –  Apr 18 '19 at 13:00
  • 1
    Got it! I had to set the permission to set the alarm in the manifest: –  Apr 18 '19 at 13:06
  • 1
    oh, I forgot to add the permission, I have updated the answer. – Amin Pinjari Apr 18 '19 at 13:17