We can find this change:
public class MainActivity extends Activity { private Handler mHandler = newHandler() { @Override public void handleMessage(Message msg) { //TODO handle message... } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mHandler.sendMessageDelayed(Message.obtain(), 60000); //just finish this activity finish(); }}
Then run the Android Lint tool to warn about memory leakage: This Handler class shocould be static or leaks might occur.
To modify this issue, you only need to define the Handler class as static as prompted by Lint, and then use WeakReference to keep external Activity objects.
private Handler mHandler = new MyHandler(this);private static class MyHandler extendsHandler{ private final WeakReference<Activity> mActivity; public MyHandler(Activity activity) { mActivity = newWeakReference<Activity>(activity); } @Override public void handleMessage(Message msg) { System.out.println(msg); if(mActivity.get() == null) { return; } }}
Therefore, when you use an internal class in an Activity, you must always consider whether you can control the lifecycle of the internal class. If not, you 'd better define it as a static internal class.