我们要实现的目标是:做一个短信发送器
界面:
因为要涉及到短信发送这种属于隐私的问题,所以我们要在AndroidManifest.xml中添加一行代码,来获得权限:
<uses-permission android:name="android.permission.SEND_SMS"/>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="100dp" android:layout_height="wrap_content" android:text="@string/number" android:id="@+id/numberlabel" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/number" android:layout_toRightOf="@id/numberlabel" android:layout_alignTop="@id/numberlabel" android:layout_marginLeft="5dp" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/content" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:minLines="3" android:id="@+id/content" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button" android:id="@+id/button" /> </LinearLayout>
package cn.itcast.sms; import java.util.ArrayList; import android.app.Activity; import android.os.Bundle; import android.telephony.SmsManager; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { private EditText numberText; private EditText contentText; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); numberText = (EditText) this.findViewById(R.id.number); contentText = (EditText) this.findViewById(R.id.content); Button button = (Button) this.findViewById(R.id.button); button.setOnClickListener(new ButtonClickListener()); } private final class ButtonClickListener implements View.OnClickListener{ public void onClick(View v) { String number = numberText.getText().toString(); String content = contentText.getText().toString(); SmsManager manager = SmsManager.getDefault(); //获得默认的消息管理器 ArrayList<String> texts = manager.divideMessage(content); //拆分长短信 for(String text : texts){ manager.sendTextMessage(number, null, text, null, null); //发送短信 } Toast.makeText(MainActivity.this, R.string.success, Toast.LENGTH_LONG).show(); } } }
原文地址:http://blog.csdn.net/u010800530/article/details/39085013