Logging during calling state in Android - android

Everyboday. I am trying to log some information such as phonenumber, calling time and so on during calling state in android. I was tried to build with some codes following as below:
package com.test.dialuplog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
public class IncomingBroadcastReceiver extends BroadcastReceiver {
String mPhoneNumber;
public static IncomingBroadcastReceiver pThis;
#Override
public void onReceive(Context context, Intent intent) {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(new CustomPhoneStateListener(context), PhoneStateListener.LISTEN_CALL_STATE);
}
public class CustomPhoneStateListener extends PhoneStateListener {
//private static final String TAG = "PhoneStateChanged";
Context context; //Context to make Toast if required
public CustomPhoneStateListener(Context context) {
super();
this.context = context;
}
#Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
//when Idle i.e no call
Toast.makeText(context, "Phone state Idle", Toast.LENGTH_LONG).show();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
//when Off hook i.e in call
//Make intent and start your service here
Toast.makeText(context, "Phone state Off hook", Toast.LENGTH_LONG).show();
break;
case TelephonyManager.CALL_STATE_RINGING:
//when Ringing
Toast.makeText(context, "Phone state Ringing", Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
}
}
And also I wrote some codes in AndroidManifest.xml like this:
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen">
<receiver android:name=".IncomingBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
<activity
android:name=".SplashActivity"
android:configChanges="orientation"
android:screenOrientation="portrait"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
After coded, I called to my phone with different one.
But nothing happened, This codes are followed from open source, but nothing happened. Are there anybody who has already experienced? If it is, Please teach me what I wrong. Thank you.

Related

Phone state listener using broadcast receiver in android not working

I am trying to detect Incoming call using Broadcast Listener.Since I received one fault in my app when someone calls, my app still plays the song. So I want to pause song during Incoming Call. But I am not receiving any response.
Here is the complete code So that you all can understand where am I messing.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<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>
<receiver android:name=".IncomingCall">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
</application>
IncomingCall.java
package com.example.suraj.freewee;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
public class IncomingCall extends BroadcastReceiver {
private String LOG_TAG = getClass().getSimpleName();
TelephonyManager telephonyManager;
Context context;
#Override
public void onReceive(Context context, Intent intent) {
try {
this.context = context;
telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
MyPhoneStateListener phoneListener = new MyPhoneStateListener();
telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
Log.e(LOG_TAG, "inside on receive");
} catch (Exception e) {
e.printStackTrace();
Log.e(LOG_TAG, e.toString());
}
}
private class MyPhoneStateListener extends PhoneStateListener {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
Log.e(LOG_TAG, "Number : " + incomingNumber);
try {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING: {
//PAUSE
SongsAdapter.player.pause();
Log.e(getClass().getSimpleName(), "call ringing");
break;
}
case TelephonyManager.CALL_STATE_OFFHOOK: {
SongsAdapter.player.pause();
Log.e(getClass().getSimpleName(), "call offhook");
break;
}
case TelephonyManager.CALL_STATE_IDLE: {
//PLAY
SongsAdapter.player.start();
Log.e(getClass().getSimpleName(), "call idle");
break;
}
default: {
}
}
} catch (Exception ex) {
Log.e(getClass().getSimpleName(), "Error: " + ex.toString());
}
}
}
}
In logcat no log errors are shown
So why is this giving me such behaviour. thanks in advance
You're registering listener inside onReceive. That's pointless. As
Android documentation states:
A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active.
It should be enough to get EXTRA_STATE from Intent in onReceive and do your switch there.
If you're still not getting anything logged trim it to minimal case - leave only Log statement inside onReceive. Does it work? AFAIK there are two cases when app won't receive broadcast - If it was never started or if it was force stopped.
try editing onReceive() as below
public void onReceive(Context context, Intent intent)
{
TelephonyManager phoneManager =
(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
if(phoneManager.getCallState() == TelephonyManager.CALL_STATE_RINGING)
{
string fromNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.i(TAG, "u have a call from a number " + fromNumber);
}
}
Now call to ur number and see the number in logs

Android, TelephonyManager, the joys of PhoneStateListener and incoming numbers

I've very newly gotten into Android development, and decided that my first conquest on this fresh field would be to grasp how the phone reacted to incoming calls.
A little googling later led me to http://www.compiletimeerror.com/2013/08/android-call-state-listener-example.html#.Vi3Ren4vfwM (so my code shares a striking resemblance to his/hers).
My main (and only) activity looks like this:
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
TelephonyMgr.listen(new TeleListener(),
PhoneStateListener.LISTEN_CALL_STATE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
class TeleListener extends PhoneStateListener {
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
// CALL_STATE_IDLE;
Log.d("MyLittleDebugger", "I'm in " + state + " and the number is " + incomingNumber);
Toast.makeText(getApplicationContext(), "CALL_STATE_IDLE",
Toast.LENGTH_LONG).show();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
// CALL_STATE_OFFHOOK;
Log.d("MyLittleDebugger", "I'm in " + state + " and the number is " + incomingNumber);
Toast.makeText(getApplicationContext(), "CALL_STATE_OFFHOOK",
Toast.LENGTH_LONG).show();
break;
case TelephonyManager.CALL_STATE_RINGING:
// CALL_STATE_RINGING
Log.d("MyLittleDebugger", "I'm in " + state + " and the number is " + incomingNumber);
Toast.makeText(getApplicationContext(), incomingNumber,
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "CALL_STATE_RINGING",
Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
}
}
Now, here's where the fun stops. I got the app running on emulator, and used DDMS to spoof a few phone calls to my emulated device to see where the pieces landed.
And surely enough toast popped up and MyLittleDebugger flared up upon state swaps. The listener was working, however no number was ever being shown in my log or my toast.
It was just blank where the number should have been! Not null or anything, no, but blank!
After a little more googling, I realized that my AndroidManifest.xml might be the problem. It is as follows:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.x.xy" >
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<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>
Now, here's the question: what am I missing?
Clearly, a little fraction of a something has gone wrong somewhere, because I am able to have my TelephonyMgr object .listen() to call states, but I can't get the number to show.
New information:
I've also tried this on my phone, without emulating to the exact same result.
You probably need to make use of broadcast receiver which may help you what you trying to achieve.
create class extending broadcast receiver and in that try to catch the incoming number.
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
TelephonyManager mtelephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
mtelephony.listen(new PhoneStateListener(){
#Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
// CALL_STATE_RINGING
Log.d("MyLittleDebugger", "I'm in " + state + " and the number is " + incomingNumber);
Toast.makeText(getApplicationContext(), incomingNumber,
Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "CALL_STATE_RINGING",
Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
},PhoneStateListener.LISTEN_CALL_STATE);
}
and in your manifest this line as well.
<receiver android:name=".MyReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
I haven't used the listen function of TelephonyManager, but I did successfully use a BroadcastReceiver for getting the phone state changes and the phone number.
Register your receiver in the Activity or in the Manifest (if you want to receive updates when the app is in background):
Activity:
#Override
protected void onResume() {
super.onResume();
BroadcastReceiver receiver = new PhoneStateBroadcastReceiver();
IntentFilter filter= new IntentFilter();
filter.addAction("android.intent.action.PHONE_STATE");
filter.addAction("android.intent.action.NEW_OUTGOING_CALL");
registerReceiver(reciever, filter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(reciever);
}
Manifest:
<receiver
android:name=".PhoneStateBroadcastReceiver"
android:permission="android.permission.READ_PHONE_STATE" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
and a basic receiver:
public class PhoneStateBroadcastReceiver extends BroadcastReceiver {
private final String TAG = getClass().getName();
private static String number = null;
#Override
public void onReceive(final Context context, final Intent intent) {
if (intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
Log.d(TAG, intent.getAction() + ", EXTRA_STATE: " + state);
// on ringing get incoming number
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.d(TAG, "EXTRA_INCOMING_NUMBER: " + number);
}
}
if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Log.d(TAG, intent.getAction() + ", EXTRA_PHONE_NUMBER: " + number);
}
}
}
and in this SO answer you can find a nice implementation that also handles multiple calls:
https://stackoverflow.com/a/15564021/348378
I would advise you to run your app on a real working phone!
There are multiple reasons why a phone number is not available on all notifications, but you stand a much better chance of there being one if the call is from a real phone network that can provide the number.

Receiving the Broadcast

I want to make a application that gets the incoming calling number if the call is from a specific number then do some stuff . I want to get the incoming calling number even when the application is not running .. I am using the BraodcastReceiver to get the incoming number .
I have two java class one which extends he activity and the other extends the BraodcastReceiver for getting the incoming calling number .
Main class which extends activity :
package digicare.ringmanager;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class Main_Activity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_layout, menu);
return true;
}
}
it is pretty simple and the Number checker class which extends the BroadcastReceiver :
package digicare.ringmanager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
public class number_checker extends BroadcastReceiver {
private int ringer_mode ;
private String AM_str;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
AudioManager AM =(AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
Log.w("start", "starting the Main_Activity");
AM_str=String.valueOf(ringer_mode);
Log.w("Ringer_mode at start", AM_str);
//setting the ringer mode on number match
try {
Bundle extras=intent.getExtras();
if (extras !=null){
String state = extras.getString(TelephonyManager.EXTRA_STATE);
Log.w("state at start",state);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
String phonenumber = extras.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
//AM.setRingerMode(1);
ringer_mode =AM.getRingerMode();
AM_str=String.valueOf(ringer_mode);
Log.w("Ringer_mode at ringing", AM_str);
Log.w("Number", phonenumber);
if (phonenumber.equals("1234")){
Log.w("yahoo", "Number matched");
if (ringer_mode==AudioManager.RINGER_MODE_SILENT || ringer_mode==AudioManager.RINGER_MODE_VIBRATE ){
AM.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Log.w("Phone number is matched .!", "Now , ringer mode is normal");
int now_nor =AM.getRingerMode();
String now_nor_str=String.valueOf(now_nor);
Log.w("ring_mode at num matched",now_nor_str);
}
}
}
if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK ) || state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
int now_nor =AM.getRingerMode();
String now_nor_str=String.valueOf(now_nor);
Log.w("ring_mode at offHock",now_nor_str);
if (ringer_mode==AudioManager.RINGER_MODE_NORMAL){
AM.setRingerMode(AudioManager.RINGER_MODE_NORMAL );
Log.w("Normal", "");
}else if (ringer_mode==AudioManager.RINGER_MODE_SILENT ){
AM.setRingerMode(AudioManager.RINGER_MODE_SILENT );
Log.w("silent", "");
}else if (ringer_mode==AudioManager.RINGER_MODE_VIBRATE ){
AM.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
Log.w("vibrat", "");
}
// Log.w("Again", "Now the Ringer mode is get back ");
int now =AM.getRingerMode();
String now_str=String.valueOf(now);
Log.w("ring_mode at end ",now_str);
}
}
} catch (Exception e) {
// TODO: handle exception
Log.w("MY_DEBUG_TAG", e);
}
}
}
And the AndroidManifist.xml is this :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="digicare.ringmanager"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="5"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="digicare.ringmanager.Main_Activity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="number_checker" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
</application>
</manifest>
but this not working this cannot get the incoming calling number .
wot could i do ???? have to call the number_checker class for register the Braodcast ???
please help i am a new android developer
You can either dynamically register an instance of this class with Context.registerReceiver() or statically publish an implementation through the tag in your AndroidManifest.xml.
Note: If registering a receiver in your Activity.onResume() implementation, you should unregister it in Activity.onPause(). (You won't receive intents when paused, and this will cut down on unnecessary system overhead). Do not unregister in Activity.onSaveInstanceState(), because this won't be called if the user moves back in the history stack.
also check this link :
http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html
NEW Update:
check this link http://androidexample.com/Incomming_Phone_Call_Broadcast_Receiver__-_Android_Example/index.php?view=article_discription&aid=61&aaid=86
Update 2
put . before the receiver name. like this <receiver android:name=".number_checker" >

How to start a service upon device boot up? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Trying to start a service on boot on Android
BroadcastReceiver
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class StartActivityAtBoot extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent i = new Intent(context, CompareIMSI.class);
context.startService(i);
}
}
}
CompareSIM.java
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.widget.Toast;
public class CompareIMSI extends Service{
Context context;
TelephonyManager operator;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
//compareSIM();
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
compareSIM();
}
public void compareSIM(){
final String STORAGE = "Storage";
SharedPreferences unique = getSharedPreferences(STORAGE, 0);
final String storedIMSI = unique.getString("simIMSI", "");
final String currentIMSI = getSubscriberId().toString();
if (!storedIMSI.equals(currentIMSI)){
Intent i = new Intent(CompareIMSI.this, ScreenLockActivity.class);
startActivity(i);
}
}
public String getSubscriberId(){
String IMSI = null;
String serviceName = Context.TELEPHONY_SERVICE;
TelephonyManager m_telephonyManager = (TelephonyManager) getSystemService(serviceName);
IMSI = m_telephonyManager.getSubscriberId();
return IMSI;
}
}
I would like the application to start the compareSIM service upon boot up, during boot up, this service will run as the current attached SIM card IMSI will be retrieved and matched with the already saved IMSI, once they are different the user will be brought to a login layout. I want to perform this during boot up but failed to do so... Kindly advice me on the coding, thanks
floow these steps for stating your service on BOOT:
Step 1: In AndroidManifest.xml add BOOT_COMPLETED permission as:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
Step 2: In AndroidManifest.xml Register your Reciver as:
<receiver android:name=".StartActivityAtBoot" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>
Step 3: In AndroidManifest.xml Register your Service as:
<service android:name=".CompareIMSI"> </service>
Step 3: In StartActivityAtBoot Start your service as:
public class StartActivityAtBoot extends BroadcastReceiver
{
static final String ACTION = "android.intent.action.BOOT_COMPLETED";
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(ACTION))
{
context.startService(new Intent(context,
CompareIMSI.class), null);
Toast.makeText(context, "CompareIMSI service has started!", Toast.LENGTH_LONG).show();
}
}
}
This is all about Starting a Service on Boot.Thanks
You need to register the BroadcastReceiver in the Android manifest, like this:
<receiver android:name=".StartActivityAtBoot">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Also make sure that you have this permission in the manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Check Your androidManifest file. You need to add receiver at androidManifest file.
<receiver android:name=".......StartActivityAtBoot" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>

Retrieve incoming call's phone number in Android

I would like to retrieve the incoming call's phonenumber and do something with it like the do
in http://blog.whitepages.com/2009/02/27/caller-id-by-whitepages-a-new-android-app-that-puts-telemarketers-on-alert/
Could you please help me because I can't find any information about this.
Where do i start and how do i get hold of the phonenumber?
Ok so currently my code looks like below. When I place the call the CustomBroadcastReceiver catches it and the log message is printed out. I can retrieve the telephone number from the bundle. But! I can't get hte CustomPhoneStateListener to work. As you can see I have registered my customPhoneState listener to the receiver but the log message never get's printed out from the CustomPhoneStateListener class. What am I my missing here?
Is my thinking correct?
<receiver android:name=".CustomBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
</application>
<uses-sdk android:minSdkVersion="5" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
public class CustomPhoneStateListener extends PhoneStateListener {
private static final String TAG = "CustomPhoneStateListener";
public void onCallStateChange(int state, String incomingNumber){
Log.v(TAG, "WE ARE INSIDE!!!!!!!!!!!");
Log.v(TAG, incomingNumber);
switch(state){
case TelephonyManager.CALL_STATE_RINGING:
Log.d(TAG, "RINGING");
break;
}
}
public class CustomBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "CustomBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "WE ARE INSIDE!!!!!!!!!!!");
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
CustomPhoneStateListener customPhoneListener = new CustomPhoneStateListener();
telephony.listen(customPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
Bundle bundle = intent.getExtras();
String phoneNr= bundle.getString("incoming_number");
Log.v(TAG, "phoneNr: "+phoneNr);
}
Use PhoneStateListener. It has an onCallStateChanged handler; one of the supplied arguments you'll get is a String containing the incoming phone number.
Your overridden method in CustomPhoneStateListener should be called onCallStateChanged() (and not onCallStateChange()).
This would have been spotted by the Java compiler if you would have had the #Override annotation, like you have for onReceive().
The above answers are out-od-dated now. There are valid for Android 7 and lower.
For android 9 and higher you have to add another permission in the Androidmanifest.xml with the permission
<uses-permission android:name="android.permission.READ_CALL_LOG"/>
without the phone number will be null. For Android 8 I am not sure.
PhoneStateReciever.java
package com.incomingcalls;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
public class PhoneStateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
try {
System.out.println("Receiver start");
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.e("Incoming Number", "Number is ," + incomingNumber);
Log.e("State", "State is ," + state);
if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
Toast.makeText(context,"Incoming Call State",Toast.LENGTH_SHORT).show();
Toast.makeText(context,"Ringing State Number is -"+incomingNumber,Toast.LENGTH_SHORT).show();
}
if ((state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))){
Toast.makeText(context,"Call Received State",Toast.LENGTH_SHORT).show();
}
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
Toast.makeText(context,"Call Idle State",Toast.LENGTH_SHORT).show();
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
AnroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.incomingcalls">
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".PhoneStateReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
</application>
</manifest>

Categories

Resources