標籤:android android應用 android簡訊
Android應用開發中我們常常需要傳送簡訊。這對於android平台來說,是最簡單不過的功能了,無需太多代碼,也無需自訂代碼,只需要調用android提供的訊息管理類SmsManager就可以了。
【源碼下載】http://www.code4apk.com/android-code/202
核心就是使用SmsManager的sendTextMessage方法加上PendingIntent跳轉。
核心代碼如下:
SmsManager sms=SmsManager.getDefault();PendingIntent intent=PendingIntent.getBroadcast(MainActivtiy.this,0, new Intent(), 0);sms.sendTextMessage(phone.getText().toString(), null, text.getText().toString(), intent, null);
下面一起來實現這個功能:
第1步:建立一個activity :MainActivtiy
import android.app.Activity;import android.app.PendingIntent;import android.content.Intent;import android.os.Bundle;import android.telephony.SmsManager;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;public class MainActivtiy extends Activity {EditText text;EditText phone;Button send;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);send=(Button)findViewById(R.id.send);text=( EditText)findViewById(R.id.text);phone=( EditText)findViewById(R.id.phone);send.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {SmsManager sms=SmsManager.getDefault();PendingIntent intent=PendingIntent.getBroadcast(MainActivtiy.this,0, new Intent(), 0);sms.sendTextMessage(phone.getText().toString(), null, text.getText().toString(), intent, null);Toast.makeText( MainActivtiy.this, "發送成功.....", Toast.LENGTH_LONG).show();}});}}
第2步:修改設定檔:main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical" ><EditTextandroid:id="@+id/phone"android:layout_width="fill_parent"android:layout_height="wrap_content"android:hint="請輸入電話號碼"android:inputType="phone"android:text="" ></EditText><EditTextandroid:id="@+id/text"android:inputType="text"android:hint="請輸入訊息"android:layout_width="fill_parent"android:layout_height="wrap_content" ></EditText><Buttonandroid:id="@+id/send"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="發送訊息" ></Button></LinearLayout>
第3步:在設定檔AndroidManifest.xml中添加傳送簡訊支援
<uses-permission android:name="android.permission.SEND_SMS"/>
第4步調試運行:
【源碼下載】http://www.code4apk.com/android-code/202