创建一个 Singelton 类,如:-
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);
}
}
用于MyHandler.getHandler()
运行它并MyHandler.stopMyHandler()
在任何活动中停止它。
在你的Activity
课上:-
@Override
public void onPause()
{
super.onPause();
MyHandler.pauseMyHandler(myRunnable);
}
@Override
public void onResume()
{
super.onResume();
MyHandler.resumeMyHandler(myRunnable);
}
Runnable
在 UI 线程上运行的代码:-
runOnUiThread(new Runnable() {
@Override
public void run() {
//update your UI
}
});