Skip to content

Instantly share code, notes, and snippets.

@VDenis
Created April 9, 2016 12:16
Show Gist options
  • Save VDenis/4696347704b842463a3a44d6abcfab30 to your computer and use it in GitHub Desktop.
Save VDenis/4696347704b842463a3a44d6abcfab30 to your computer and use it in GitHub Desktop.
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