Android:: Calling methods form Broadcasr Receiver class?
I have an SMSreceiver class, I am new to android, now my question is that is it possible to call any methods in other class from that class. Basically what I am trying to do is to add each received message to the linked list of strings. Here is my code...
public class SMSReceiver extends BroadcastReceiver {
/**
* @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
*/
static List<String> recNumList = new LinkedList<开发者_如何学编程;String>();
static String message;
static Integer count = 0;
static String phoneNum;
static String newMessage = null;
List<String> recMsgs;
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
for (int n = 0; n < messages.length; n++) {
smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
}
phoneNum = smsMessage[0].getDisplayOriginatingAddress();
message = smsMessage[0].getMessageBody() + "\n" +
"Time Stamp:" + smsMessage[0].getTimestampMillis();
recMsgs.add(message);
}
}
But the application force closes and does not add anything. Can someone help me please?
Well, firstly, you should not be adding sms to an array in a broadcast receiver, since it will then be recycled within like 100 milliseconds, so if you're wanting to keep track of the list of sms, you need to create a service to run in the background.
Alternatively, you could save the sms to the sharedPreferences using:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences();
// i always use default, though it isn't necessarily convention, I don't think;
SharedPreferences.editor editor = pref.edit();
editor.putString("msg", message);
editor.commit();
//issue with that is, then every time you add a new sms to the shared Preferences
// the previous one will be overridden. Resolving that is not something I will cover here
And the reason why you are getting the nullpointerexception is because your recMsgs is never initialized. do that with the following within the onReceive(), though you should really migrate it to a service if you need to maintain an array:
recMsgs = new ArrayList<String>;
then any calls to recMsgs.add(...) will work properly
I THINK that could have been the issue anyway.
精彩评论