Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public class MainActivity extends Activity {
 
        Handler handler;
        TextView tvTest;
        int cnt = 0;
 
        @Override
        protected void onCreate(Bundle savedInstanceState) {
 
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
 
                tvTest = (TextView) findViewById(R.id.tvTest);
               
                handler = new MyHandler(this);
                handler.sendEmptyMessageDelayed(0, 1000);
        }
 
        void someMethod() {
                tvTest.setText("Count = " + cnt++);
                handler.sendEmptyMessageDelayed(0, 1000);
        }
 
        @Override
        protected void onDestroy() {
                if (handler != null)
                        handler.removeCallbacksAndMessages(null);
                super.onDestroy();
        }
 
        static class MyHandler extends Handler {
 
                WeakReference<MainActivity> wrActivity;
 
                public MyHandler(MainActivity activity) {
                        wrActivity = new WeakReference<MainActivity>(activity);
                }
 
                @Override
                public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        MainActivity activity = wrActivity.get();
                        if (activity != null)
                                activity.someMethod();
                }
        }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment