This is probably all in Java mechanics that I don't know, but here's my problem:
I have an SMS receiver that spits out two variables, the sender and the message body. I'm trying to access them from a separate service. I have a toast message in my SMS receiver (as shown in the code) and it shows the message fine, but when I try to toast that same thing from the service, the message is nothing. So the SMS receiver is receiving the message correctly.
public class SmsReceiver extends BroadcastReceiver {
public String senderNum;
public String message;
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
senderNum = currentMessage.getDisplayOriginatingAddress();
String msg = currentMessage.getDisplayMessageBody();
message = msg;
Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + msg);
}
}
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
Intent i = new Intent(context, ChatHeadService.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(i);
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context,
"senderNum: "+ senderNum + ", message: " + message, duration);
toast.show();
}
}
I am trying to access the variable using:
SmsReceiver r = new SmsReciever();
message = r.message;
sender = r.senderNum;
Here i am specifying another way to access the value in ChatHeadService . You can change the code for invoking the Service by like this in broadcastReceiver class
Intent i = new Intent(context, ChatHeadService.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("num",senderNum);
i.putExtra("msg",msg);
context.startService(i);
In ChatHeadService you can retrive it as using the following code:
Intent intent=getIntent();
String message = intent.getStringExtra("msg");
String senderInfo= intent.getStringExtra("num");
Toast toast = Toast.makeText(context,
"senderNum: "+ senderInfo + ", message: " + message, duration).show();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.