美好的一天,我动态构建了 android 短信发送和交付接收器,我收到泄漏错误,因为我需要在切换活动之前取消注册接收器。我想在收到响应时注销接收器。
此外,我无法覆盖 onPause 和 resume,因为此类是一个库并扩展了对话框,并且必须在代码中构造接收器。
这是代码:
private void sendSMS(String msg, String msisdn, String func) {
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
log("SMS FUNCTION: RUN");
PendingIntent sentPI = PendingIntent.getBroadcast(mContext, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(mContext, 0,
new Intent(DELIVERED), 0);
BroadcastReceiver smsReceiverD=new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
log("SMS FUNCTION: SMS DELIVER CHECK");
switch (getResultCode())
{
case Activity.RESULT_OK:
break;
case Activity.RESULT_CANCELED:
sendEventLog("Failed(SMS not delivered)");
break;
}
}
};
BroadcastReceiver smsReceiverS=new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
log("SMS FUNCTION: SEND CHECK");
switch (getResultCode())
{
case Activity.RESULT_OK:
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
log("Failed(Generic failure)");
sendEventLog("moFailed(Generic failure)");
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
sendEventLog("Failed(No service)");
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
sendEventLog("Failed(Null PDU)");
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
sendEventLog("Failed(Radio off)");
break;
}
}
};
SmsManager MySmsManager = SmsManager.getDefault();
sendEventLog("Send("+keyword+":"+msisdn+")");
if (msg != null) {
log("SMS FUNCTION: SMS SEND");
MySmsManager.sendTextMessage(msisdn, null, keyword, sentPI, deliveredPI);
mContext.registerReceiver(smsReceiverD,new IntentFilter(DELIVERED));
mContext.registerReceiver(smsReceiverS,new IntentFilter(SENT));
}
}
我想添加
mContext.unregisterReceiver(smsReceiverS);
在 smsReciverS.
它说
Cannot refer to a non-final variable smsReceiverS inside an inner class defined in a different method
如果我确实做到了:
The local variable smsReceiverS may not have been initialized
请有人帮忙。