Mssjim
Mssjim

Reputation: 58

Service relaunched when Activity closed

This service causes the device to vibrate after 10 seconds, but when the activity is closed or the application is removed from the recent apps, the service is restarted.

public class Vibrar extends Service {

    @Override
    public IBinder onBind(Intent p1) {
        // TODO: Implement this method
        return null;
    }

    int delay = 10000; //milliseconds

    @Override
    public void onCreate() {
        // TODO: Implement this method
        Toast.makeText(getApplicationContext(),"created",Toast.LENGTH_SHORT).show();
        super.onCreate();
        Vibrar();
    }

    public void Vibrar() {
        new Handler().postDelayed(new Runnable() {
            public void run() {
                Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                v.vibrate(200);
            }
        }, delay);
    }
}

I've already tried using the onStartComand method with value ofreturn START_STICK and START_NOT_STICK, but it keeps restarting or is terminated immediately.

I wanted it to continue where it left off even if the app was removed from recent apps. Is there any way to do this?

Upvotes: 0

Views: 59

Answers (3)

Sarthak Gandhi
Sarthak Gandhi

Reputation: 2170

I have seen many coders do this mistake of using anonymous handlers.

Use this:

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if(System.currentMillis() - getLastVibrationTime() > delay){
                Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
                v.vibrate(200);
                saveVibrationTime();
            }
        }
    };
    handler.postDelayed(runnable,10000);

And in on Destroy :

handler.removeCallbacks(runnable);

This will make sure when you exit the app or service the handler is also cancelled.

Hope this helps.

Upvotes: 2

Abdullah Tellioglu
Abdullah Tellioglu

Reputation: 1474

Have you tried to use alarm manager? Its main purpose is the scheduling events so it would fit to your problem. https://developer.android.com/training/scheduling/alarms.html Checkout this link please.

If this does not solve your solution, I have an alternative solution for you which is save the last vibration time to internal storage, and check the current time with saved time.

public class Vibrar extends Service {
    private static final String TIME_KEY = "lastinsertedtime";
    @Override
    public IBinder onBind(Intent p1) {
        // TODO: Implement this method
        return null;
    }

    int delay = 10000; //milliseconds

    @Override
    public void onCreate() {
        // TODO: Implement this method
        Toast.makeText(getApplicationContext(),"created",Toast.LENGTH_SHORT).show();
        super.onCreate();
        Vibrar();
    }
    public long getLastVibrationTime(){
        SharedPreferences preferences = getApplicationContext().getSharedPreferences("INTERNAL_STORAGE_NAME",Context.MODE_PRIVATE);
        return Long.parseLong(preferences.getString(TIME_KEY,"0"));
    }
    public void saveVibrationTime(){
        SharedPreferences preferences = getApplicationContext().getSharedPreferences("INTERNAL_STORAGE_NAME",Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(TIME_KEY,String.valueOf(System.currentMillis()));
        editor.commit();
    }
    public void Vibrar() {
        new Handler().postDelayed(new Runnable() {
            public void run() {
                if(System.currentMillis() - getLastVibrationTime() > delay){
                     Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
                     v.vibrate(200);
                     saveVibrationTime();
                }

            }
        }, 100);// check it for 100 ms
    }
}

Upvotes: 0

César Ferreira
César Ferreira

Reputation: 681

You need to start and stop your service.

To start the service:

Intent intent_current = new Intent(activity,Vibrar.class);
activity.startService(intent_current);

When you need it to stop :

Intent intent_current = new Intent(activity,Vibrar.class);
activity.stopService(intent_current);

Important note: Your service will run like an independent activity so you need to ensure you stop the service otherwise it will keep running until you run out of memory. You should take a look on the Activity life cycle

Upvotes: 0

Related Questions