要使用手机 短信服务,在Android Manifest.xml中必须添加短信服务权限
Android Manifest.xml
<?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:Android
="http://schemas.android.com/apk/res/android"
MainActivity.java
?
package org.me.sendsms;
import Android
.app.Activity;
import Android
.app.PendingIntent;
import Android
.content.Intent;
import Android
.os.Bundle;
import Android
.telephony.gsm.SmsManager;
import Android
.view.View;
import Android
.widget.Button;
import Android
.widget.EditText;
import Android
.widget.Toast;
import java.util.List;
publicclass MainActivity extends Activity {
private EditText txtNo;
private EditText txtContent;
private Button btnSend;
/** Called when the activity is first created. */
@Override
publicvoid onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
txtNo = (EditText) findViewById(R.id.txtNo);
txtContent = (EditText) findViewById(R.id.txtContent);
btnSend = (Button) findViewById(R.id.btnSend);
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
publicvoid onClick(View v) {
String strNo = txtNo.getText().toString();
String strContent = txtContent.getText().toString();
SmsManager smsManager = SmsManager.getDefault();
PendingIntent sentIntent = PendingIntent.getBroadcast(MainActivity.this, 0, new Intent(), 0);
//如果字数超过70,需拆分成多条短信发送
if (strContent.length() > 70) {
List<String> msgs = smsManager.divideMessage(strContent);
for (String msg : msgs) {
smsManager.sendTextMessage(strNo, null, msg, sentIntent, null);
}
} else {
smsManager.sendTextMessage(strNo, null, strContent, sentIntent, null);
}
Toast.makeText(MainActivity.this, "短信发送完成", Toast.LENGTH_LONG).show();
}
});
}
}
?
其实Android已经把发送短信的功能封装得很好了,通过对Android中文API 的学习,我们也会很容易编写出Android发送短信的代码来!
?
——资料来自于瀚宇通开发网 : http://www.henii.com