1)关键代码如下
1.MainActivity.java
package com.example.androidtestapp;
import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.telephony.gsm.SmsManager;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private Button button1=null;
private String phoneNumberString="10086";
private String msgString="10086";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1=(Button)findViewById(R.id.button1);
button1.setText("send "+msgString+" to "+phoneNumberString);
button1.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View arg0) {
/*建构一获得default instance的SmsManager对象*/
SmsManager smsManager=SmsManager.getDefault();
/*收件人电话号码格式与短信字数没有超过70个字符,发送短信*/
PendingIntent pendingIntent=PendingIntent.getBroadcast(MainActivity.this, 0, new Intent(), 0);
smsManager.sendTextMessage(phoneNumberString, null , msgString, pendingIntent,null);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
2.需要添加发送短信的权限
AndroidManifest.xml代码如下
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidtestapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.androidtestapp.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<!--添加可以发送短信的权限 -->
<uses-permission android:name="android.permission.SEND_SMS"/>
</manifest>