Search code examples
androidalarmmanagercountdown

I'm trying to create a daily countdown using AlarmManager in Android Studios


I'm trying to make something where a set number will decrease everyday, even if the app is closed, and not active. For instance, if you don't open the app for 5 days, when you do open it, the number will be 5 numbers lower. I've been trying to use AlarmManager, but I can only get it to make a Toast and not run a function in the main activity. Here is my code...

Main Activity

private TextView mTest;
private Button mButton;

private int number = 100;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mButton = (Button) findViewById(R.id.button);
    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            scheduleAlarm();
        }
    });
}

public void scheduleAlarm(){
    Intent intentAlarm = new Intent(this, AlarmReceiver.class);
    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 100000, 100000, PendingIntent.getBroadcast(this, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT ));
    Toast.makeText(MainActivity.this, "This is starting!", Toast.LENGTH_SHORT).show();
}

public void subtract(){
    mTest = (TextView) findViewById(R.id.textView);
    number -= 1;
    String numberString = Integer.toString(number);
    mTest.setText(numberString);
}

and Here is the broadcast

private MainActivity mMainActivity = new MainActivity();

@Override
public void onReceive(Context context, Intent intent) {

   mMainActivity.subtract();
   Toast.makeText(context, "This is bogus", Toast.LENGTH_LONG).show();

}

Solution

  • You can easily accomplish this using a Timer (https://developer.android.com/reference/java/util/Timer.html)

    Follow this example:

    long MINUTE_TO_MSEC = 60000;
    long DAY_TO_MSEC = MINUTE_TO_MSEC * 60 * 24;
    Timer timer = new Timer();
    TimerTask countdownTask = new TimerTask() {
        public void run() {
            /* your function goes here */
        }
    }
    timer.scheduleAtFixedRate(task,0,DAY_TO_MSEC);
    

    This will run your code every 24 hours.