Async task completion after activity

Here is my process and problem:

  • In this application, you press the menu button

  • In this menu, you press the toggle button that launches Async-Task (makes a sound sound every 30 seconds). This task is to start constantly when the switch is installed, and to cancel when it is not installed. This job is great to start and stop the process while you stay in the menu window.

  • Check the switch box!

  • If the window peels back and the menu opens again, my save state for switching will be checked and the process is still running. However, I THINK that I have lost access to this instance of the Async task. What could be the reason that unchecking the screen will cause the program to crash?
    myTask.cancle (true); it may be like a lost link, and my Asynch-Task now flows in a void where I can no longer call or control it!

What can I do to capture the Async task and cancel it in this situation?

TL, DR; If I create an async task from one action (mTask = new ...), but then leave this action, how can I access mTask?

+4
source share
2 answers

You must stop the synchronization task as soon as the action is destroyed or stopped, if it is not necessary,

@Override public void onStop(){ mTask.cancel(); } 

see this for more information on canceling Android sync task - Cancel AsyncTask popup

0
source

I think you should not use the AsyncTask API, which is designed to perform a multitask task in the background thread and provides bindings for updating the user interface when it finishes or has intermediate results.

You can simply use the Runnable and singleton pattern to find an instance in constructs and action breaks. Something like (singleton templateplate omitted for brevity)

 public class Player implements Runnable { public static void start() {} @Override public void run() { while (alive) { playSound(); sleep(); } } public static void stop() {} public static boolean isAlive() {} } 

Then, when you initialize your widgets:

 checkbox.setChecked(Player.isAlive()); checkbox.setOnCheckedStateChangeListener(new OnCheckedChangeListener(){ @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) Player.start(); else Player.stop(); } }); 

Thus, your background thread is completely independent of any activity that started it.

0
source

Source: https://habr.com/ru/post/1445395/


All Articles