How to keep the countdown running in the background

Asked

Viewed 178 times

0

I’m trying to do a countdown of 24 hours but keep running in the background, because I want to send a notification when it’s 5 hours, what I got so far was trying to implement a service with broacast receiver ( I didn’t quite understand this )but every time the app is closed ( deleted from recent ) the count stops and restarts when I open the app.

Mainactivity:

    package br.com.igoroliv.testecountdown;

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 txvcon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txvcon = (TextView) findViewById(R.id.txv_tempo);
        startService(new Intent(this, BroadcastService.class));
        Log.i(TAG, "Started service");
    }

    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);
            txvcon.setText(""+millisUntilFinished/1000);
        }
    }
}

Broadcastservice

package br.com.igoroliv.testecountdown;

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/08/2017.
 */

public class BroadcastService  extends Service {

    private final static String TAG = "BroadcastService";

    public static final String COUNTDOWN_BR = "br.com.igoroliv.countdown_br";
    Intent bi = new Intent(COUNTDOWN_BR);

    CountDownTimer cdt = null;

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

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

        cdt = new CountDownTimer(80000, 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 super.onStartCommand(intent, flags, startId);
    }

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

1 answer

1

You have to put it on your manifest:

<receiver android:name="SeuBroadcastReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter> 
   <action android:name="android.intent.action.BOOT_COMPLETED" /> 
    <category android:name="android.intent.category.DEFAULT" /> 
</intent-filter>

doing this, your service will run forever, shall we say so.

  • I don’t have a Broadcastreceiver class so it doesn’t work

  • see here: http://blog.globalcode.com.br/2010/05/respondendo-eventos-no-android.html

  • I did not understand what you passed me, I want to have 24 hours counting on my screen, but when the app opens again it continues counting from where it stopped, not restart the count

  • Voce needs to have a broadcastreceiver to be able to receive the service msgs, because for what posted, You need the counter to restart from where it stopped when the application was closed, dai Voce will have to implement one in order to be able to activate the flags in the manifest in order to continue running the device boot, that is with the originating app closed. see here, in English, can help you with an example: https://stackoverflow.com/questions/22496863/how-to-run-countdowntimer-in-a-service-in-android

  • This in English, I’m starting to understand it, already understood the broadcast, but I don’t understand why it restarts the count when the app is deleted from memory, it seems that it recreates the service when this happens, should not continue running?

  • thanks for the help, but I’ve changed my mind, I won’t have to keep it in the background, so just need that count continue from where it left off - the time that’s gone by, but I’m having a hard time calculating, if you can help me, I opened another https question://en.stackoverflow.com/questions/230632/how-to-do-time-calculation-on-android

Show 1 more comment

Browser other questions tagged

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