Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發實例 >> 編寫最簡單的Android接受短信程序

編寫最簡單的Android接受短信程序

編輯:Android開發實例

使用android編寫接受短信,當收到短信時彈出程序對話框顯示在手機上,顯示短信內容。

如下效果圖:

 

 

 

首先:

1、在xml文件中增加權限:接受短信的權限:

<uses-permission android:name="android.permission.RECEIVE_SMS" />

2、然後建立一個BroadcastReceiver,此BroadcastReceiver是為了收到短信的時候,運行此程序,如下代碼:

  public void onReceive(Context context, Intent intent) {
     // TODO
      String action="android.intent.action.MAIN"; 
      String category="android.intent.category.LAUNCHER";
        Intent mBootIntent = new Intent(context, MessageSeeDemo.class);
        mBootIntent.setAction(action);
        mBootIntent.addCategory(category); 
      mBootIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      Bundle bundle = intent.getExtras();
      Object messages[] = (Object[]) bundle.get("pdus");
      SmsMessage smsMessage[] = new SmsMessage[messages.length];
      for (int n = 0; n < messages.length; n++) {
              smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
     }
    // show first message
      mBootIntent.putExtra("mess", "Received SMS: " + smsMessage[0].getMessageBody());
      context.startActivity(mBootIntent);
  }

3、在action中彈出提示框顯示這條短信,

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Intent intent = this.getIntent();
        String str = null;
        str = intent.getStringExtra("mess");
        if(str != null){
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Received SMS: " + str)
                    .setCancelable(false)
                    .setPositiveButton("確定",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                }
                            });
            builder.create().show();
        }
    }

4、在xml中添加receiver

<receiver android:name=".receiver.SMSReceiver"
    android:enabled="true">
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

運行此程序後,退出此程序,給10086發送10086,當短信來時,就會彈出此程序;

源代碼見:http://henzil.googlecode.com/svn/trunk/android.messageSee/

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