在listview适配器中取消注册广播接收器的位置/方式?

时间:2015-04-20 16:09:32

标签: java android

我得到了“Activity已经泄露了IntentReceiver ......你是否错过了对unregisterReceiver()的调用?”在运行时执行下面的代码。我想我需要为my_custom_adapter中创建的广播接收器调用unregisterReceiver,但我不知道在哪里放置unregisterReceiver语句,以及如何引用接收器。有人可以帮忙吗?

主要活动:

CheckBox master_cb = new CheckBox(getApplicationContext());
master_cb.setText("Check All");
//HERE IS THE LIST VIEW WHICH I HAVE CREATED IN MY XML FILE.
ListView lv = (ListView) findViewById(R.id.listView1);
//HERE I AM CREATING CUSTOM ADAPTER OBJECT.
my_custom_adapter adapter = new my_custom_adapter(this, android.R.layout.simple_list_item_1, elements);
lv.addHeaderView(master_cb);
lv.setAdapter(adapter);
master_cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        Intent my_intent = new Intent("master_check_change");
        my_intent.putExtra("check_value", isChecked);
        sendBroadcast(my_intent);
    }
});

my_customer_adapter:

public class my_custom_adapter extends ArrayAdapter<String> {
    private Context context                     = null;
    ArrayList<String> elements                 = null;
    private ArrayList<Boolean> itemChecked      = null;

    public my_custom_adapter(Context context, int type, ArrayList<String>  elements)
    {
        super(context, type, elements);
        this.elements =  elements;
        this.context = context;
        itemChecked = new ArrayList<Boolean>();
        BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals("master_check_change")) {
                    boolean check_value = intent.getBooleanExtra("check_value", false);
                    set_checked(check_value);
                    notifyDataSetChanged();
                }
            }
        };
        context.registerReceiver(receiver, new IntentFilter("master_check_change"));
        set_checked(false);
    }

1 个答案:

答案 0 :(得分:1)

移动接收器变量:

BroadcastReceiver receiver;

在构造函数之外,然后将myOnDestroy方法添加到my_custom_adapter:

public myOnDestroy(){
    context.unregisterReceiver(receiver);
}

现在,在你的活动的onDestroy中调用它,即:

((my_custom_adapter)(getListView().getAdapter())).myOnDestroy();