How do I process broadcasts that were sent while my activity was stopped?

Alex Johnson

My activity starts a service which runs a CountDownTimer. The timer sends broadcasts back to the activity as it counts down. The activity processes the broadcasts in the onReceive method of a BroadcastReceiver. All of this works fine.

My problem comes when the following events happen in this order:

  1. App is stopped (via onPause())
  2. Timer finishes
  3. App is resumed (via onResume())

When the app is resumed the service is no longer sending broadcasts, so the activity does not know how much time is left on the timer or if it's finished. This prevents the activity from updating the UI.

I've tried a dozen ways of dealing with this, and read through many Stack Overflow questions and answers, but I've yet to find a solution. I would think that there's a way to pick up a broadcast that was sent while the activity was not active, but I've yet to find a way.

For the record, here is my relevant Activity and Service code:

activity.java

// Start service
timerIntent.putExtra("totalLength", totalLength);
this.startService(timerIntent);

// ...

// BroadcastReceiver
private BroadcastReceiver br = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getExtras() != null && inSession) {
            session.setRemaining(intent.getExtras().getLong("millisUntilFinished"));
            updateProgress();
        }
    }
};

// ...

// onResume
@Override
public void onResume() {
    super.onResume();
    registerReceiver(br, new IntentFilter(TimerService.COUNTDOWN_TS));
}

service.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    long length = intent.getExtras().getLong("totalLength");

    countDownTimer = new CountDownTimer(length, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            timerServiceIntent.putExtra("millisUntilFinished", millisUntilFinished);
            sendBroadcast(timerServiceIntent);
        }

        @Override
        public void onFinish() {
        }
    };

    countDownTimer.start();

    return super.onStartCommand(intent, flags, startId);
}

What's the best way to process the broadcasts that the service sent while the activity was stopped?

Kuffs

Use the BroadcastReceiver to store the last request (SharedPreferences perhaps) it received and check it when the Activity starts.

Alternatively, instead of processing a countdown using broadcasts, just store the time that the countdown would end. The Activity can then handle the countdown all by itself as it knows when it should end. Using a service and broadcasts seem to be a little over-engineered for such a simple task.

Update: From the way you have described your task, I see you needing to handle 2 scenarios. This is how I would likely do it.

Assuming that "XYZ" is the service\intent\whatever starting the countdown and "ABC" is the Activity displaying the progress. (ABC and XYZ could be the same activity if that is what you wanted)

Requirements: When the countdown starts, I would make XYZ store the time that the countdown should end in SharedPreferences.

  1. ABC is already running when the countdown starts. As Commonsware said, the Eventbus model is excellent for handling this scenario so long as XYZ and ABC are running in the same process. Just fire an event to read the preference value and count down to the specified time. If the user closes ABC and reopens it, Scenario 2 will kick in.

  2. ABC is not running. Check in OnResume whether the countdown time has elapsed. If not, set up ABC to display the countdown again. If there is no countdown active, do something else.

If you also need to do something when the countdown has elapsed regardless of whether you have a UI active, then again Commonsware's suggestion of AlarmManager is perfect.

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

How do I find out which process is using so much of my RAM?

来自分类Dev

Can I be informed that an activity intent was sent without registering an activity for it to start

来自分类Dev

how do i pass the HTTP response from one activity to another activity in android

来自分类Dev

How do i sort my listview alphabetically?

来自分类Dev

How do I link boost to my program?

来自分类Dev

Unfortunately the app has stopped. What can I do to fix this?

来自分类Dev

How do I get the nth derivative in my scheme program?

来自分类Dev

How do i pass my scope correctly to look for variables

来自分类Dev

How do I use a Codeigniter method within my own function?

来自分类Dev

How do I get my aliases to have correct completion?

来自分类Dev

How do I use my Application Resources from another window?

来自分类Dev

How do I get MVC to find my controller path?

来自分类Dev

How do I choose the URL for my Spring Boot webapp?

来自分类Dev

How do I get my nested if statement to work in jQuery

来自分类Dev

.Net Database how do I properly close my database connections?

来自分类Dev

How do I know if my app has been minimized?

来自分类Dev

How do I get `sbt test` to recognize my custom target?

来自分类Dev

How do I know if my MacBook Pro supports SATA III?

来自分类Dev

How do I transfer my Google Chrome profile to a new PC?

来自分类Dev

How do you I add a module into my PYTHONPATH?

来自分类Dev

Mapping between DTO and domain objects, how can I make the process transparent to my repository?

来自分类Dev

How do I modify my code so that my lists operate as accordions

来自分类Dev

How do I write a shell script to get a given process idle time?

来自分类Dev

GIT: How do I add a file to the first commit (and rewrite history in the process)?

来自分类Dev

How do I recompile and reload Java source code while `lein repl` is running?

来自分类Dev

How do I open an outlook .msg file from my harddrive that is NOT in outlook?

来自分类Dev

Azure and TFS, how do I share my project with a new developer joining the team

来自分类Dev

How do i call a controller action from within my view using Razor?

来自分类Dev

How do I prevent my program from skipping html2pdf function?

Related 相关文章

  1. 1

    How do I find out which process is using so much of my RAM?

  2. 2

    Can I be informed that an activity intent was sent without registering an activity for it to start

  3. 3

    how do i pass the HTTP response from one activity to another activity in android

  4. 4

    How do i sort my listview alphabetically?

  5. 5

    How do I link boost to my program?

  6. 6

    Unfortunately the app has stopped. What can I do to fix this?

  7. 7

    How do I get the nth derivative in my scheme program?

  8. 8

    How do i pass my scope correctly to look for variables

  9. 9

    How do I use a Codeigniter method within my own function?

  10. 10

    How do I get my aliases to have correct completion?

  11. 11

    How do I use my Application Resources from another window?

  12. 12

    How do I get MVC to find my controller path?

  13. 13

    How do I choose the URL for my Spring Boot webapp?

  14. 14

    How do I get my nested if statement to work in jQuery

  15. 15

    .Net Database how do I properly close my database connections?

  16. 16

    How do I know if my app has been minimized?

  17. 17

    How do I get `sbt test` to recognize my custom target?

  18. 18

    How do I know if my MacBook Pro supports SATA III?

  19. 19

    How do I transfer my Google Chrome profile to a new PC?

  20. 20

    How do you I add a module into my PYTHONPATH?

  21. 21

    Mapping between DTO and domain objects, how can I make the process transparent to my repository?

  22. 22

    How do I modify my code so that my lists operate as accordions

  23. 23

    How do I write a shell script to get a given process idle time?

  24. 24

    GIT: How do I add a file to the first commit (and rewrite history in the process)?

  25. 25

    How do I recompile and reload Java source code while `lein repl` is running?

  26. 26

    How do I open an outlook .msg file from my harddrive that is NOT in outlook?

  27. 27

    Azure and TFS, how do I share my project with a new developer joining the team

  28. 28

    How do i call a controller action from within my view using Razor?

  29. 29

    How do I prevent my program from skipping html2pdf function?

热门标签

归档