详解Android开发之收发短信的处理操作
来源:爱站网时间:2020-11-25编辑:网友分享
在项目开发的时候,我们程序员要把短信和接收这个功能做好,才能在程序上线后收到短信即可验证,下面是爱站技术频道小编为大家带来的详解Android开发之收发短信的处理操作,需要的朋友可以参考下面的介绍。
在项目开发的时候,我们程序员要把短信和接收这个功能做好,才能在程序上线后收到短信即可验证,下面是爱站技术频道小编为大家带来的详解Android开发之收发短信的处理操作,需要的朋友可以参考下面的介绍。
效果图:
MainActivity:
import android.app.Activity; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.telephony.SmsManager; import android.telephony.SmsMessage; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private TextView sender; private TextView content; private IntentFilter receiveFilter; private MessageReceiver messageReceiver; private EditText to; private EditText msgInput; private Button send; private IntentFilter sendFilter; private SendStatusReceiver sendStatusReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sender = (TextView) findViewById(R.id.sender); content = (TextView) findViewById(R.id.content); to = (EditText) findViewById(R.id.to); msgInput = (EditText) findViewById(R.id.msg_input); send = (Button) findViewById(R.id.send); //为接收短信设置要监听的广播 receiveFilter = new IntentFilter(); receiveFilter.addAction("android.provider.Telephony.SMS_RECEIVED"); messageReceiver = new MessageReceiver(); registerReceiver(messageReceiver, receiveFilter); //为发送短信设置要监听的广播 sendFilter = new IntentFilter(); sendFilter.addAction("SENT_SMS_ACTION"); sendStatusReceiver = new SendStatusReceiver(); registerReceiver(sendStatusReceiver, sendFilter); send.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //发送短信 //并使用sendTextMessage的第四个参数对短信的发送状态进行监控 SmsManager smsManager = SmsManager.getDefault(); Intent sentIntent = new Intent("SENT_SMS_ACTION"); PendingIntent pi = PendingIntent.getBroadcast( MainActivity.this, 0, sentIntent, 0); smsManager.sendTextMessage(to.getText().toString(), null, msgInput.getText().toString(), pi, null); } }); } @Override protected void onDestroy() { super.onDestroy(); //在Activity摧毁的时候停止监听 unregisterReceiver(messageReceiver); unregisterReceiver(sendStatusReceiver); } class MessageReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); //使用pdu秘钥来提取一个pdus数组 Object[] pdus = (Object[]) bundle.get("pdus"); SmsMessage[] messages = new SmsMessage[pdus.length]; for (int i = 0; i
activity_main:
AndroidManifest:
//接受短信 //发送短信
以上就是爱站技术频道小编介绍的详解Android开发之收发短信的处理操作,建议你可以来js.aizhan.com学习和了解,这是专业平台,相信一定能帮到您。