TelephonyManager(telephone manager)


Introduction to this section:

This chapter is the last chapter of the basic Android introductory tutorial. It mainly explains some scattered knowledge points and some omissions. To supplement the knowledge points, these scattered knowledge points include the use of various system services, such as the phone manager and SMS manager in this section. Vibrators, alarm clocks, wallpapers, etc., sensors and the like! It’s a mess and everything! Okay, what we are going to learn in this section It is TelephonyManager, as the name suggests: used to manage mobile phone call status, obtain phone information (device information, sim card information and Network information), listen to phone status (call status service status, signal strength status, etc.) and can call the phone dialer to make calls! Without further ado, let’s start this section~

Official API:TelephonyManager


1. Obtain the service object of TelephonyManager

TelephonyManager tManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);


2. Usage example


1) Call the dialer to dial the phone number

Uri uri=Uri.parse("tel:"+电话号码);    
Intent intent=new Intent(Intent.ACTION_DIAL,uri);    
startActivity(intent);

2) Obtain Sim card information and network information

Running renderings:

1.png

# #Implementation code:

Layout file:

activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv_phone1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/tv_phone2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/tv_phone3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/tv_phone4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/tv_phone5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/tv_phone6"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/tv_phone7"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/tv_phone8"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/tv_phone9"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp" /></LinearLayout>

MainActivity.java:

public class MainActivity extends AppCompatActivity {

    private TextView tv_phone1;
    private TextView tv_phone2;
    private TextView tv_phone3;
    private TextView tv_phone4;
    private TextView tv_phone5;
    private TextView tv_phone6;
    private TextView tv_phone7;
    private TextView tv_phone8;
    private TextView tv_phone9;
    private TelephonyManager tManager;
    private String[] phoneType = {"未知","2G","3G","4G"};
    private String[] simState = {"状态未知","无SIM卡","被PIN加锁","被PUK加锁",
            "被NetWork PIN加锁","已准备好"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //①获得系统提供的TelphonyManager对象的实例
        tManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        bindViews();
    }

    private void bindViews() {
        tv_phone1 = (TextView) findViewById(R.id.tv_phone1);
        tv_phone2 = (TextView) findViewById(R.id.tv_phone2);
        tv_phone3 = (TextView) findViewById(R.id.tv_phone3);
        tv_phone4 = (TextView) findViewById(R.id.tv_phone4);
        tv_phone5 = (TextView) findViewById(R.id.tv_phone5);
        tv_phone6 = (TextView) findViewById(R.id.tv_phone6);
        tv_phone7 = (TextView) findViewById(R.id.tv_phone7);
        tv_phone8 = (TextView) findViewById(R.id.tv_phone8);
        tv_phone9 = (TextView) findViewById(R.id.tv_phone9);

        tv_phone1.setText("设备编号:" + tManager.getDeviceId());
        tv_phone2.setText("软件版本:" + (tManager.getDeviceSoftwareVersion()!= null?
                tManager.getDeviceSoftwareVersion():"未知"));
        tv_phone3.setText("运营商代号:" + tManager.getNetworkOperator());
        tv_phone4.setText("运营商名称:" + tManager.getNetworkOperatorName());
        tv_phone5.setText("网络类型:" + phoneType[tManager.getPhoneType()]);
        tv_phone6.setText("设备当前位置:" + (tManager.getCellLocation() != null ? tManager
                .getCellLocation().toString() : "未知位置"));
        tv_phone7.setText("SIM卡的国别:" + tManager.getSimCountryIso());
        tv_phone8.setText("SIM卡序列号:" + tManager.getSimSerialNumber());
        tv_phone9.setText("SIM卡状态:" + simState[tManager.getSimState()]);
    }
}

By the way, don’t forget to add permissions in AndroidManifest.xml!

<!-- 添加访问手机位置的权限 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<!-- 添加访问手机状态的权限 -->
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

By the way, maybe you want to get the network standard instead of ordinary 2G, 3G, 4G. In fact, we can go to the source code of the TelephonyManager class:

2.png

We can judge different network standards based on the value of this networkType, for example, if networkType == 1 That one is in GPRS format~ And the value of this networkType can be obtained through

3.png

, which is the getNetworkType() method! Okay, it’s that simple. You can list an array as above and then use Different subscripts show different values! By the way, there are also Sim card status and values ​​in the string array, which can be viewed in the source code:

4.png

Others can be explored by yourself~


3) Obtain the signal strength of the mobile phone

The unit of network signal strength is dBm (milliwatt decibel), which is generally expressed as a negative number. The normal mobile phone signal range is from -110dBm Between (poor) and -50dBm (good), if it is smaller than -50dBm, it means you are standing near the base station, such as my n5 display The signal strength is -51dBm, sometimes -59dBm, because the Nansoft Building is next door and there is a base station above...

In addition, the way to obtain signal strength in 2G, 3G, and 4G is to override PhoneStateListener's onSignalStrengthsChanged() Method, this event will be triggered when the signal strength changes. We can get the signal strength in this event!

Mobile phone acquisition signal strength code example:

dBm =-113+2*asuThis is a fixed formula, asu( Independent signal unit)

Operation renderings:

5.png

##Implementation code:

MainActivity.java:

public class MainActivity extends AppCompatActivity {

    private TextView tv_rssi;
    private MyPhoneStateListener mpsListener;
    private TelephonyManager tManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tManager = ((TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE));
        tv_rssi = (TextView) findViewById(R.id.tv_rssi);
        mpsListener  = new MyPhoneStateListener();
        tManager.listen(mpsListener,290);
    }

    private class MyPhoneStateListener extends PhoneStateListener {
        private int asu = 0,lastSignal = 0;
        @Override
        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
            asu = signalStrength.getGsmSignalStrength();
            lastSignal = -113 + 2 * asu;
            tv_rssi.setText("当前手机的信号强度:" + lastSignal + " dBm" );
            super.onSignalStrengthsChanged(signalStrength);
        }
    }
}

In addition, because the author’s cards are all mobile cards, I don’t know about China Unicom and Telecom, but I saw several APIs like this from the source code:

  • getEvdoDbm():Telecom 3G
  • getCdmaDbm():China Unicom 3G
  • getLteDbm(): 4G
These should be able to directly obtain the dBm signal strength. If you have the conditions, you can try it~

Also, don’t forget to add permissions!

<!-- 添加访问手机状态的权限 -->
 <uses-permission android:name="android.permission.READ_PHONE_STATE"/>


4) Monitor all incoming calls on your mobile phone

You can obtain the monitored call record results in different ways. What is used here is to Records are written to a file, And you can also send it to you in the form of text messages, or upload it to a certain platform. Of course, if there are not many communication records, you can also use text messages. If there are more, it will be easy for others to discover! In addition, Activity is used here instead of Service, which means to open this Activity, Only then can we monitor. Usually our needs must be run secretly in the background. Because of time constraints, we will not write the Service. If necessary You can modify it by yourself and let the Service start with the boot!

Code Analysis:

is very simple, in fact, it is just a rewrite of TelephonyManager Call status listener

PhoneStateListenerThen call the TelephonyManager.listen() method to listen. When a call comes, The program will record the caller number to the file!

Implementation code

MainActivity.java

public class MainActivity extends Activity  
{  
    TelephonyManager tManager;  
  
    @Override  
    public void onCreate(Bundle savedInstanceState)  
    {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
        // 取得TelephonyManager对象  
        tManager = (TelephonyManager)   
            getSystemService(Context.TELEPHONY_SERVICE);  
        // 创建一个通话状态监听器  
        PhoneStateListener listener = new PhoneStateListener()  
        {  
            @Override  
            public void onCallStateChanged(int state, String number)  
            {  
                switch (state)  
                {  
                // 无任何状态  
                    case TelephonyManager.CALL_STATE_IDLE:  
                        break;  
                    case TelephonyManager.CALL_STATE_OFFHOOK:  
                        break;  
                    // 来电铃响时  
                    case TelephonyManager.CALL_STATE_RINGING:  
                        OutputStream os = null;  
                        try  
                        {  
                            os = openFileOutput("phoneList", MODE_APPEND);  
                        }  
                        catch (FileNotFoundException e)  
                        {  
                            e.printStackTrace();  
                        }  
                        PrintStream ps = new PrintStream(os);  
                        // 将来电号码记录到文件中  
                        ps.println(new Date() + " 来电:" + number);  
                        ps.close();  
                        break;  
                    default:  
                        break;  
                }  
                super.onCallStateChanged(state, number);  
            }  
        };  
        // 监听电话通话状态的改变  
        tManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);  
    }  
}

Running result:

Attention! Keep this program in the foreground! Use another phone to dial the number, and then you can use the DDMS file Explorer application We can see the phoneList file in the files directory corresponding to the package name. We can export it to the computer and open it. The approximate content of the file is as follows:

THR Oct 30 12:05:48 GMT 2014 Call: 137xxxxxxx

By the way, don’t forget permissions!

<!-- 授予该应用读取通话状态的权限 -->  
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>


5) Blacklist calls are automatically hung up

The so-called blacklist is to add some phone numbers to a collection. When the mobile phone receives these calls Just hang up! But Android does not provide us with an API to hang up the phone, so we need to call the API in the service through AIDL. Achieve hanging up the phone!

So the first step is to copy the following two files in the android source code to the corresponding locations under src. They are: ITelephony.aidl;

under the android.telephony package NeighboringCellInfo.aidl;

to be created Corresponding package! Just put the aidl file under the above package!!! Then you only need to call ITelephony's endCall to hang up the phone!

What is given here is a simple interception of a single number. After entering the number and clicking the shield button, if the blocked call comes in at this time if; It will hang up directly. The code is relatively simple. Paste it below. Because the simulator used is Genymotion, I won’t demonstrate it. Screenshot after the program is running!

MainActivity.java

public class MainActivity extends Activity {  
  
    private TelephonyManager tManager;  
    private PhoneStateListener pListener;  
    private String number;  
    private EditText locknum;  
    private Button btnlock;  
      
    public class PhonecallListener extends PhoneStateListener  
    {  
        @Override  
        public void onCallStateChanged(int state, String incomingNumber) {  
            switch(state)  
            {  
            case TelephonyManager.CALL_STATE_IDLE:break;  
            case TelephonyManager.CALL_STATE_OFFHOOK:break;  
            //当有电话拨入时  
            case TelephonyManager.CALL_STATE_RINGING:  
                if(isBlock(incomingNumber))  
                {  
                    try  
                    {  
                        Method method = Class.forName("android.os.ServiceManager")  
                                .getMethod("getService", String.class);  
                        // 获取远程TELEPHONY_SERVICE的IBinder对象的代理  
                        IBinder binder = (IBinder) method.invoke(null,  
                            new Object[] { TELEPHONY_SERVICE });  
                        // 将IBinder对象的代理转换为ITelephony对象  
                        ITelephony telephony = ITelephony.Stub.asInterface(binder);  
                        // 挂断电话  
                        telephony.endCall();  
                    }catch(Exception e){e.printStackTrace();}  
                }  
                break;  
            }  
            super.onCallStateChanged(state, incomingNumber);  
        }  
    }  
      
      
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
          
        locknum = (EditText) findViewById(R.id.locknum);  
        btnlock = (Button) findViewById(R.id.btnlock);  
          
        //获取系统的TelephonyManager管理器  
        tManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);  
        pListener = new PhoneStateListener();  
        tManager.listen(pListener, PhoneStateListener.LISTEN_CALL_STATE);  
          
        btnlock.setOnClickListener(new OnClickListener() {  
              
            @Override  
            public void onClick(View v) {  
                number = locknum.getText().toString();                
            }  
        });  
          
    }  
      
    public boolean isBlock(String phone)  
    {  
        if(phone.equals(number))return true;  
        return false;  
    }  
}

Permissions, permissions, permissions

<!-- 授予该应用控制通话的权限 -->  
<uses-permission android:name="android.permission.CALL_PHONE" />    
<!-- 授予该应用读取通话状态的权限 -->  
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

Also , the Chinese version of related properties and methods can be seen: Android phone information related API


3. Download the sample code of this section

TelephonyManagerDemo.zip

TelephonyManagerDemo2.zip

Blacklist Interception Demo.zip


Summary of this section:

Okay, this section about TelephonyManager (telephone manager) ends here, it should have been covered. Most of the development requirements have been met. If there is anything missing, please feel free to mention it~

Thank you~6.gif