Keep Countdowntimer running after the app closes

Asked

Viewed 135 times

0

I made a Countdown in a service, it works when the app is sending to the background, but when the app to the state "Dead" it to the count and restarts when I open again. I need it to continue working even in the dead state, because I need to send notifications when a certain time arrives for example. The code that I’m having this result: Broadcastservice.java.

package com.example.igord.myapplication2;

import android.app.Service;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.util.Log;

/**
 * Created by igord on 19/09/2017.
 */

public class BroadcastService extends Service {
    private final static String TAG = "BroadcastService";

    public static final String COUNTDOWN_BR = "com.example.igord.myapplication2";
    Intent bi = new Intent(COUNTDOWN_BR);

    CountDownTimer cdt = null;

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

        Log.i(TAG, "Starting timer...");

        cdt = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

                Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
                bi.putExtra("countdown", millisUntilFinished);
                sendBroadcast(bi);
            }

            @Override
            public void onFinish() {
                Log.i(TAG, "Timer finished");
            }
        };

        cdt.start();
    }

    @Override
    public void onDestroy() {

        cdt.cancel();
        Log.i(TAG, "Timer cancelled");
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_NOT_STICKY;

    }

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

Mainactivity

package com.example.igord.myapplication2;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "igr";
    private TextView texttempo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService(new Intent(this, BroadcastService.class));
        Log.i(TAG, "Started service");
        texttempo = (TextView) findViewById(R.id.txt_tempo);

    }

    private BroadcastReceiver br = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            updateGUI(intent); // or whatever method used to update your GUI fields
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        registerReceiver(br, new IntentFilter(BroadcastService.COUNTDOWN_BR));
        Log.i(TAG, "Registered broacast receiver");
    }

    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver(br);
        Log.i(TAG, "Unregistered broacast receiver");
    }

    @Override
    public void onStop() {
        try {
            unregisterReceiver(br);
        } catch (Exception e) {
            // Receiver was probably already stopped in onPause()
        }
        super.onStop();
    }

    @Override
    public void onDestroy() {
        stopService(new Intent(this, BroadcastService.class));
        Log.i(TAG, "Stopped service");
        super.onDestroy();
    }

    private void updateGUI(Intent intent) {
        if (intent.getExtras() != null) {
            long millisUntilFinished = intent.getLongExtra("countdown", 0);
            Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
            texttempo.setText(String.valueOf(millisUntilFinished / 1000));
        }

    }
}
  • 1

    I think this is not the best approach. See How to perform a method at a given time?

  • 1

    Dude, I think the best way for you to do this would be by the time difference, for example when your app hits the "stop" state it records the current time with sharedpreferences, then when you open the app, you take the current time and take the difference

  • @I need the Countdown running also in Ui, so I thought this way, it is not only for notification.

  • @Matheus Currently this way, but I want to keep running because I need to send notification when it is missing for example 3 hours to finish

  • Right, so this has to be a function of a backend @Igoroliveira, a running service or something that sends these notifications, because if it kills the app process, how will it continue processing ? hehe

  • As said above, I don’t just use to send notification, there is a counter in the app UI. then it would be interesting to keep running, because then I can remove this calculation when the app is opened again ( which is giving me some strange bugs). I saw that it is possible to do with broadcast receiver but not able to implement.

  • Opa Igor, all right? I did a project of mine, where I have a very similar approach. I program an Alarm Manager, but I have a counter in the notification and UI. How did I do it? It was kind of dirty at the time, because I was starting on Android, but I created a Service to run the counter in the notification and thus had there time always stored. So when I opened the Activity again I already had the counter running in my notification. It was like this https://www.youtube.com/watch?v=kbm6XSLNFHg

  • @Lmaker is more or less what I want, but I have no interest in always having the notification running, only in the same app Ui.

  • I got it, but it still doesn’t work when I reset the phone

  • If you could help me here: https://answall.com/questions/239318/manter-servi%C3%A7o-when-cell-reboot

  • A notification gave as an example, I think the approach remains the same. Run a contdown in the service

Show 6 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.