Easy Tutorial
❮ Jquery Check Id Is Exists 8 Awesome Awk Built In Variables ❯

10.1 TelephonyManager (Telephony Manager)

Category Android Basic Tutorial

Introduction to This Section:

>

This section is the final chapter of the Android Basic Tutorial, focusing on a variety of miscellaneous knowledge points and supplementary information that may have been omitted. These scattered knowledge points include the use of various system services, such as the Telephony Manager, SMS Manager, Vibrator, Alarm Clock, Wallpaper, etc., as well as sensors and other miscellaneous items! We will be learning about the TelephonyManager in this section, which, as the name suggests, is used to manage the phone call status, obtain phone information (device information, SIM card information, and network information), monitor phone status (call status service status, signal strength status, etc.), and also make calls using the phone dialer! Let's get started with the content of this section~

Official API: TelephonyManager


1. Obtain the TelephonyManager Service Object

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


2. Usage Examples


1) Dial a phone number using the dialer

Uri uri=Uri.parse("tel:"+phoneNumber);    
Intent intent=new Intent(Intent.ACTION_DIAL,uri);    
startActivity(intent);

2) Retrieve SIM card information and network information

Running effect picture :

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 = {"Unknown","2G","3G","4G"};
    private String[] simState = {"Unknown status","No SIM card","Locked by PIN","Locked by PUK",
            "Locked by Network PIN","Ready"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //① Obtain an instance of the system-provided TelphonyManager object
        tManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        bindViews
&lt;uses-permission android:name="android.permission.READ_PHONE_STATE"/>

By the way, you might want to get the network system, not just the common 2G, 3G, 4G, etc. In fact, we can go to the source code of the TelephonyManager class:

We can determine different network systems based on the value of this networkType. For example, if networkType == 1, that is the GPRS system. And the value of this networkType can be obtained by

That is, this getNetworkType() method! Well, it's that simple. You can list an array as mentioned above and then display different values based on different indices!

By the way, there are also SIM card status strings in the array, and you can check them in the source code:

You can explore other things on your own~

---

### 3) Acquiring the Mobile Phone's Signal Strength

>

The unit of network signal strength is dBm (decibel-milliwatt), usually represented by a negative number. The normal range of mobile phone signal strength varies from -110dBm (poor) to -50dBm (good). If it's less than -50dBm, it means you are near the base station, such as my n5 showing a signal strength of -51dBm, sometimes -59dBm, because the next building is the NanRuan building, which has a base station on top...

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

**Example of Mobile Phone Signal Strength Acquisition Code** :

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

**Running Effect Picture** :

**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("Current mobile phone signal strength: " + lastSignal + " dBm");
        super.onSignalStrengthsChanged(signalStrength);
    }
}

}


In addition, because the author's cards are all mobile cards, I don't know about Unicom and Telecom, but I saw the following APIs in the source code:

-**getEvdoDbm()** : Telecom 3G

-**getCdmaDbm()** : Unicom 3G

-**getLteDbm()** : 4G

These should be able to directly obtain dBm signal strength. If you have the conditions, you can try it~

Also, don't forget to add the permission!

<!-- Add permission to access the phone status --> <uses-permission android:name="android.permission.READ_PHONE_STATE"/>


---

### 4) Listen to all incoming calls on the mobile phone

>

For the results of the monitored call records, you can obtain them in different ways. Here, the call records are written into a file. You can also send them to you in the form of a text message, or upload them to a certain platform. Of course, if there are not many communication records, you can also use text messages. If there are many, it is easy to be discovered by others! In addition, here we use Activity instead of Service, which means that you need to open this Activity to monitor. Our usual needs are to run in the background secretly. Due to time constraints, I will not write the Service. If you need it, you can modify it yourself to let the Service start with the boot!

**Code Analysis** :

>

It's very simple, in fact, it is to override the TelephonyManager's call state listener **PhoneStateListener** and then call the TelephonyManager.listen() method to monitor. When an incoming call comes, the program will record the incoming number in the file!

**Implementation Code
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;
        //When a call is incoming
        case TelephonyManager.CALL_STATE_RINGING:
            if(isBlock(incomingNumber))
            {
                try
                {
                    Method method = Class.forName("android.os.ServiceManager")
                            .getMethod("getService", String.class);
                    //Get the proxy of the remote TELEPHONY_SERVICE's IBinder object
                    IBinder binder = (IBinder) method.invoke(null,
                        new Object[] { TELEPHONY_SERVICE });
                    //Convert the IBinder object's proxy to an ITelephony object
                    ITelephony telephony = ITelephony.Stub.asInterface(binder);
                    //Hang up the call
                    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);

    //Get the system's TelephonyManager manager
    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** :

<!-- Grant this app the permission to control phone calls --> <uses-permission android:name="android.permission.CALL_PHONE" /> <!-- Grant this app the permission to read phone state --> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> ```

Additionally, for related properties and methods in Chinese, see: Android Phone Information Related APIs


3. Download the sample code for this section

TelephonyManagerDemo.zip

TelephonyManagerDemo2.zip

Blacklist Interception Demo.zip


Summary of this section:

>

Well, this section on TelephonyManager (phone manager) learning is here, which should have covered most of the development needs. If there is anything missing, please feel free to propose~

Thank you~

-1.0 Android Basic Tutorial

-1.0.1 Latest Android Basic Tutorial Catalog for 2015

-1.1 Background Related and System Architecture Analysis

-1.2 Development Environment Construction

-1.2.1 Developing Android APP with Eclipse + ADT + SDK

-1.2.2 Developing Android APP with Android Studio

-1.3 Solving SDK Update Issues

-1.4 Genymotion Emulator Installation

-1.5.1 Git Tutorial on Basic Operations of Local Repositories

-1.5.2 Git on Using GitHub to Set Up Remote Repositories

-1.6 How to Play with 9 (Nine Sister) Images

-1.7 Interface Prototype Design

-1.8 Project Related Analysis (Various Files, Resource Access)

-1.9 Android Program Signing and Packaging

-1.11 Decompiling APK to Obtain Code & Resources

-[

❮ Jquery Check Id Is Exists 8 Awesome Awk Built In Variables ❯