Android实现发短信,打电话

最近做的这个HTML5项目中有2个调用本地的打电话,发短信功能,之后就去在网上找实现方式下面就是实现方式。

  1. 首先想到就是权限问题所以在AndroidManifest中添加权限
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.my.test">
    
        <!-- 允许程序发送SMS短信 -->
        <uses-permission android:name="android.permission.SEND_SMS"/>
        <!-- 允许程序读取短信息 -->
        <uses-permission android:name="android.permission.READ_SMS"/>
        <!-- 允许程序监控一个将收到短信息,记录或处理 -->
        <uses-permission android:name="android.permission.RECEIVE_SMS"/>
        <!-- 打电话 -->
        <uses-permission android:name="android.permission.CALL_PHONE"/>
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
        </application>
    
    </manifest>
  2. 布局文件
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="com.my.test.MainActivity">
    
        <Button
            android:id="@+id/btn_call1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="打电话(调到拨号页面)"
            android:textAllCaps="false" />
    
        <Button
            android:id="@+id/btn_call2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="打电话(直接拨号)"
            android:textAllCaps="false" />
    
        <Button
            android:id="@+id/btn_send_message1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="发短信(第一种方式)"
            android:textAllCaps="false" />
    
        <Button
            android:id="@+id/btn_send_message2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="发短信(第二种方式)"
            android:textAllCaps="false" />
    
        <Button
            android:id="@+id/btn_send_message3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="发短信(跳到发送短信页面)"
            android:textAllCaps="false" />
    
    </LinearLayout>
    
  3. Activity页面代码
    package com.my.test;
    
    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.net.Uri;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.telephony.PhoneNumberUtils;
    import android.telephony.SmsManager;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;
    
    import java.util.List;
    
    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    
        private Button btn_call1;
        private Button btn_call2;
        private Button btn_send_message1;
        private Button btn_send_message2;
        private Button btn_send_message3;
        private final String TAG = getClass().getSimpleName();
        private SMSBroadcastReceiver1 smsBr1;
        private SMSBroadcastReceiver2 smsBr2;
        private IntentFilter intentFilter1;
        private IntentFilter intentFilter2;
        private final static String SENT_SMS_ACTION = "SENT_SMS_ACTION";
        private final static String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            btn_call1 = (Button) findViewById(R.id.btn_call1);
            btn_call2 = (Button) findViewById(R.id.btn_call2);
            btn_send_message1 = (Button) findViewById(R.id.btn_send_message1);
            btn_send_message2 = (Button) findViewById(R.id.btn_send_message2);
            btn_send_message3 = (Button) findViewById(R.id.btn_send_message3);
    
            btn_call1.setOnClickListener(this);
            btn_call2.setOnClickListener(this);
            btn_send_message1.setOnClickListener(this);
            btn_send_message2.setOnClickListener(this);
            btn_send_message3.setOnClickListener(this);
    
            //注册广播
            smsBr1 = new SMSBroadcastReceiver1();
            intentFilter1 = new IntentFilter(SENT_SMS_ACTION);
            registerReceiver(smsBr1, intentFilter1);
    
            smsBr2 = new SMSBroadcastReceiver2();
            intentFilter2 = new IntentFilter(DELIVERED_SMS_ACTION);
            registerReceiver(smsBr2, intentFilter2);
    
        }
    
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_call1:
                    callPhone1("10086");
                    break;
    
                case R.id.btn_call2:
                    callPhone2("10086");
                    break;
    
                case R.id.btn_send_message1:
                    sendMessage1("10086", "119");   //10086查流量短信
                    break;
    
                case R.id.btn_send_message2:
                    sendMessage2("10086", "113");   //10086查话费短信
                    break;
    
                case R.id.btn_send_message3:
                    sendMessage3("15164054765", "测试");
                    break;
            }
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            unregisterReceiver(smsBr1);
            unregisterReceiver(smsBr2);
        }
    
        /**
         * 打电话
         *
         * @param tel 电话号码
         */
        private void callPhone1(String tel) {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:" + tel));
            startActivity(intent);
        }
    
        /**
         * 打电话
         *
         * @param tel 电话号码
         */
        private void callPhone2(String tel) {
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + tel));
            startActivity(intent);
        }
    
        /**
         * 发送短信
         *
         * @param tel     电话号码
         * @param content 短息内容
         */
        private void sendMessage1(String tel, String content) {
            Intent sendIntent = new Intent(SENT_SMS_ACTION);
            PendingIntent sendPI = PendingIntent.getBroadcast(this, 0, sendIntent, 0);
    
            SmsManager smsManager = SmsManager.getDefault();
            List<String> divideContents = smsManager.divideMessage(content);
            for (String text : divideContents) {
                smsManager.sendTextMessage(tel, null, text, sendPI, null);
            }
        }
    
        /**
         * 发送短信
         *
         * @param tel     电话号码
         * @param content 短息内容
         */
        private void sendMessage2(String tel, String content) {
            Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);
            PendingIntent deliverPI = PendingIntent.getBroadcast(this, 0, deliverIntent, 0);
    
            SmsManager smsManager = SmsManager.getDefault();
            List<String> divideContents = smsManager.divideMessage(content);
            for (String text : divideContents) {
                smsManager.sendTextMessage(tel, null, text, null, deliverPI);
            }
        }
    
        /**
         * 发送短信(掉起发短信页面)
         *
         * @param tel     电话号码
         * @param content 短息内容
         */
        private void sendMessage3(String tel, String content) {
            if (PhoneNumberUtils.isGlobalPhoneNumber(tel)) {
                Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + tel));
                intent.putExtra("sms_body", content);
                startActivity(intent);
            }
        }
    
        private class SMSBroadcastReceiver1 extends BroadcastReceiver {
    
            @Override
            public void onReceive(Context context, Intent intent) {
                switch (getResultCode()) {
                    case Activity.RESULT_OK:
                        Toast.makeText(context, "短信发送成功", Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Log.e(TAG, "SmsManager.RESULT_ERROR_GENERIC_FAILURE");
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Log.e(TAG, "SmsManager.RESULT_ERROR_RADIO_OFF");
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Log.e(TAG, "SmsManager.RESULT_ERROR_NULL_PDU");
                        break;
                }
            }
        }
    
        private class SMSBroadcastReceiver2 extends BroadcastReceiver {
    
            @Override
            public void onReceive(Context context, Intent intent) {
                Toast.makeText(context, "短信发送成功", Toast.LENGTH_SHORT).show();
            }
        }
    }


  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个简易电话簿的实现,包括打电话和发送短信功能。需要注意的是,需要在 AndroidManifest.xml 文件中添加对应的权限。 布局文件 activity_main.xml: ```xml <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ListView android:id="@+id/contact_list" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="16dp"> <EditText android:id="@+id/search_text" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:hint="Search contacts" /> <Button android:id="@+id/search_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Search" /> </LinearLayout> </LinearLayout> ``` 联系人列表项布局文件 contact_item.xml: ```xml <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="16dp"> <TextView android:id="@+id/name_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18sp" android:textStyle="bold" /> <TextView android:id="@+id/phone_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="16sp" /> <TextView android:id="@+id/email_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="16sp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/call_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Call" /> <Button android:id="@+id/sms_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="SMS" /> </LinearLayout> </LinearLayout> ``` Java 代码 MainActivity.java: ```java public class MainActivity extends AppCompatActivity { private List<Contact> contactList; private ContactAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 初始化联系人列表 contactList = new ArrayList<>(); adapter = new ContactAdapter(this, contactList); ListView contactListView = findViewById(R.id.contact_list); contactListView.setAdapter(adapter); // 添加联系人 Contact contact1 = new Contact("John Smith", "1234567890", "john.smith@example.com"); Contact contact2 = new Contact("Jane Doe", "0987654321", "jane.doe@example.com"); Contact contact3 = new Contact("Bob Johnson", "5555555555", "bob.johnson@example.com"); contactList.add(contact1); contactList.add(contact2); contactList.add(contact3); // 设置联系人列表项点击事件 contactListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Contact contact = contactList.get(position); String phone = contact.getPhone(); String email = contact.getEmail(); // 打电话 Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone)); startActivity(callIntent); // 发短信 Intent smsIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phone)); smsIntent.putExtra("sms_body", "Hello, " + contact.getName() + "!"); startActivity(smsIntent); } }); // 设置搜索按钮点击事件 Button searchButton = findViewById(R.id.search_button); searchButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText searchText = findViewById(R.id.search_text); String query = searchText.getText().toString().toLowerCase(); List<Contact> filteredList = new ArrayList<>(); for (Contact contact : contactList) { if (contact.getName().toLowerCase().contains(query) || contact.getPhone().contains(query) || contact.getEmail().toLowerCase().contains(query)) { filteredList.add(contact); } } adapter.clear(); adapter.addAll(filteredList); adapter.notifyDataSetChanged(); } }); } } ``` 联系人数据模型类 Contact.java: ```java public class Contact { private String name; private String phone; private String email; public Contact(String name, String phone, String email) { this.name = name; this.phone = phone; this.email = email; } public String getName() { return name; } public String getPhone() { return phone; } public String getEmail() { return email; } } ``` 联系人列表适配器类 ContactAdapter.java: ```java public class ContactAdapter extends ArrayAdapter<Contact> { public ContactAdapter(Context context, List<Contact> contacts) { super(context, 0, contacts); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.contact_item, parent, false); } Contact contact = getItem(position); TextView nameText = convertView.findViewById(R.id.name_text); nameText.setText(contact.getName()); TextView phoneText = convertView.findViewById(R.id.phone_text); phoneText.setText(contact.getPhone()); TextView emailText = convertView.findViewById(R.id.email_text); emailText.setText(contact.getEmail()); Button callButton = convertView.findViewById(R.id.call_button); callButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String phone = contact.getPhone(); Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone)); getContext().startActivity(callIntent); } }); Button smsButton = convertView.findViewById(R.id.sms_button); smsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String phone = contact.getPhone(); Intent smsIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phone)); smsIntent.putExtra("sms_body", "Hello, " + contact.getName() + "!"); getContext().startActivity(smsIntent); } }); return convertView; } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值