我的項目的目的是接收短信。所以,問題是,當我收到一條消息時,我需要將消息值傳遞給我的主類。這是我的設置。使用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);
我不認爲這是正確的做法。它無論如何都不起作用
你說得對。你不應該這樣做新的活動。 –
好吧,我很高興知道我錯了。但最佳做法是什麼? :D –
你有一個接收器,所以你需要廣播一條消息給它。你也可以看看使用像EventBus –