0

I'm trying to make an app that resets every midnight to a default view.

So, I set up an alarm in my MainActivity, and an AlarmReceiver that extends BroadcastReceiver

This is the AlarmReceiver class:

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // Will be executed when Alarm is fired
        Toast.makeText(context, "HELLO TEST", Toast.LENGTH_SHORT).show();
    }
}

And this is my MainActivity

// VerticalViewPager & adapter
VerticalViewPager verticalViewPager = (VerticalViewPager) findViewById(R.id.verticalViewPager);
adapterViewPager = new CustomPagerAdapter(getSupportFragmentManager());
verticalViewPager.setAdapter(adapterViewPager);

In this example, the alarm fires off everyday at midnight, and write the toast message. What I want instead is that the alarm changes the current item displayed in ViewPager:

// Will set the view I want
verticalViewPager.setCurrentItem(3);

But of course, I can't write this under the onReceive method because it doesn't know what verticalViewPager is. I'm new to OOP as well.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62

1 Answers1

0

There are plenty of ways to link AlarmReceiver with those components which are actually able to fully control verticalViewPager. E.g EventBus(little bit old), RXjava(Publish subject) , etc.

And if app does not always run in foreground at midnight, it's more like you need to deep link to the target page(MainActivity?), and then get the Viewpager updated.

W.Z
  • 21
  • 2
  • If the app doesn't run at midnight it doesn't matter, I just do a Calendar comparaison, and set the pager to 3 onCreate if it's a different day than yesterday. – Robert Disto Nov 17 '17 at 12:12