Hanlder + 弱引用防内存漏泄示例*

Hanlder + 弱引用防内存漏泄示例:

 1 public class MainActivity extends AppCompatActivity {
 2 
 3     public final MyHandler handler = new MyHandler(this);
 4     public final ThreadA threadA = new ThreadA(this);
 5 
 6     public static class ThreadA extends Thread {
 7         private WeakReference<MainActivity> activityRef;
 8 
 9         public ThreadA(MainActivity activity) {
10             activityRef = new WeakReference<MainActivity>(activity);
11         }
12 
13         @Override
14         public void run() {
15             MainActivity activity = activityRef.get();
16             if (activity != null) {
17                 Message msg = new Message();
18                 msg.obj = "Hi,MainThread, I'm threadA.";
19                 activity.handler.sendMessage(msg);
20             }
21         }
22     }
23 
24     ;
25 
26     public static class MyHandler extends Handler {
27 
28         private WeakReference<MainActivity> activityRef;
29 
30         public MyHandler(MainActivity activity) {
31             activityRef = new WeakReference<MainActivity>(activity);
32         }
33 
34         @Override
35         public void handleMessage(Message msg) {
36             super.handleMessage(msg);
37             MainActivity activity = activityRef.get();
38             if (activity != null) {
39                 //...
40                 String data = (String) msg.obj;
41                 System.out.println(data);
42             }
43         }
44     }
45 
46     @Override
47     protected void onCreate(Bundle savedInstanceState) {
48         super.onCreate(savedInstanceState);
49         System.out.println("onCreate");
50         //...
51 
52         threadA.start();//开启一个无内存泄漏的线程(对MainActivity 弱引用),
53 
54         //...
55     }
56 
57 }

 

posted @ 2016-09-18 08:27  f9q  阅读(213)  评论(0编辑  收藏  举报