Android开发app实现发送短信功能
程序使用手機發短信的方法
短信收發:
◆發送短信只需要幾行代碼,如下:
SmsManager sms = SmsManager.getDefault(); PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(), 0); sms.sendTextMessage(phoneNumber, null, MsgStr, pi, null); |
其中參數phoneNumber和MsgStr均是String類型,表示接收方的電話號碼和短信內容
◆接收短信主要是繼承BroadcaseReceiver 類?,覆蓋onReceive 函數:
package?com.android.TinySMS; ? import?android.app.Activity; import?android.app.PendingIntent; import?android.content.BroadcastReceiver; import?android.content.Context; 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; ? public?class?TinySMS extends?Activity { ????public?static?final?String SMS_ACTION?= "com.android.TinySMS.RESULT"; // private TextView message; ????private?Button snd; ????private?EditText tel; ????private?EditText txt; ????private?SentReceiver receiver?= new?SentReceiver(); ? ????private?class?SentReceiver extends?BroadcastReceiver { @Override public?void?onReceive(Context context, Intent intent) { ????if?(intent.getAction().equals(SMS_ACTION)) { ???? int?code = getResultCode(); ???? //短消息發送成功 ???? if(code == Activity.RESULT_OK) ???? Toast.makeText(TinySMS.this, R.string.msg_sent, ???? Toast.LENGTH_SHORT).show(); ????} } ????}; ? ????/** Called when the activity is first created. */ ????@Override ????public?void?onCreate(Bundle savedInstanceState) { ????????super.onCreate(savedInstanceState); ????????setContentView(R.layout.main); ???? tel?= (EditText) findViewById(R.id.EditText01); ???? tel.setText("5554"); ?//模擬器之間互發短信 ???? txt?= (EditText) findViewById(R.id.EditText02); ???? txt.setText("我用自己的程序試試發短信。"); ???? snd?= (Button) findViewById(R.id.Button01); ???? ???? snd.setOnClickListener(new?View.OnClickListener() { ???? ????public?void?onClick(View arg0) { ???? ???? String phoneNo = tel.getText().toString(); ???? ???? String message = txt.getText().toString(); ???? ???? if?(phoneNo.length()>0 && message.length()>0){ ???? ???? sendSMS(phoneNo, message); ???? ???? } else?{ ???? ???? Toast.makeText(TinySMS.this, ???? ???? "請重新輸入電話號碼和短信內容", ???? ???? Toast.LENGTH_LONG).show(); ???? ???? } ???? ????} ? ???? }); ????} ? ????private?void?sendSMS(String address, String content) ????{ ???? SmsManager manager = SmsManager.getDefault(); ???? Intent i = new?Intent(SMS_ACTION); ???? //生成PendingIntent,當消息發送完成,接收到廣播 ???? PendingIntent?sentIntent = PendingIntent.getBroadcast( ??? this, ??? 0, ??? i, ??? PendingIntent.FLAG_ONE_SHOT); ???? manager.sendTextMessage( ???? address, ???? null, ???? content, ???? sentIntent, ???? null); ????} } |
如果要收發短信,還需在AndroidManifest.xml中聲明權限:
<uses-permission?android:name="android.permission.READ_SMS"></uses-permission> <uses-permission?android:name="android.permission.SEND_SMS"></uses-permission> |
總結
以上是生活随笔為你收集整理的Android开发app实现发送短信功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 26个思维转换,实现跨越式成长
- 下一篇: Introducing Android