简体   繁体   English

如何从广播接收机访问变量?

[英]How do I access variables from a broadcast receiver?

This is probably all in Java mechanics that I don't know, but here's my problem: 这可能是我不知道的Java机制中的全部,但这是我的问题:

I have an SMS receiver that spits out two variables, the sender and the message body. 我有一个SMS接收器,它吐出了两个变量,即发送者和消息正文。 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. 我的SMS接收器中有一条祝酒消息(如代码所示),它显示的消息很好,但是当我尝试从服务中敬酒同一件事时,该消息什么也没有。 So the SMS receiver is receiving the message correctly. 因此,SMS接收器正在正确接收该消息。

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 . 在这里,我指定了另一种访问ChatHeadService中的值的方法 You can change the code for invoking the Service by like this in broadcastReceiver class 您可以像在broadcastReceiver类中那样更改用于调用Service的代码。

 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: ChatHeadService中,您可以使用以下代码来检索它:

   Intent intent=getIntent();
   String message = intent.getStringExtra("msg");
   String senderInfo= intent.getStringExtra("num");
   Toast toast = Toast.makeText(context, 
                             "senderNum: "+ senderInfo + ", message: " + message, duration).show();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM