我收到“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/