How To Register Broadcast Receiver?
Here is my source code and it keeps force closing everytime I run it... public class MainActivity extends Activity { private static String content; private static String ph
Solution 1:
You need to move your receiver outside the onCreate. something like -
publicclassMainActivityextendsActivity {
privatestaticString content;
privatestaticString phone;
privateStringnumber;
privateString message;
privateBroadcastReceiver receiver = newBroadcastReceiver(){
@OverridepublicvoidonReceive(Context context, Intent intent) {
//---get the SMS message passed in---Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
if (bundle != null)
{
number = "";
message = "";
//---retrieve the SMS message received---Object[] pdus = (Object[]) bundle.get("pdus");
msgs = newSmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
number = msgs[i].getOriginatingAddress();
message = msgs[i].getMessageBody();
}
//---display the new SMS message--- Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
SendMe();
}
}
};
/** Called when the activity is first created. */@OverridepublicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = newIntentFilter();
filter.addAction(YOUR_SMS_ACTION);
this.registerReceiver(this.receiver, filter);
setContentView(R.layout.main);
}
publicvoidSendMe(){
PendingIntent pi = PendingIntent.getActivity(this, 0,
newIntent(this, MainActivity.class), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(number, null, message, pi, null);
}
}
Solution 2:
The force close is likely happening because you are managing the UI from within your broadcast receiver. There's a 10-second limit on a BR's onReceive before it is forced closed.
To solve, use an Activity component to generate your Toast.
Solution 3:
I am a little confused here. It seems that you want to register aBroadcastReceiver for the "SMS_RECEIVED" IntentFilter but the filter has not been declared anywhere in the code as far as I can see.
Try replacing the null at the end of registerReceiver {} to new IntentFilter("SMS_RECEIVED")); to see if it works. Maybe its the reason why you are getting a null pointer exception.
i.e. }
}
}, null);
to }
}
}, new IntentFilter("SMS_RECEIVED"));
Post a Comment for "How To Register Broadcast Receiver?"