흔히들 BroadcastReceiver 를 사용할때 등록하는것은 예제코들 잘 보고 실천을 하지만

해제하는것에 대해서는 심각하게 생각들을 안하는 것 같다.

 

BroadCastReceiver를 등록한다는것 자체가 익명의 클래스를 생성해서 Android Framework에 등록을 하게된다.

아직  BroadCastReceiver 를 등록했던 액티비티가 사라지게되면 어떻게 될까?

 

해당 액티비티의 context를 Android Framework가 쥐고있기에 완벽하게 해제가 되지않고 memory leak 이 발생하게 된다.

 

onStop 혹은 onDestroy method에서 적절하게 BroadCastReceiver를 필히 해제해줘야 할 것이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 
 
public BroadCastActivitiy extends AppCompatActivity {
 
    private BroadCastReceiver br;
 
 
    ....
 
    protected void onStart() {
        super.onstart();
        br = new BroadCastReceiver() {
            @override
            public void onReceive(Context context, Intent intent) {
 
            }
          }
        registerReceiver(br, new IntentFilter("hello.myworld"));
    }
 
 
 
    protected void onStop() {
        super.onStart();
        if (br != null)
             unregisterReceiver(br);        
    }
 
    protected void onDestory() {
        super.onDestory();
        if (br != null)
             unregisterReceiver(br);
    }
 
 
}
 
 

 

+ Recent posts