0
protected void onCreate(Bundle savedInstanceState) {`
super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (Button) findViewById(R.id.test_button);
    button.setText("before");
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            button.setText("after");
        }
    }, 2000);
}

I think this solution will not cause a memory leak. According to the answer which gets most votes (How to pause / sleep thread or process in Android?),this will cause a memory leak. what do you think?

Community
  • 1
  • 1
古月弓虽
  • 1
  • 1
  • 1
  • 2

1 Answers1

0

To avoid memory leak, handler need to have WeakReference to activity. You can do it like this

private static class MyHandler extends Handler {}
private final MyHandler mHandler = new MyHandler();

public static class MyRunnable implements Runnable {
private final WeakReference<Activity> mActivity;

public MyRunnable(Activity activity) {
    mActivity = new WeakReference<>(activity);
}

@Override
public void run() {
    Activity activity = mActivity.get();
    if (activity != null) {
        Button btn = (Button) activity.findViewById(R.id.button);
        btn.setBackgroundResource(R.drawable.defaultcard);
    }
}
}

private MyRunnable mRunnable = new MyRunnable(this);

public void onClick(View view) {
  my_button.setBackgroundResource(R.drawable.icon);

  // Execute the Runnable in 2 seconds
  mHandler.postDelayed(mRunnable, 2000);
}

Same is also mentioned in https://stackoverflow.com/a/3039718/3812404

Community
  • 1
  • 1
Hari Ram
  • 3,098
  • 5
  • 23
  • 30