java - 在哪里/如何在 ListView 适配器中取消注册广播接收器?

标签 java android

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

主要 Activity :

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);
    }
});

我的客户适配器:

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);
    }

最佳答案

移动接收器变量:

BroadcastReceiver receiver;

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

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

现在,在您的 Activity 的 onDestroy 中调用它,即:

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

关于java - 在哪里/如何在 ListView 适配器中取消注册广播接收器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29752972/

相关文章:

java - JNI 方法返回旧数据

java - 格式问题

android - 安卓WIFI传输文件

android - 在 Android Room 数据库中查询全文搜索表

java - 如何使用 Java 同步共享文件夹中的文件访问(或 : ReadWriteLock on network level)

java - Gitlab 和 Code-Climate - 它真正涵盖了什么?没有什么?

java - 在测试类中调用没有参数的测试方法

android - 如何在 webrtc android 中以不同的 View 呈现远程和本地视频

android - 如何通过 AIR for Android 发送带附件的电子邮件?

android - 前一个 fragment 的 onSaveInstanceState 调用当前 fragment 的 on-orientation