我有一段代码,我正在从服务中调用:
context.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
try {
WifiManager mWm = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
ret = mWm.isWifiEnabled();
// DO MORE STUFF HERE
} catch (Exception e) {
}
}
}, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
我想要的是检查并确保registerReceiver
在再次调用它之前尚未监听的方法。这可能吗?
例如,如果我的代码片段在方法中,并且我调用该方法10次,那么onReceive
方法现在似乎运行了10次。
答案 0 :(得分:14)
无法找到答案 - 您应该只拨打registerReceiver
一次,最有可能是在您创建服务时。
当您致电BroadcastReceiver
时,您需要保留对unregisterService
的引用(onDestroy()
是它的自然位置),否则系统会警告您泄漏广播接收器生气,可能会对你大喊大叫。
答案 1 :(得分:0)
这样的事情
class Thing {
interface R {
void onReceive(Context c, Intent i);
}
private BroadcastReceiver receiver;
private IntentFilter filter;
private boolean isRegistered = false;
public Thing(Thing.R r, String... actions) {
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
r.onReceive(context, intent);
}
};
filter = new IntentFilter();
for (String a : actions)
filter.addAction(a);
}
public void register(Context c) {
if (isRegistered) return;
c.registerReceiver(receiver, filter);
isRegistered = true;
}
public void unregister(Context c) {
if (!isRegistered) return;
c.unregisterReceiver(receiver);
isRegistered = false;
}
}
然后
Thing t = new Thing((c, i) -> {
try {
WifiManager mWm = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
ret = mWm.isWifiEnabled();
// DO MORE STUFF HERE
} catch (Exception e) {
}
}, WifiManager.WIFI_STATE_CHANGED_ACTION);
现在可以随意拨打t.register
!