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?)的答案,这将导致内存泄漏。你觉得怎么样?
答案 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);
}
中也提到了同样的问题