Android短信与电话:简易实例

来源:互联网 发布:网络黑侠 编辑:程序博客网 时间:2024/06/05 13:03

     短信的发送功能通过一个SmsManager对象的sendTextMessage (String destinationAddress, String scAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent)方法来实现,第四个参数分别代表发送成败的广播。

    短信的发送状态以及接收状态可以通过广播来实现。

public class MainActivity extends ActionBarActivity {EditText editTextTel, editTextCon;Button button;SmsManager smsManager = SmsManager.getDefault();  //SmsManager实例化方法ListView listView;ArrayAdapter<String> adapter;List<String> list;                                //存放发送内容的ListViewBroadcastReceiver smsReceiver;BroadcastReceiver smsSendReceiver;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);editTextTel = (EditText) findViewById(R.id.edittext_tel);editTextCon = (EditText) findViewById(R.id.edittext_content);button = (Button) findViewById(R.id.button);listView = (ListView) findViewById(R.id.listview);list = new ArrayList<String>();adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, list);listView.setAdapter(adapter);smsReceiver = new SMSReceiver();smsSendReceiver = new SMSSendReceiver();IntentFilter filter = new IntentFilter(        //短信接收广播android.provider.Telephony.Sms.Intents.SMS_RECEIVED_ACTION);registerReceiver(smsReceiver, filter);                   IntentFilter filter2 = new IntentFilter("SMS_SEND_ACTION"); //发送状态广播registerReceiver(smsSendReceiver, filter2);button.setOnClickListener(new OnClickListener() {           //发送短信@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubString stringTel = editTextTel.getText().toString();String stringCon = editTextCon.getText().toString();// sendSMS(stringCon, stringTel);if (!stringTel.equals("") && !stringCon.equals("")) {Intent intent = new Intent("SMS_SEND_ACTION");     //这两句是关键PendingIntent pendingIntent = PendingIntent.getBroadcast( getApplicationContext(), 0, intent, 0);smsManager.sendTextMessage(stringTel, null, stringCon,pendingIntent, null);list.add(stringCon);              //将信息内容存放在ListViewlistView.setAdapter(adapter);editTextCon.setText("");} else {if (stringTel.equals("")) {editTextTel.setError("please in put phonenumber");}if (stringCon.equals("")) {editTextCon.setError("please in put content");}}}});}@Overrideprotected void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();unregisterReceiver(smsReceiver);unregisterReceiver(smsSendReceiver);}// private void sendSMS(String tel, String con) {// SmsManager smsManager = SmsManager.getDefault();// smsManager.sendTextMessage(tel, null, con, null, null);// Toast.makeText(MainActivity.this,// "you have sent " + con + " to " + tel, Toast.LENGTH_SHORT)// .show();// }private class SMSReceiver extends BroadcastReceiver {   //接收到短信的广播,里面是解析短信内容的方法@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stubBundle bundle = intent.getExtras();if (bundle != null) {Object[] myObject = (Object[]) bundle.get("pdus");SmsMessage[] messages = new SmsMessage[myObject.length];for (int i = 0; i < myObject.length; i++) {messages[i] = SmsMessage.createFromPdu((byte[]) myObject[i]);}StringBuilder stringBuilder = new StringBuilder();for (SmsMessage message : messages) {stringBuilder.append(message.getDisplayOriginatingAddress()+ "\n");stringBuilder.append(message.getDisplayMessageBody());}Toast.makeText(MainActivity.this, stringBuilder.toString(),Toast.LENGTH_LONG).show();}}}private class SMSSendReceiver extends BroadcastReceiver {       //成功发送短信的广播@Overridepublic void onReceive(Context arg0, Intent arg1) {// TODO Auto-generated method stubif (getResultCode() == Activity.RESULT_OK) {Toast.makeText(MainActivity.this, "succeeded",Toast.LENGTH_LONG).show();} else {Toast.makeText(MainActivity.this, "failed", Toast.LENGTH_LONG).show();}}}}

xml布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:gravity="bottom"    android:orientation="vertical" >    <ListView        android:id="@+id/listview"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_weight="10" >    </ListView>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_weight="1"        android:gravity="bottom"        android:orientation="vertical" >        <EditText            android:id="@+id/edittext_tel"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:digits="0123456789"            android:hint="输入号码" />        <EditText            android:id="@+id/edittext_content"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:hint="输入短信内容" />        <Button            android:id="@+id/button"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginLeft="230dp"            android:text="发送短信" />    </LinearLayout></LinearLayout>




    电话不多做介绍了,监听来电状态改变倒是可以做一些文章的,前段时间做个东西需要监听是否有未接电话,没有找到这个广播,最后通过判断来电状态实现,也可以通过监听数据库来实现。

public class MainActivity extends ActionBarActivity {Button button;EditText editText;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);button = (Button) findViewById(R.id.btn);editText = (EditText) findViewById(R.id.et);button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubIntent intent = new Intent(Intent.ACTION_CALL);intent.setData(Uri.parse("tel:" + editText.getText().toString()));startActivity(intent);}});MyPhoneStateListener listener = new MyPhoneStateListener();TelephonyManager manager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);  //很常见的需要一个managermanager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);}private class MyPhoneStateListener extends PhoneStateListener {  @Overridepublic void onCallStateChanged(int state, String incomingNumber) {// TODO Auto-generated method stubsuper.onCallStateChanged(state, incomingNumber);switch (state) {case TelephonyManager.CALL_STATE_IDLE:System.out.println(">> CALL_STATE_IDLE");break;case TelephonyManager.CALL_STATE_OFFHOOK:System.out.println(">> CALL_STATE_OFFHOOK");break;case TelephonyManager.CALL_STATE_RINGING:System.out.println(">> CALL_STATE_RINGING");break;}}}}

    最后别忘了相应权限。感觉这个短信和电话可总结的内容不多,后面如果有学到什么新的东西再来更新吧!数据库的学习一触即发了~~

0 0
原创粉丝点击