布局如图: To:________________ //输入手机号
_______________ Send //输入短信内容,点击Send按钮发送信息
<LinearLayout android:layout_width="match_parent" android:layout_height="50dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:text="To:" android:padding="10dp"/> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/to" android:layout_weight="1" android:layout_gravity="center_vertical"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp"> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:layout_gravity="center_vertical" android:padding="10dp" android:id="@+id/msg_input"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/send" android:text="Send" android:textAllCaps="false" /> </LinearLayout>
在MainActivity中:
send=(Button)findViewById(R.id.send); to=(EditText)findViewById(R.id.to); msgInput=(EditText)findViewById(R.id.msg_input); sendFilter=new IntentFilter(); sendFilter.addAction("SENT_SMS_ACTION"); sendStatusReceiver=new SendStatusReceiver(); registerReceiver(sendStatusReceiver,sendFilter); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SmsManager smsManager=SmsManager.getDefault();//获取SmsManager的实例 Intent sentIntent=new Intent("SENT_SMS_ACTION"); PendingIntent pi=PendingIntent.getBroadcast(MainActivity.this,0,sentIntent,0); smsManager.sendTextMessage(to.getText().toString(),null,msgInput.getText().toString(),pi,null); } });@Override protected void onDestroy(){ super.onDestroy(); unregisterReceiver(sendStatusReceiver); } class SendStatusReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context,Intent intent){ if(getResultCode()==RESULT_OK){//短信发送成功 Toast.makeText(context,"Send succeeded",Toast.LENGTH_LONG).show(); to.setText(""); //短信发送后清除其内容 msgInput.setText(""); }else{ Toast.makeText(context,"Send failed",Toast.LENGTH_LONG).show(); } } } }声明权限:<uses-permission android:name="android.permission.SEND_SMS"/>