android调用ITelephony类,AIDL实现电话,联系人黑名单拦截挂断服务

版权声明:本文为博主原创文章,未经博主允许不得转载。
首先新建AIDL文件,ITelephony.aidl。注意包名为com.android.internal.telephony,不可更改,此时需要重新rebuild project才能正常使用。

android调用ITelephony类,AIDL实现电话,联系人黑名单拦截挂断服务_第1张图片
总体效果图:如下
android调用ITelephony类,AIDL实现电话,联系人黑名单拦截挂断服务_第2张图片
废话不多说,咱还是直接上代码吧:
首先布局文件:activity_phonestate


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_phonestate"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:orientation="vertical">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="黑名单"
            android:textColor="#0e0e0e"
            android:textSize="25dp" />
    LinearLayout>




    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical">

        <EditText
            android:id="@+id/et_phone_et"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:ems="10"
            android:hint="请输入黑名单号码"
            android:inputType="phone">

            <requestFocus />
        EditText>

        <Button
            android:id="@+id/bt_contact"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:layout_weight="1"
            android:onClick="getTelClick"
            android:text="选择联系人" />
    LinearLayout>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="30sp"
            android:onClick="yes"
            android:text="设置黑名单" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="no"
            android:text="取消黑名单" />
    LinearLayout>

LinearLayout>

2.Myphone

package com.zking.suzhen_android_phone;

import com.android.internal.telephony.ITelephony;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.widget.Toast;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by Administrator on 2017/2/13.
 */

public class Myphone extends BroadcastReceiver {

    private TelephonyManager telephonyManager;

    @Override
    public void onReceive(Context context, Intent intent) {
        if ("android.intent.action.PHONE_STATE".equals(intent.getAction())) {
            String number = intent.getStringExtra("incoming_number");
            Toast.makeText(context, "收到电话,号码是:" + number, Toast.LENGTH_SHORT).show();

//获取电话状态,电话管理者
            telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            int str = telephonyManager.getCallState();
            switch (str) {
                case TelephonyManager.CALL_STATE_RINGING:
                    Toast.makeText(context, "未接听", Toast.LENGTH_SHORT).show();
//得到电话管理者类对象
                    Class clazz = TelephonyManager.class;
//得到方法
                    try {
                        Method method = clazz.getDeclaredMethod("getITelephony", null);
                        //设置可访问
                        method.setAccessible(true);
                        //执行方法
                        ITelephony iTelephony = (ITelephony) method.invoke(telephonyManager, null);

                        //判断
                        //得到号码
                        String n = PhoneUtil.getString(context, "number", "").trim();
                        if (n.equals(number)) {
                            iTelephony.endCall();
                        }
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {

                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    Toast.makeText(context, "通话中", Toast.LENGTH_SHORT).show();
                    break;
                case TelephonyManager.CALL_STATE_IDLE:
                    Toast.makeText(context, "已挂断", Toast.LENGTH_SHORT).show();
                    break;


            }


        }


    }
}

3.PhoneAction

package com.zking.suzhen_android_phone;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class PhoneActivity extends AppCompatActivity {

    private EditText et_phone;
    private Button contact;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phone);
        et_phone = (EditText) findViewById(R.id.et_phone_et);
        String number = PhoneUtil.getString(PhoneActivity.this, "number", "");
        et_phone.setText(number);
        contact = (Button) findViewById(R.id.bt_contact);

//获取联系人
        contact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                PhoneActivity.this.startActivityForResult(intent, 1);
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    Uri contactData = data.getData();
                    Cursor cursor = managedQuery(contactData, null, null, null,
                            null);
                    cursor.moveToFirst();
                    String nums = this.getContactPhone(cursor);
                    Log.i("test", "所选手机号为:" + nums);
                    //将编辑器直接赋值
                    et_phone.setText(nums);


                }
                break;

            default:
                break;
        }

    }


    private String getContactPhone(Cursor cursor) {
        // TODO Auto-generated method stub
        int phoneColumn = cursor
                .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
        int phoneNum = cursor.getInt(phoneColumn);
        String result = "";
        if (phoneNum > 0) {
            // 获得联系人的ID号
            int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);
            String contactId = cursor.getString(idColumn);
            // 获得联系人电话的cursor
            Cursor phone = getContentResolver().query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "="
                            + contactId, null, null);
            if (phone.moveToFirst()) {
                for (; !phone.isAfterLast(); phone.moveToNext()) {
                    int index = phone
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                    int typeindex = phone
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
                    int phone_type = phone.getInt(typeindex);
                    String phoneNumber = phone.getString(index);
                    result = phoneNumber;

                }
                if (!phone.isClosed()) {
                    phone.close();
                }
            }
        }
        return result;
    }


    //黑名单点击事件
    public void yes(View view) {
//        //得到号码
        final String number = et_phone.getText().toString();
        AlertDialog.Builder builder = new AlertDialog.Builder(PhoneActivity.this);
        builder.setTitle("温馨提示");
        builder.setMessage("你确定设置" + number + "黑名单吗?");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(PhoneActivity.this, "黑名单设置成功", Toast.LENGTH_SHORT).show();
                PhoneUtil.setString(PhoneActivity.this, "number", number);
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();

    }

    //取消黑名单
    public void no(View view) {
        String number = PhoneUtil.getString(PhoneActivity.this, "number", "");

        if (!"".equals(number)) {
            PhoneUtil.setString(PhoneActivity.this, "number", "");
            Toast.makeText(this, "取消成功", Toast.LENGTH_SHORT).show();
        }
    }
}

4.配置清单文件,权限


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.zking.suzhen_android_phone">

    
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <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">

        activity>
        
        <receiver android:name=".Myphone">
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" />
            intent-filter>
        receiver>

        <activity android:name=".PhoneActivity">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            intent-filter>


        activity>
    application>

manifest>

以上就是我的经验和总结,欢迎大家留言讨论,不懂得可以评论留言!

你可能感兴趣的:(android四大基本组件)