我编写了一个程序来在 Android 中发送和接收短信。发送短信成功,但当目标手机收到短信时,会显示强制关闭对话框。点击后打开收到的短信。
我希望收到的短信显示在我放入页面的文本视图中。
短信接收器.java
public class SmsReceiver extends BroadcastReceiver
{
public String str = "";
@Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
if (bundle != null)
{
//Object[] smsExtra = (Object[]) bundle.getSMS_EXTRA_NAME);
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
//for put sms in database---------------------
// ContentResolver contentResolver = context.getContentResolver();
//End for put sms in database---------------------
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
// SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[i]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
}
//---display the new SMS message---
// Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
Intent act=new Intent(context,MainActivity.class);
act.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
act.putExtra("message",str);
context.startActivity(act);
}
}
}
MainActivity.java
public class MainActivity extends Activity {
SmsReceiver _smsReceiver =new SmsReceiver();
private TextView showSms;
private String ReceivedSms;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// _smsReceiver.onReceive(getBaseContext(), getIntent());
setContentView(R.layout.activity_main);
Intent _intent =getIntent();
ReceivedSms=_intent.getStringExtra("message");
showSms=(TextView)this.findViewById(R.id.txt_Show);
showSms.setText(ReceivedSms);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}