使用BroadcastReceiver将值传递给主类

时间:2016-05-21 20:22:31

标签: android broadcastreceiver

我的项目的目的是接收短信。所以,问题是,当我收到消息时,我需要将消息值传递给我的主类。这是我的设置。

主要课程:

public class MainActivity extends AppCompatActivity implements LocationListener {

LocationManager locationManager;
String mprovider;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //some activity is going on here.
}

public void reply(final String smsMessage) {
    TextView txtMessage = (TextView) findViewById(R.id.lblMessage);
    txtMessage.setText("message: "+smsMessage);
}

SmsReceiver类:

public class SmsReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent)
{
    Bundle myBundle = intent.getExtras();
    SmsMessage [] messages = null;
    String strMessage = "";

    if (myBundle != null)
    {
        Object [] pdus = (Object[]) myBundle.get("pdus");

        messages = new SmsMessage[pdus.length];

        for (int i = 0; i < messages.length; i++)
        {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                String format = myBundle.getString("format");
                messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format);
            }
            else {
                messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
            }
            strMessage += "SMS From: " + messages[i].getOriginatingAddress();
            strMessage += " : ";
            strMessage += messages[i].getMessageBody();
            strMessage += "\n";
        }

        Log.e("SMS", strMessage);
        Toast.makeText(context, strMessage, Toast.LENGTH_SHORT).show();
        MainActivity main = new MainActivity();
        main.reply(strMessage);
    }
}
}

如你所见。我声明了主类并将值解析为主类的方法。

MainActivity main = new MainActivity();         main.reply(strMessage);

我认为这不是正确的做法。它无论如何都不起作用

1 个答案:

答案 0 :(得分:0)

您可以制作主要活动的单例实例。或者将您的主要活动传递给SmsReceiver实例。

Singleton会有点像这样

 public class MainActivity.... {
     public static MainActivity instance;

     public void onCreate.... {
           instance = this
     }
}

然后你可以像MainActivity.instance一样引用它。 但最好将主活动实例传递给短信收发器。