Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android如何實現接收和發送短信

Android如何實現接收和發送短信

編輯:關於Android編程

每一部手機都具有短信接收和發送功能,下面我們通過代碼來實現接收和發送短信功能。 

一、接收短信

1、創建內部廣播接收器類,接收系統發出的短信廣播
2、從獲得的內容中解析出短信發送者和短信內容
3、在Activity中注冊廣播
4、添加接收短信權限

下面放上具體的代碼 
activity_main.xml文件用於顯示短信發送者號碼和顯示短信內容

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

  <TextView
    android:id="@+id/sms_from"
    android:layout_width="wrap_content"
    android:layout_height="20dp"
    android:text="From" />
  <TextView
    android:id="@+id/sms_from_txt"
    android:layout_width="wrap_content"
    android:layout_height="20dp"
    android:layout_marginLeft="15dp"
    android:layout_toRightOf="@id/sms_from"/>
  <TextView
    android:id="@+id/sms_content"
    android:layout_width="wrap_content"
    android:layout_height="20dp"
    android:layout_below="@id/sms_from"
    android:layout_marginTop="20dp"
    android:text="Content" />
  <TextView
    android:id="@+id/sms_content_txt"
    android:layout_width="wrap_content"
    android:layout_height="20dp"
    android:layout_marginLeft="15dp"
    android:layout_marginTop="20dp"
    android:layout_below="@id/sms_from_txt"
    android:layout_toRightOf="@id/sms_content"/>
</RelativeLayout>

MainActivity.java文件

public class MainActivity extends AppCompatActivity {
  private TextView fromTv;
  private TextView contentTv;

  private IntentFilter intentFilter;
  private MessageReceiver messageReceiver;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initView();
    getSms();
  }

  private void getSms() {
    intentFilter = new IntentFilter();                 intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
    messageReceiver = new MessageReceiver();
    //設置較高的優先級
    intentFilter.setPriority(100);
    registerReceiver(messageReceiver, intentFilter);
  }

  private void initView() {
    fromTv = (TextView) findViewById(R.id.sms_from_txt);
    contentTv = (TextView) findViewById(R.id.sms_content_txt);
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(messageReceiver);
  }

  class MessageReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
      Bundle bundle = intent.getExtras();
      //提取短信消息
      Object[] pdus = (Object[]) bundle.get("pdus");
      SmsMessage[] messages = new SmsMessage[pdus.length];
      for (int i = 0; i < messages.length; i++) {
        messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
      }
      //獲取發送方號碼
      String address = messages[0].getOriginatingAddress();

      String fullMessage = "";
      for (SmsMessage message : messages) {
        //獲取短信內容
        fullMessage += message.getMessageBody();
      }
      //截斷廣播,阻止其繼續被Android自帶的短信程序接收到
      abortBroadcast();
      fromTv.setText(address);
      contentTv.setText(fullMessage);
    }
  }
}

注:注冊的廣播接收器,一定要在OnDestroy()方法中取消注冊。

由於短信廣播是有序廣播,如果我們不想讓Android自帶的短信程序接收到短信,就可以設置我們自身接收器的優先級,同時在我們接受完廣播後將廣播截斷,阻止其被Android自帶的短信程序接收到。 

二、發送短信

1、獲取接收者的號碼和短信內容
2、獲得短信發送管理實例
3、構造PendingIntent啟動短信發送狀態監控廣播
4、調用發送短信函數,傳入參數發送短信
5、構造廣播接收器內部類監控短信是否發送成功
6、獲得廣播接收器實例和IntentFilter實例,注冊廣播接收器
7、在onDestroy()中取消注冊的廣播接收器
8、在AndroidManifest.xml文件中加入短信發送權限

下面放上具體的布局文件和代碼 
activity_send_msg.xml文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  <EditText
    android:id="@+id/to_ed"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:hint="to"/>
  <EditText
    android:id="@+id/to_content"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_below="@id/to_ed"
    android:hint="content"/>
  <Button
    android:id="@+id/send_msg"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_below="@id/to_content"
    android:text="@string/send_message"/>
</RelativeLayout>

SendMsgActivity.java文件

public class SendMsgActivity extends AppCompatActivity implements View.OnClickListener {
  private Context context;
  private EditText toEdit;
  private EditText toContent;
  private IntentFilter sendFilter;
  private SendStatusReceiver sendStatusReceiver;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_send_msg);
    context = this;
    initView();
  }

  private void initView() {
    toEdit = (EditText) findViewById(R.id.to_ed);
    toContent = (EditText) findViewById(R.id.to_content);
    //添加發送按鈕的點擊監聽事件
    Button sendMsg = (Button) findViewById(R.id.send_msg);
    sendMsg.setOnClickListener(this);
  }

  @Override
  public void onClick(View view) {
    switch (view.getId()){
      case R.id.send_msg:
        sendMessage();
       break;
      default:
        break;
    }
  }

  private void sendMessage() {
    //獲取短信接收者號碼
    String to = toEdit.getText().toString();
    //獲取發送短信內容
    String content = toContent.getText().toString();
    //獲得廣播接收器實例和IntentFilter實例
    sendStatusReceiver = new SendStatusReceiver();
    sendFilter = new IntentFilter();
    sendFilter.addAction("SENT_SMS_ACTION");
    //注冊廣播監聽
    registerReceiver(sendStatusReceiver, sendFilter);
    //構造PendingIntent啟動短信發送狀態監控廣播
    Intent sendIntent = new Intent("SENT_SMS_ACTION");
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, sendIntent, 0);
    //獲得短信管理實例
    SmsManager smsManager = SmsManager.getDefault();

    //調用發送短信函數,傳入參數發送短信(第一、三、四參數依次為接收者號碼,短信內容,短信發送狀態監控的PendingIntent)
    smsManager.sendTextMessage(to, null, content, pi, null);
  }

  /**
   * 構造廣播接收器內部類監控短信是否發送成功
   */
  class SendStatusReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
      if (getResultCode() == RESULT_OK){
        Toast.makeText(context, "successful", Toast.LENGTH_SHORT).show();
      }else{
        Toast.makeText(context, "failed", Toast.LENGTH_SHORT).show();
      }
    }
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    //取消注冊的廣播
    unregisterReceiver(sendStatusReceiver);
  }
}

在AndroidManifest.xml文件中加入短信發送權限 
<uses-permission android:name="android.permission.SEND_SMS"/>

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved