也就是说,我有一个动态创建的BroadcastReceiver,可以收听一段广播,然后我希望它取消注册。
我没有找到任何这样做的示例代码,但我也没有在android在线文档中找到任何禁止这样做的规则。但是,我不能让它在活动中停留很长时间,而且它在匿名类中,所以包含类甚至不知道变量名。
也就是说,代码看起来如下所示:
myInfoReceiver = new BroadcastReceiver() {
onReceive(Context ctx, Intent intt) {
// do some Notification when I get here
nm.notify("I got here") // obvious pseudo code
ctx.unregisterReceiver(myInfoReceiver);
} // end onReceive
ctx.registerReceiver),uInfoReceiver, new IntentFilter(...));
}; // end BroadcastReceiver但是当我运行它的时候,Android会在它调用注销器时抱怨,它坚持说接收者不是要注销的(我忘记了确切的措辞,但是它抛出了IllegalArgumentException)。
我还试着修改代码,以检查'intt‘中的操作是否与预期的相同--但是它仍然执行onReceive,但无声地未能注销。
发布于 2015-06-11 15:54:44
你的问题的答案是“是的”。然而..。
...you需要在与调用registerReceiver()相同的Context上调用registerReceiver()。在您发布的代码中,您正在调用作为参数传递给unregisterReceiver()的Context上的onReceive()。这不是相同的Context,这就是为什么您要获得异常。
发布于 2015-06-11 14:20:29
我只想说是的,一点问题也没有。
例如,我将它用于一次性的位置修复,也可以在其他逻辑中使用,而不会发现它有任何问题。
而且我已经看过很多次了。
发布于 2016-09-28 13:28:54
我尝试过各种解决方案,最后我就是这样做的:
登记:
MyApplication.getInstance().getApplicationContext().registerReceiver(sentReceiver, new IntentFilter(SENT));SentReceiver:
public class SentReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(context,
context.getString(R.string.sms_envoye), Toast.LENGTH_SHORT)
.show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(context,
context.getString(R.string.sms_defaillance_generique),
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(context,
context.getString(R.string.sms_pas_de_service),
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(context,
context.getString(R.string.sms_pas_de_pdu),
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(context,
context.getString(R.string.sms_radio_desactivee),
Toast.LENGTH_SHORT).show();
break;
}
MyApplication.getInstance().getApplicationContext().unregisterReceiver(this);
}使用MyApplication:
public class MyApplication extends Application {
private static MyApplication mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
}https://stackoverflow.com/questions/30783282
复制相似问题