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.
source share