在Android中暂停/休眠线程或进程

时间:2017-03-25 13:48:44

标签: android memory-leaks handler

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);
}

我认为此解决方案不会导致内存泄漏。根据获得大多数选票(How to pause / sleep thread or process in Android?)的答案,这将导致内存泄漏。你觉得怎么样?

1 个答案:

答案 0 :(得分:0)

为避免内存泄漏,处理程序需要将WeakReference用于活动。你可以这样做

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);
}

https://stackoverflow.com/a/3039718/3812404

中也提到了同样的问题