AndroidでSMSを送受信するプログラムを作成しました。SMSの送信は成功しますが、宛先の電話でSMSを受信すると、強制終了ダイアログが表示されます。クリックすると受信したSMSが開きます。
受信したSMSをページに入れたテキストビューに表示したい。
SmsReceiver.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;
}
}