Is it necessary to unregister the broad cast receiver? If so then how can I unregister it. My code scenario is as follows:
I have make a static method to send an sms in which I have registered a broadcast receiver like that:
public static void sendSMS(final Context mContext,String phoneNumber, String message)
{
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(mContext, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(mContext, 0,
new Intent(DELIVERED), 0);
//---when the SMS has been sent---
mContext.registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(mContext, "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(mContext, "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(mContext, "No cellular network service Available",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(mContext, "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(mContext, "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
//---when the SMS has been delivered---
mContext.registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(mContext, "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(mContext, "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
This method is created in a non activity class whose name is HomeSafeStaticMethod. Now what I do I am calling this method in my service to send the sms like that:-
HomeSafeStaticMethod.sendSMS(CheckInSOSMessageService.this,emergencyNumber,first_Name+"\n"+address+" "+city+" "+country);
This method is calling from onCreate method of my service class. Now I want that when my service will finished I want to unregister the broad cast receiver in onDestroy method.How can I achieve that... Please help me to sort out this problem.Thanks in advance!