Вопрос

Mind the typos, just a mock up.

class myActivity1 extends Activity
{
 oncreate()
  {
    Handler myHandler = new Handler();
    myHandler.postDelayed(myRunnable,1000)
  }

 onPause()
  {
  }
}

The handler does its job, and after 1 second the myRunnable runs. Assuming I call another postDelayed inside my myRunnable, that restarts the postDelayed for repetition.

In myActivity1 I am not using the removeCallbacks() function, thus the myHandler will be running even if I leave the activity.

However, my question is, HOW CAN I CANCEL the myHandler from inside another activity that I moved to ? (Assume my app has 15 activites, and I do not know inside which one I am.)

Это было полезно?

Решение

Create a Singelton class like :-

public class MyHandler {
    private static Handler handler;

    public static Handler getHandler() {
        if (handler == null) {
            initHandler();
        }
        return handler;
    }

    private static void initHandler() {
        handler = new Handler();
        handler.postDelayed(myRunnable,1000);
    }

    public static void stopMyHandler() {
        handler.removeCallbacksAndMessages(null);
    }

    public static void pauseMyHandler(Runnable myRunnable) {
        handler.removeCallbacksAndMessages(myRunnable);
    }

    public static void resumeMyHandler(Runnable myRunnable) {
        handler.postDelayed(myRunnable,1000);
    }
}

Use MyHandler.getHandler() to run it and MyHandler.stopMyHandler() to stop it in any activity.

In your Activity class:-

    @Override
    public void onPause()
    {
        super.onPause();
        MyHandler.pauseMyHandler(myRunnable);
    }

    @Override
    public void onResume()
    {
        super.onResume();
        MyHandler.resumeMyHandler(myRunnable);
    }

Code for Runnable that runs on UI thread:-

    runOnUiThread(new Runnable() {

          @Override
          public void run() {
                //update your UI
          }
    });
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top