Using the Telephony API

The telephony API is used to among other things monitor phone information including the current states of the phone, connections, network etc.

In this example, we want to utilize the telephone manager part of the Application Framework and use phone listeners (PhoneStateListener) to retrieve various phone states.

This is a simple tutorial utilizing the telephony API and its associated listener which can be good before implementing other application functions related to a phone state like connecting the Call.

This is a small example that can be used expanded with the various methods available, please see https://developer.android.com/reference/android/telephony/package-summary.html


TelephonyDemo.java
Code:

package com.marakana;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.TextView;

public class TelephonyDemo extends Activity {
TextView textOut;
TelephonyManager telephonyManager;
PhoneStateListener listener;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// Get the UI
textOut = (TextView) findViewById(R.id.textOut);

// Get the telephony manager
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

// Create a new PhoneStateListener
listener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
String stateString = "N/A";
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
stateString = "Idle";
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
stateString = "Off Hook";
break;
case TelephonyManager.CALL_STATE_RINGING:
stateString = "Ringing";
break;
}
textOut.append(String.format("\nonCallStateChanged: %s", stateString));
}
};

// Register the listener wit the telephony manager
telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
}
}


main.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Telephony Demo"
android:textSize="22sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textOut"
android:text="Output"></TextView>
</LinearLayout>


Output

Source
https://www.protechtraining.com/static/tutorials/TelephonyDemo.zip

Copyright © 2018 ProTech. All Rights Reserved.

Sign In Create Account

Navigation

Social Media