我已经动态注册了我的广播接收器,现在我如何取消注册它。我使用了unregisterReceiver(this)。但我认为它不起作用。
IntentFilter filter = new IntentFilter("SENT");
//---when the SMS has been sent---
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent waiting room",
Toast.LENGTH_SHORT).show();
unregisterReceiver(this);
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "No Network Detected",
Toast.LENGTH_SHORT).show();
break;
}
}
}, filter);
答案 0 :(得分:0)
您可以使用
unregisterReceiver(nameofyourbroadcastreceiver);
示例代码
public class MyActivity extends Activity
{
private final BroadcastReceiver mybroadcast = new SomeBroadcastReceiver();
public void onResume()
{
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(mybroadcast, filter);
}
public void onPause()
{
unregisterReceiver(mybroadcast);
}
}
您的代码:
IntentFilter filter = new IntentFilter("SENT");
BroadcastReceiver br = new BroadcastReceiver() {
@Override
public void onReceive (Context context, Intent intent) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent waiting room",
Toast.LENGTH_SHORT).show();
unregisterReceiver(br);
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "No Network Detected",
Toast.LENGTH_SHORT).show();
break;
}
}
};
registerReceiver (br, filter);
答案 1 :(得分:0)
你必须提供一个BroadcastReceiver
实例作为第一个参数。
BroadcastReceiver mReceiver= new BroadcastReceiver(){
...
}
unregisterReceiver(mReceiver);