I am developing an application where one of the things we need is to control the outgoing call, at least to be able to stop it from our application.
I've tried using Intent.ACTION_CALL from an existing activity:
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber));
startActivity(callIntent);
But stopping the call seems to be disallowed through the API.
Can you suggest some workaround?
For example: enabling airplane mode during the call? Just an example; this hack didn't work for me.
Capturing the outgoing call in a BroadcastReceiver has been mentioned and is definitely the best way to do it if you want to end the call before dialing.
Once dialing or in-call, however, that technique no longer works. The only way to hang up that I've encountered so far, is to do so through Java Reflection. As it is not part of the public API, you should be careful to use it, and not rely upon it. Any change to the internal composition of Android will effectively break your application.
Prasanta Paul's blog demonstrates how it can be accomplished, which I have summarized below.
Obtaining the ITelephony object:
TelephonyManager tm = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
try {
// Java reflection to gain access to TelephonyManager's
// ITelephony getter
Log.v(TAG, "Get getTeleService...");
Class c = Class.forName(tm.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
com.android.internal.telephony.ITelephony telephonyService =
(ITelephony) m.invoke(tm);
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG,
"FATAL ERROR: could not connect to telephony subsystem");
Log.e(TAG, "Exception object: " + e);
}
Ending the call:
telephonyService.endCall();
EDIT: To Android P or newer, please see: https://stackoverflow.com/a/51121175/450148
Try this:
(I used Reflection to access advanced telephony features and modify somethings)
// required permission <uses-permission android:name="android.permission.CALL_PHONE"/>
try {
//String serviceManagerName = "android.os.IServiceManager";
String serviceManagerName = "android.os.ServiceManager";
String serviceManagerNativeName = "android.os.ServiceManagerNative";
String telephonyName = "com.android.internal.telephony.ITelephony";
Class telephonyClass;
Class telephonyStubClass;
Class serviceManagerClass;
Class serviceManagerStubClass;
Class serviceManagerNativeClass;
Class serviceManagerNativeStubClass;
Method telephonyCall;
Method telephonyEndCall;
Method telephonyAnswerCall;
Method getDefault;
Method[] temps;
Constructor[] serviceManagerConstructor;
// Method getService;
Object telephonyObject;
Object serviceManagerObject;
telephonyClass = Class.forName(telephonyName);
telephonyStubClass = telephonyClass.getClasses()[0];
serviceManagerClass = Class.forName(serviceManagerName);
serviceManagerNativeClass = Class.forName(serviceManagerNativeName);
Method getService = // getDefaults[29];
serviceManagerClass.getMethod("getService", String.class);
Method tempInterfaceMethod = serviceManagerNativeClass.getMethod(
"asInterface", IBinder.class);
Binder tmpBinder = new Binder();
tmpBinder.attachInterface(null, "fake");
serviceManagerObject = tempInterfaceMethod.invoke(null, tmpBinder);
IBinder retbinder = (IBinder) getService.invoke(serviceManagerObject, "phone");
Method serviceMethod = telephonyStubClass.getMethod("asInterface", IBinder.class);
telephonyObject = serviceMethod.invoke(null, retbinder);
//telephonyCall = telephonyClass.getMethod("call", String.class);
telephonyEndCall = telephonyClass.getMethod("endCall");
//telephonyAnswerCall = telephonyClass.getMethod("answerRingingCall");
telephonyEndCall.invoke(telephonyObject);
} catch (Exception e) {
e.printStackTrace();
Log.error(DialerActivity.this,
"FATAL ERROR: could not connect to telephony subsystem");
Log.error(DialerActivity.this, "Exception object: " + e);
}
Create a BroadcastReceiver with a priority of 0.
In the BC intercept the ACTION_NEW_OUTGOING_CALL intent in its onReceive method
call setResultData(null) in the same method
This will prevent the call from initiating (as long as your receiver is the last to process the intent I think)
Here's the most updated code, which will work for Android P too, because it has an official API for it (here) :
in manifest, add this:
<uses-permission android:name="android.permission.ANSWER_PHONE_CALLS"/>
In code, use this:
Java:
#SuppressLint("PrivateApi")
public static boolean endCall(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
final TelecomManager telecomManager = (TelecomManager) context.getSystemService(Context.TELECOM_SERVICE);
if (telecomManager != null && ContextCompat.checkSelfPermission(context, Manifest.permission.ANSWER_PHONE_CALLS) == PackageManager.PERMISSION_GRANTED) {
telecomManager.endCall();
return true;
}
return false;
}
//use unofficial API for older Android versions, as written here: https://stackoverflow.com/a/8380418/878126
try {
final Class<?> telephonyClass = Class.forName("com.android.internal.telephony.ITelephony");
final Class<?> telephonyStubClass = telephonyClass.getClasses()[0];
final Class<?> serviceManagerClass = Class.forName("android.os.ServiceManager");
final Class<?> serviceManagerNativeClass = Class.forName("android.os.ServiceManagerNative");
final Method getService = serviceManagerClass.getMethod("getService", String.class);
final Method tempInterfaceMethod = serviceManagerNativeClass.getMethod("asInterface", IBinder.class);
final Binder tmpBinder = new Binder();
tmpBinder.attachInterface(null, "fake");
final Object serviceManagerObject = tempInterfaceMethod.invoke(null, tmpBinder);
final IBinder retbinder = (IBinder) getService.invoke(serviceManagerObject, "phone");
final Method serviceMethod = telephonyStubClass.getMethod("asInterface", IBinder.class);
final Object telephonyObject = serviceMethod.invoke(null, retbinder);
final Method telephonyEndCall = telephonyClass.getMethod("endCall");
telephonyEndCall.invoke(telephonyObject);
return true;
} catch (Exception e) {
e.printStackTrace();
LogManager.e(e);
}
return false;
}
or in Kotlin:
#SuppressLint("PrivateApi")
fun endCall(context: Context): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
val telecomManager = context.getSystemService(Context.TELECOM_SERVICE) as TelecomManager
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ANSWER_PHONE_CALLS) == PackageManager.PERMISSION_GRANTED) {
telecomManager.endCall()
return true
}
return false
}
//use unofficial API for older Android versions, as written here: https://stackoverflow.com/a/8380418/878126
try {
val telephonyClass = Class.forName("com.android.internal.telephony.ITelephony")
val telephonyStubClass = telephonyClass.classes[0]
val serviceManagerClass = Class.forName("android.os.ServiceManager")
val serviceManagerNativeClass = Class.forName("android.os.ServiceManagerNative")
val getService = serviceManagerClass.getMethod("getService", String::class.java)
val tempInterfaceMethod = serviceManagerNativeClass.getMethod("asInterface", IBinder::class.java)
val tmpBinder = Binder()
tmpBinder.attachInterface(null, "fake")
val serviceManagerObject = tempInterfaceMethod.invoke(null, tmpBinder)
val retbinder = getService.invoke(serviceManagerObject, "phone") as IBinder
val serviceMethod = telephonyStubClass.getMethod("asInterface", IBinder::class.java)
val telephonyObject = serviceMethod.invoke(null, retbinder)
val telephonyEndCall = telephonyClass.getMethod("endCall")
telephonyEndCall.invoke(telephonyObject)
return true
} catch (e: Exception) {
e.printStackTrace()
return false
}
}
You can try enabling then disabling airplane mode:
android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.AIRPLANE_MODE_ON, 1);
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", 1);
sendBroadcast(new Intent("android.intent.action.AIRPLANE_MODE"));
sendBroadcast(intent);
android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.AIRPLANE_MODE_ON, 0);
intent.putExtra("state", 0);
sendBroadcast(new Intent("android.intent.action.AIRPLANE_MODE"));
sendBroadcast(intent);
For Ilana:
public class ilanasReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
if (getResultData()!=null) {
String number = "123456";
setResultData(number);
}
}
}
}
In addition in Manifest put in package section:
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
That is all.
Considering the potential for wonderful mischief I would be surprised if this is allowed.
This thread says flatly that the API cannot end a call. Others have tried.
According to the documentation on ACTION_NEW_OUTGOING_CALL
The Intent will have the following extra value:
EXTRA_PHONE_NUMBER - the phone number originally intended to be dialed.
Once the broadcast is finished, the resultData is used as the actual number to call. If null, no call will be placed.
Related
I try below code but it return null for both.
TelephonyManager telephonyInfo = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE));
telephonyInfo.serialSIM1 = telephonyManager.getSimSerialNumber();
telephonyInfo.serialSIM2 = null;
try {
telephonyInfo.serialSIM1 = getSerialBySlot(context, "getSimSerialNumberGemini", 0);
telephonyInfo.serialSIM2 = getSerialBySlot(context, "getSimSerialNumberGemini", 1);
} catch (GeminiMethodNotFoundException e) {
e.printStackTrace();
try {
telephonyInfo.serialSIM1 = getSerialBySlot(context, "getSimSerialNumber", 0);
telephonyInfo.serialSIM2 = getSerialBySlot(context, "getSimSerialNumber", 1);
} catch (GeminiMethodNotFoundException e1) {
//Call here for next manufacturer's predicted method name if you wish
e1.printStackTrace();
}
}
private static String getSerialBySlot(Context context, String predictedMethodName, int slotID) throws GeminiMethodNotFoundException {
String lsSerialNumber = null;
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try{
Class<?> telephonyClass = Class.forName(telephony.getClass().getName());
Class<?>[] parameter = new Class[1];
parameter[0] = int.class;
Method getSimID = telephonyClass.getMethod(predictedMethodName, parameter);
Object[] obParameter = new Object[1];
obParameter[0] = slotID;
Object ob_phone = getSimID.invoke(telephony, obParameter);
if(ob_phone != null){
lsSerialNumber = ob_phone.toString();
}
} catch (Exception e) {
e.printStackTrace();
throw new GeminiMethodNotFoundException(predictedMethodName);
}
return lsSerialNumber;
}
private static class GeminiMethodNotFoundException extends Exception {
private static final long serialVersionUID = -996812356902545308L;
public GeminiMethodNotFoundException(String info) {
super(info);
}
}
Then use it.
String getSerialNumber1 = telephonyInfo.getSerialSIM1();
String getSerialNumber2 = telephonyInfo.getSerialSIM2();
Log.i(TAG, "state getSerialNumber1 : " + getSerialNumber1);
Log.i(TAG, "state getSerialNumber2 : " + getSerialNumber2);
Below is the log which is got in logcat
09-16 07:20:07.042 6973-6973/app.myApp I/SimChangeReceiver: state getSerialNumber1 : null
09-16 07:20:07.042 6973-6973/app.myApp I/SimChangeReceiver: state getSerialNumber2 : null
I can get IMEI and the dual sim or not.
I search around for the related question,But I did not found any other method.
try this i have not tested but it might help you.
Instead of using getSimSerialNumber, you can use SubscriptionManager.
// Requires, android.permission.READ_PHONE_STATE
SubscriptionManager sm = SubscriptionManager.from(mContext);
// it returns a list with a SubscriptionInfo instance for each simcard
// there is other methods to retrieve SubscriptionInfos (see [2])
List<SubscriptionInfo> sis = sm.getActiveSubscriptionInfoList();
// getting first SubscriptionInfo
SubscriptionInfo si = sis.get(0);
// getting iccId
String iccId = si.getIccId();
I am trying to get a list of networks on Android devices that have multiple SIM cards "dual sim."
I use the TelephonyManager class but the method getNetworkType only returns the network for the first sim "sim 1."
There's no API for this before Android Android 5.1 (API22). But then you have SubscriptionManager and its getActiveSubscriptionInfoList()
I have found a posible solution. I have used the android reflection to call TelephonyManager methods for example if i want the data Network I can use getDataNetworkType as follows:
getNetworkTypeReflection(telephonyManager, "getDataNetworkType", slot, false);
private static String getNetworkTypeReflection(final TelephonyManager telephony, final String predictedMethodName, final int slotID, final boolean isPrivate) {
String result = null;
try {
final Class<?> telephonyClass = Class.forName(telephony.getClass().getName());
final Class<?>[] parameter = new Class[1];
parameter[0] = int.class;
final Method getSubtecnology;
if (slotID != -1) {
if (isPrivate) {
getSubtecnology = telephonyClass.getDeclaredMethod(predictedMethodName, parameter);
} else {
getSubtecnology = telephonyClass.getMethod(predictedMethodName, parameter);
}
} else {
if (isPrivate) {
getSubtecnology = telephonyClass.getDeclaredMethod(predictedMethodName);
} else {
getSubtecnology = telephonyClass.getMethod(predictedMethodName);
}
}
final Object obPhone;
final Object[] obParameter = new Object[1];
obParameter[0] = slotID;
if (getSubtecnology != null) {
if (slotID != -1) {
obPhone = getSubtecnology.invoke(telephony, obParameter);
} else {
obPhone = getSubtecnology.invoke(telephony);
}
if (obPhone != null) {
result = obPhone.toString();
}
}
} catch (Exception e) {
//e.printStackTrace();
return null;
}
return result;
}
The problem is that this option only works on Android 5.1 (API22) but only in some device in others you need Android 7.0 (API24).
If anyone has other options are welcome.
I am writing an android app in which I need to answer an incoming call, do some work and then end the call.
After all the Googling I could find two different ways to achieve this both of which do not work with recent versions of Android, specifically after 4.1, Jelly Bean.
I.) Access "com.android.internal.telephony.ITelephony" using Java Reflection in the Broadcast receiver for "android.intent.action.PHONE_STATE". Below sample code can be found in hundreds of related post:
public class PhoneCallReceiver extends BroadcastReceiver {
Context context = null;
private static final String TAG = "Phone call";
private ITelephony telephonyService;
#Override
public void onReceive(Context context, Intent intent) {
if (!intent.getAction().equals("android.intent.action.PHONE_STATE"))
return;
Log.v(TAG, "Receving....");
TelephonyManager telephony = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
try {
Log.v(TAG, "Get getTeleService...");
Class c = Class.forName(telephony.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
telephonyService = (ITelephony) m.invoke(telephony);
telephonyService.silenceRinger();
Log.v(TAG, "Answering Call now...");
telephonyService.answerRingingCall();
Log.v(TAG, "Call answered...");
//telephonyService.endCall();
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG,
"FATAL ERROR: could not connect to telephony subsystem");
Log.e(TAG, "Exception object: " + e);
}
}
}
The problem with this code is that
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
is required for this method to work, and this permission has been defined as "for system apps only" from android v 2.3. In short, normal user apps can not define this permission in the manifest file anymore.
II.) Another way is to simulate pushing of the Headset hook which makes Android answer the call. This is done by broadcasting the "Intent.ACTION_MEDIA_BUTTON" as shown in below code.
public class PhoneCallReceiver extends BroadcastReceiver {
Context context = null;
private static final String TAG = "Phone call";
#Override
public void onReceive(Context context, Intent intent) {
if (!intent.getAction().equals("android.intent.action.PHONE_STATE"))
return;
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Intent answer = new Intent(Intent.ACTION_MEDIA_BUTTON);
answer.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
context.sendOrderedBroadcast(answer, null);
Log.d(TAG, "Answered incoming call from: " + number);
}
return;
}
}
This method works till Android 4.1 after which android has restricted user apps from broadcasting "Intent.ACTION_MEDIA_BUTTON".
So my conclusion is that currently there is no way how we can achieve this in Android 4.1 or later.
Has anybody else found any other solution or workaround to this problem?
This works from Android 2.2 to 4.0 and now after adding the try catch to the last line it works for 4.1.2 and 4.2 Frankly speaking dont know how it works but it works for me.
Log.d(tag, "InSecond Method Ans Call");
// froyo and beyond trigger on buttonUp instead of buttonDown
Intent buttonUp = new Intent(Intent.ACTION_MEDIA_BUTTON);
buttonUp.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
sendOrderedBroadcast(buttonUp, "android.permission.CALL_PRIVILEGED");
Intent headSetUnPluggedintent = new Intent(Intent.ACTION_HEADSET_PLUG);
headSetUnPluggedintent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
headSetUnPluggedintent.putExtra("state", 0);
headSetUnPluggedintent.putExtra("name", "Headset");
try {
sendOrderedBroadcast(headSetUnPluggedintent, null);
} catch (Exception e) {
e.printStackTrace();
}
This is working for me in Android 4.1.2 as well as i have tested on 4.2
This still gives an exception which is handled.
Edit for End Call
Hope this helps all the people looking for total solution for answer and end call.
/**
* Reject button click listener will reject the incoming call.
*/
private class RejectCallOnClickListener implements OnClickListener {
#Override
public void onClick(View v) {
Log.d(tag, "OnRejectButton: " + "Reject OnClick");
ignoreCall();
exitCleanly();
}
}
/**
* ignore incoming calls
*/
private void ignoreCall() {
if (USE_ITELEPHONY)
ignoreCallAidl();
else
ignoreCallPackageRestart();
}
/**
* AIDL/ITelephony technique for ignoring calls
*/
private void ignoreCallAidl() {
try {
// telephonyService.silenceRinger();
telephonyService.endCall();
} catch (RemoteException e) {
e.printStackTrace();
Log.d(tag, "ignoreCall: " + "Error: " + e.getMessage());
} catch (Exception e) {
e.printStackTrace();
Log.d(tag, "ignoreCall" + "Error: " + e.getMessage());
}
}
/**
* package restart technique for ignoring calls
*/
private void ignoreCallPackageRestart() {
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
am.restartPackage("com.android.providers.telephony");
am.restartPackage("com.android.phone");
}
/**
* cleanup and exit routine
*/
private void exitCleanly() {
unHookReceiver();
this.finish();
}
My application has been using the following code to answer the phone for about 6 months:
Intent i = new Intent(Intent.ACTION_MEDIA_BUTTON);
i.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP,
KeyEvent.KEYCODE_HEADSETHOOK));
context.sendOrderedBroadcast(i, null);
I have tested this on Android Versions from 2.2 to 4.2.2. I have not seen a SecurityException broadcasting "Intent.ACTION_MEDIA_BUTTON" in my testing n a 4.2.2 device, nor have I seen crash reports from the Play Store indicating such exceptions are occurring.
I will say that this does not always work. It does not work on HTC devices due to the fact that HTC devices have a HeadsetObeserver that listen for the actually plugging in of a wired headset. Without this event, which it is currently a SecurityException for a third party app to broadcast, the HeadsetHook KeyEvent goes ignored.
The previous answers are misleading. The following code block does nothing:
Intent headSetUnPluggedintent = new Intent(Intent.ACTION_HEADSET_PLUG);
headSetUnPluggedintent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
headSetUnPluggedintent.putExtra("state", 0);
headSetUnPluggedintent.putExtra("name", "Headset");
try {
sendOrderedBroadcast(headSetUnPluggedintent, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
except generate a SecurityException and catch it.
In the other answers where the code works, it is because of the KeyEvent.KEYCODE_HEADSETHOOK being broadcast.
Try this
Answer for end the call using pro grammatically. Its working fine for me.
try {
String serviceManagerName = "android.os.ServiceManager";
String serviceManagerNativeName = "android.os.ServiceManagerNative";
String telephonyName = "com.android.internal.telephony.ITelephony";
Class telephonyClass;
Class telephonyStubClass;
Class serviceManagerClass;
Class serviceManagerStubClass;
Class serviceManagerNativeClass;
Class serviceManagerNativeStubClass;
Method telephonyCall;
Method telephonyEndCall;
Method telephonyAnswerCall;
Method getDefault;
Method[] temps;
Constructor[] serviceManagerConstructor;
// Method getService;
Object telephonyObject;
Object serviceManagerObject;
telephonyClass = Class.forName(telephonyName);
telephonyStubClass = telephonyClass.getClasses()[0];
serviceManagerClass = Class.forName(serviceManagerName);
serviceManagerNativeClass = Class.forName(serviceManagerNativeName);
Method getService = // getDefaults[29];
serviceManagerClass.getMethod("getService", String.class);
Method tempInterfaceMethod = serviceManagerNativeClass.getMethod(
"asInterface", IBinder.class);
Binder tmpBinder = new Binder();
tmpBinder.attachInterface(null, "fake");
serviceManagerObject = tempInterfaceMethod.invoke(null, tmpBinder);
IBinder retbinder = (IBinder) getService.invoke(serviceManagerObject, "phone");
Method serviceMethod = telephonyStubClass.getMethod("asInterface", IBinder.class);
telephonyObject = serviceMethod.invoke(null, retbinder);
//telephonyCall = telephonyClass.getMethod("call", String.class);
telephonyEndCall = telephonyClass.getMethod("endCall");
//telephonyAnswerCall = telephonyClass.getMethod("answerRingingCall");
telephonyEndCall.invoke(telephonyObject);
} catch (Exception e) {
e.printStackTrace();
Log.error(DialerActivity.this,
"FATAL ERROR: could not connect to telephony subsystem");
Log.error(DialerActivity.this, "Exception object: " + e);
}
As a conclusion to this thread, here is the code that works for me for Android 4.2.2.
--> Call is answered by simulating push of headset hook and keeping the broadcast in try-catch as mentioned by #PravinDodia in abouve thread. (Observe that an exception is thrown and handled in catch and the call is answered anyway. So I guess we can just ignore this exception and continue living life as if nothing happened! )
--> Call is disconnected using ITelephony.
public class PhoneCallReceiver extends BroadcastReceiver {
Context context = null;
private static final String TAG = "Phone call";
#Override
public void onReceive(Context context, Intent intent) {
if (!intent.getAction().equals("android.intent.action.PHONE_STATE"))
return;
else {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
answerPhoneHeadsethook(context, intent);
return;
}
else if(state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
Log.d(TAG, "CALL ANSWERED NOW!!");
try {
synchronized(this) {
Log.d(TAG, "Waiting for 10 sec ");
this.wait(10000);
}
}
catch(Exception e) {
Log.d(TAG, "Exception while waiting !!");
e.printStackTrace();
}
disconnectPhoneItelephony(context);
return;
}
else {
Log.d(TAG, "ALL DONE ...... !!");
}
}
}
public void answerPhoneHeadsethook(Context context, Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.d(TAG, "Incoming call from: " + number);
Intent buttonUp = new Intent(Intent.ACTION_MEDIA_BUTTON);
buttonUp.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
try {
context.sendOrderedBroadcast(buttonUp, "android.permission.CALL_PRIVILEGED");
Log.d(TAG, "ACTION_MEDIA_BUTTON broadcasted...");
}
catch (Exception e) {
Log.d(TAG, "Catch block of ACTION_MEDIA_BUTTON broadcast !");
}
Intent headSetUnPluggedintent = new Intent(Intent.ACTION_HEADSET_PLUG);
headSetUnPluggedintent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
headSetUnPluggedintent.putExtra("state", 1); // 0 = unplugged 1 = Headset with microphone 2 = Headset without microphone
headSetUnPluggedintent.putExtra("name", "Headset");
// TODO: Should we require a permission?
try {
context.sendOrderedBroadcast(headSetUnPluggedintent, null);
Log.d(TAG, "ACTION_HEADSET_PLUG broadcasted ...");
}
catch (Exception e) {
// TODO Auto-generated catch block
//e.printStackTrace();
Log.d(TAG, "Catch block of ACTION_HEADSET_PLUG broadcast");
Log.d(TAG, "Call Answered From Catch Block !!");
}
Log.d(TAG, "Answered incoming call from: " + number);
}
Log.d(TAG, "Call Answered using headsethook");
}
public static void disconnectPhoneItelephony(Context context) {
ITelephony telephonyService;
Log.v(TAG, "Now disconnecting using ITelephony....");
TelephonyManager telephony = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
try {
Log.v(TAG, "Get getTeleService...");
Class c = Class.forName(telephony.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
telephonyService = (ITelephony) m.invoke(telephony);
//telephonyService.silenceRinger();
Log.v(TAG, "Disconnecting Call now...");
//telephonyService.answerRingingCall();
//telephonyService.endcall();
Log.v(TAG, "Call disconnected...");
telephonyService.endCall();
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG,
"FATAL ERROR: could not connect to telephony subsystem");
Log.e(TAG, "Exception object: " + e);
}
}
}
At least the disconnect functionality works and we know how it works. So those who want to develop a Call Barring application can go ahead.
For those like me who want to answer a call, I guess we can use this for now and only hope that it does not stop working in the next version.
Try this :
Intent buttonDown = new Intent(Intent.ACTION_MEDIA_BUTTON);
buttonDown.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK));
context.sendOrderedBroadcast(buttonDown, "android.permission.CALL_PRIVILEGED");
// froyo and beyond trigger on buttonUp instead of buttonDown
Intent buttonUp = new Intent(Intent.ACTION_MEDIA_BUTTON);
buttonUp.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
context.sendOrderedBroadcast(buttonUp, "android.permission.CALL_PRIVILEGED");
Add permissions in AndroidManifest.xml file as
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE"/>
ITelephony method does not work on 4.4 and I find the headset/media button method still allows a fairly long ring before hangup.
This chaps blog post shows a new method that I have tested as working on 4.4.2 Galaxy s4 and HTC one mini that hangs up much more quickly and you don't get a missed call entry either.
http://aprogrammersday.blogspot.co.uk/2014/05/disconnect-block-drop-calls-android-4.html
The technique uses a runtime exec as below, apparently you may need to use a different number for some devices.
public class HangupPhoneCallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (TelephonyManager.EXTRA_STATE_RINGING.equals(intent.getStringExtra(TelephonyManager.EXTRA_STATE))) {
Executor eS = Executors.newSingleThreadExecutor();
eS.execute(new Runnable() {
#Override
public void run() {
Runtime runtime = Runtime.getRuntime();
try {
Log.d(TAG, "service call phone 5 \n");
runtime.exec("service call phone 5 \n");
} catch (Exception exc) {
Log.e(TAG, exc.getMessage());
}
}
});
return;
}
}
}
Call disconnecting using IT Telephony doesn't work on some devices like Samsung S Duos. But you can still make ringer silent :)
To end call in older version then 9.0
use this:
TelephonyManager tm = (TelephonyManager)context.getSystemService(TELEPHONY_SERVICE);
Method m1 = null;
try {
m1 = tm.getClass().getDeclaredMethod("getITelephony");
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
m1.setAccessible(true);
Object iTelephony = null;
try {
iTelephony = m1.invoke(tm);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
Method m3 = null;
try {
m3 = iTelephony.getClass().getDeclaredMethod("endCall");
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
m3.invoke(iTelephony);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
& for pie
TelecomManager telecomManager = (TelecomManager) context.getSystemService(Context.TELECOM_SERVICE);
if (telecomManager != null) {
return telecomManager.endCall();
}
Make sure your compile SDK version is 28
private void PhoneControl(int nControl) {
if(nControl == PHONE_END_CALL) { // End call, all Android version
try {
TelecomManager telecomManager = (TelecomManager) context.getSystemService(Context.TELECOM_SERVICE);
if (telecomManager != null) {
telecomManager.endCall();
}
}catch (Exception e) {}
try {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if(tm == null)
return;
tm.getClass().getMethod("endCall").invoke(tm);
bIsEnding = true;
} catch (Exception e) {
/* Do Nothing */ }
}
if(nControl == PHONE_ACCEPT_CALL) { // Accept phone call
// if(!bCallAccepted) { // Call déjà accepté => pas d'action (évite double action)
bCallAccepted = true;
if(Build.VERSION.SDK_INT >= 26) { // Pris en charge Android >= 8.0
if(context.checkSelfPermission("android.permission.ANSWER_PHONE_CALLS") == PackageManager.PERMISSION_GRANTED) {
TelecomManager tm = (TelecomManager) context.getSystemService(Context.TELECOM_SERVICE);
if(tm != null)
tm.acceptRingingCall();
}
}
if(Build.VERSION.SDK_INT >= 23 && Build.VERSION.SDK_INT < 26) { // Hangup in Android 6.x and 7.x
MediaSessionManager mediaSessionManager = (MediaSessionManager) context.getSystemService(Context.MEDIA_SESSION_SERVICE);
if(mediaSessionManager != null) {
try {
List<MediaController> mediaControllerList = mediaSessionManager.getActiveSessions
(new ComponentName(context, NotificationReceiverService.class));
for (MediaController m : mediaControllerList) {
if ("com.android.server.telecom".equals(m.getPackageName())) {
m.dispatchMediaButtonEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK));
m.dispatchMediaButtonEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
break;
}
}
} catch (Exception e) {
// Toast.makeText(instance, "sdfsdf123123"+e, Toast.LENGTH_LONG).show();
Intent answerCalintent = new Intent(context, AcceptCallActivity.class);
answerCalintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK |
Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(answerCalintent);
/* Do Nothing */ }
}
// new Thread(new Runnable() {
//
// #Override
// public void run() {
// try {
// Runtime.getRuntime().exec("input keyevent " +
// Integer.toString(KeyEvent.KEYCODE_HEADSETHOOK));
// } catch (IOException e) {
// // Runtime.exec(String) had an I/O problem, try to fall back
// String enforcedPerm = "android.permission.CALL_PRIVILEGED";
// Intent btnDown = new Intent(Intent.ACTION_MEDIA_BUTTON).putExtra(
// Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN,
// KeyEvent.KEYCODE_HEADSETHOOK));
// Intent btnUp = new Intent(Intent.ACTION_MEDIA_BUTTON).putExtra(
// Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP,
// KeyEvent.KEYCODE_HEADSETHOOK));
//
// context.sendOrderedBroadcast(btnDown, enforcedPerm);
// context.sendOrderedBroadcast(btnUp, enforcedPerm);
// }
// }
//
// }).start();
}
if(Build.VERSION.SDK_INT < 23) { // Prend en charge jusqu'à Android 5.1
try {
if(Build.MANUFACTURER.equalsIgnoreCase("HTC")) { // Uniquement pour HTC
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
if(audioManager!=null && !audioManager.isWiredHeadsetOn()) {
Intent i = new Intent(Intent.ACTION_HEADSET_PLUG);
i.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
i.putExtra("state", 0);
i.putExtra("name", "Orasi");
try {
context.sendOrderedBroadcast(i, null);
} catch (Exception e) { /* Do Nothing */ }
}
}
Runtime.getRuntime().exec("input keyevent " +
Integer.toString(KeyEvent.KEYCODE_HEADSETHOOK));
} catch (Exception e) {
// Runtime.exec(String) had an I/O problem, try to fall back
String enforcedPerm = "android.permission.CALL_PRIVILEGED";
Intent btnDown = new Intent(Intent.ACTION_MEDIA_BUTTON).putExtra(
Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_HEADSETHOOK));
Intent btnUp = new Intent(Intent.ACTION_MEDIA_BUTTON).putExtra(
Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP,
KeyEvent.KEYCODE_HEADSETHOOK));
context.sendOrderedBroadcast(btnDown, enforcedPerm);
context.sendOrderedBroadcast(btnUp, enforcedPerm);
}
}
// }
}
}
<!--Incoming call state Listen-->
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- Store Data in Device/Shared pref-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--Get Incoming Number-->
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<!--Answer call-->
<uses-permission android:name="android.permission.ANSWER_PHONE_CALLS" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission
android:name="android.permission.MODIFY_PHONE_STATE"
tools:ignore="ProtectedPermissions" />
<!--End Calll-->
<uses-permission android:name="android.permission.CALL_PHONE" />
public class NotificationReceiverService extends NotificationListenerService {
public NotificationReceiverService() {
}
}
<service
android:name=".notifications.NotificationReceiverService"
android:enabled="true"
android:exported="true"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
if(Build.VERSION.SDK_INT >= 26) { // Permission necessaire
if(checkSelfPermission("android.permission.ANSWER_PHONE_CALLS") != PackageManager.PERMISSION_GRANTED) {
String szPermissions[] = {"android.permission.ANSWER_PHONE_CALLS"};
requestPermissions(szPermissions, 0);
}
}
if(Build.VERSION.SDK_INT < 26 && Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1 )
{ // Permission pour Android 6.x et 7.x
ContentResolver contentResolver = getContentResolver();
String enabledNotificationListeners = Settings.Secure.getString(contentResolver, "enabled_notification_listeners");
String packageName = getPackageName();
if (enabledNotificationListeners == null || !enabledNotificationListeners.contains(packageName)) {
Intent intent2 = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
intent2 = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
}
startActivity(intent2);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100ms
Intent intent=new Intent(MainActivity.this, Main2Activity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}, 1000);
}
}
After a lot of research on forums, now I know that there is no way to find IMSI or SIM serial number for both the SIM cards in a dual SIM phone (except for contacting the manufacturer). Now my changed question is, can we at all detect that the phone has two SIMs? I believe it can be detected with some intelligence. Few ways I can think of are:
Dialing an USSD code and tracing the logs for IMEI number (I tried this with *139# in India. It worked.) This will give me IMEI number for the SIM from which I dialed the USSD code. (It is presumed that the phone follows android guidelines and has two IMEI numbers.)
Storing the SIM serial number and/or IMSI for the SIM. And after detection of any other IMSI/Serial number even if the phone was not rebooted (i.e. the SIM was switched) by tracing some logs or by some broadcast event handling.
By dialing *06# you will get to see both IMEI numbers. By some way, get those two numbers. (Something like screen capturing and image parsing for text.)
If anyone can think of some other ways, they are most welcome. I would really appreciate any kind of help regarding this. Also, if anyone has any information about any manufacturers APIs or links to contact them, please do share with the community people.
Update 23 March'15 :
Official multiple SIM API is available now from Android 5.1 onwards
Other possible option :
You can use Java reflection to get both IMEI numbers.
Using these IMEI numbers you can check whether the phone is a DUAL SIM or not.
Try following activity :
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TelephonyInfo telephonyInfo = TelephonyInfo.getInstance(this);
String imeiSIM1 = telephonyInfo.getImsiSIM1();
String imeiSIM2 = telephonyInfo.getImsiSIM2();
boolean isSIM1Ready = telephonyInfo.isSIM1Ready();
boolean isSIM2Ready = telephonyInfo.isSIM2Ready();
boolean isDualSIM = telephonyInfo.isDualSIM();
TextView tv = (TextView) findViewById(R.id.tv);
tv.setText(" IME1 : " + imeiSIM1 + "\n" +
" IME2 : " + imeiSIM2 + "\n" +
" IS DUAL SIM : " + isDualSIM + "\n" +
" IS SIM1 READY : " + isSIM1Ready + "\n" +
" IS SIM2 READY : " + isSIM2Ready + "\n");
}
}
And here is TelephonyInfo.java :
import java.lang.reflect.Method;
import android.content.Context;
import android.telephony.TelephonyManager;
public final class TelephonyInfo {
private static TelephonyInfo telephonyInfo;
private String imeiSIM1;
private String imeiSIM2;
private boolean isSIM1Ready;
private boolean isSIM2Ready;
public String getImsiSIM1() {
return imeiSIM1;
}
/*public static void setImsiSIM1(String imeiSIM1) {
TelephonyInfo.imeiSIM1 = imeiSIM1;
}*/
public String getImsiSIM2() {
return imeiSIM2;
}
/*public static void setImsiSIM2(String imeiSIM2) {
TelephonyInfo.imeiSIM2 = imeiSIM2;
}*/
public boolean isSIM1Ready() {
return isSIM1Ready;
}
/*public static void setSIM1Ready(boolean isSIM1Ready) {
TelephonyInfo.isSIM1Ready = isSIM1Ready;
}*/
public boolean isSIM2Ready() {
return isSIM2Ready;
}
/*public static void setSIM2Ready(boolean isSIM2Ready) {
TelephonyInfo.isSIM2Ready = isSIM2Ready;
}*/
public boolean isDualSIM() {
return imeiSIM2 != null;
}
private TelephonyInfo() {
}
public static TelephonyInfo getInstance(Context context){
if(telephonyInfo == null) {
telephonyInfo = new TelephonyInfo();
TelephonyManager telephonyManager = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE));
telephonyInfo.imeiSIM1 = telephonyManager.getDeviceId();;
telephonyInfo.imeiSIM2 = null;
try {
telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getDeviceIdGemini", 0);
telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getDeviceIdGemini", 1);
} catch (GeminiMethodNotFoundException e) {
e.printStackTrace();
try {
telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getDeviceId", 0);
telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getDeviceId", 1);
} catch (GeminiMethodNotFoundException e1) {
//Call here for next manufacturer's predicted method name if you wish
e1.printStackTrace();
}
}
telephonyInfo.isSIM1Ready = telephonyManager.getSimState() == TelephonyManager.SIM_STATE_READY;
telephonyInfo.isSIM2Ready = false;
try {
telephonyInfo.isSIM1Ready = getSIMStateBySlot(context, "getSimStateGemini", 0);
telephonyInfo.isSIM2Ready = getSIMStateBySlot(context, "getSimStateGemini", 1);
} catch (GeminiMethodNotFoundException e) {
e.printStackTrace();
try {
telephonyInfo.isSIM1Ready = getSIMStateBySlot(context, "getSimState", 0);
telephonyInfo.isSIM2Ready = getSIMStateBySlot(context, "getSimState", 1);
} catch (GeminiMethodNotFoundException e1) {
//Call here for next manufacturer's predicted method name if you wish
e1.printStackTrace();
}
}
}
return telephonyInfo;
}
private static String getDeviceIdBySlot(Context context, String predictedMethodName, int slotID) throws GeminiMethodNotFoundException {
String imei = null;
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try{
Class<?> telephonyClass = Class.forName(telephony.getClass().getName());
Class<?>[] parameter = new Class[1];
parameter[0] = int.class;
Method getSimID = telephonyClass.getMethod(predictedMethodName, parameter);
Object[] obParameter = new Object[1];
obParameter[0] = slotID;
Object ob_phone = getSimID.invoke(telephony, obParameter);
if(ob_phone != null){
imei = ob_phone.toString();
}
} catch (Exception e) {
e.printStackTrace();
throw new GeminiMethodNotFoundException(predictedMethodName);
}
return imei;
}
private static boolean getSIMStateBySlot(Context context, String predictedMethodName, int slotID) throws GeminiMethodNotFoundException {
boolean isReady = false;
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try{
Class<?> telephonyClass = Class.forName(telephony.getClass().getName());
Class<?>[] parameter = new Class[1];
parameter[0] = int.class;
Method getSimStateGemini = telephonyClass.getMethod(predictedMethodName, parameter);
Object[] obParameter = new Object[1];
obParameter[0] = slotID;
Object ob_phone = getSimStateGemini.invoke(telephony, obParameter);
if(ob_phone != null){
int simState = Integer.parseInt(ob_phone.toString());
if(simState == TelephonyManager.SIM_STATE_READY){
isReady = true;
}
}
} catch (Exception e) {
e.printStackTrace();
throw new GeminiMethodNotFoundException(predictedMethodName);
}
return isReady;
}
private static class GeminiMethodNotFoundException extends Exception {
private static final long serialVersionUID = -996812356902545308L;
public GeminiMethodNotFoundException(String info) {
super(info);
}
}
}
Edit :
Getting access of methods like "getDeviceIdGemini" for other SIM slot's detail has prediction that method exist.
If that method's name doesn't match with one given by device manufacturer than it will not work. You have to find corresponding method name for those devices.
Finding method names for other manufacturers can be done using Java reflection as follows :
public static void printTelephonyManagerMethodNamesForThisDevice(Context context) {
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
Class<?> telephonyClass;
try {
telephonyClass = Class.forName(telephony.getClass().getName());
Method[] methods = telephonyClass.getMethods();
for (int idx = 0; idx < methods.length; idx++) {
System.out.println("\n" + methods[idx] + " declared by " + methods[idx].getDeclaringClass());
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
EDIT :
As Seetha pointed out in her comment :
telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getDeviceIdDs", 0);
telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getDeviceIdDs", 1);
It is working for her. She was successful in getting two IMEI numbers for both the SIM in Samsung Duos device.
Add <uses-permission android:name="android.permission.READ_PHONE_STATE" />
EDIT 2 :
The method used for retrieving data is for Lenovo A319 and other phones by that manufacture (Credit Maher Abuthraa):
telephonyInfo.imeiSIM1 = getDeviceIdBySlot(context, "getSimSerialNumberGemini", 0);
telephonyInfo.imeiSIM2 = getDeviceIdBySlot(context, "getSimSerialNumberGemini", 1);
I have a Samsung Duos device with Android 4.4.4 and the method suggested by Seetha in the accepted answer (i.e. call getDeviceIdDs) does not work for me, as the method does not exist. I was able to recover all the information I needed by calling method "getDefault(int slotID)", as shown below:
public static void samsungTwoSims(Context context) {
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try{
Class<?> telephonyClass = Class.forName(telephony.getClass().getName());
Class<?>[] parameter = new Class[1];
parameter[0] = int.class;
Method getFirstMethod = telephonyClass.getMethod("getDefault", parameter);
Log.d(TAG, getFirstMethod.toString());
Object[] obParameter = new Object[1];
obParameter[0] = 0;
TelephonyManager first = (TelephonyManager) getFirstMethod.invoke(null, obParameter);
Log.d(TAG, "Device Id: " + first.getDeviceId() + ", device status: " + first.getSimState() + ", operator: " + first.getNetworkOperator() + "/" + first.getNetworkOperatorName());
obParameter[0] = 1;
TelephonyManager second = (TelephonyManager) getFirstMethod.invoke(null, obParameter);
Log.d(TAG, "Device Id: " + second.getDeviceId() + ", device status: " + second.getSimState()+ ", operator: " + second.getNetworkOperator() + "/" + second.getNetworkOperatorName());
} catch (Exception e) {
e.printStackTrace();
}
}
Also, I rewrote the code that iteratively tests for methods to recover this information so that it uses an array of method names instead of a sequence of try/catch. For instance, to determine if we have two active SIMs we could do:
private static String[] simStatusMethodNames = {"getSimStateGemini", "getSimState"};
public static boolean hasTwoActiveSims(Context context) {
boolean first = false, second = false;
for (String methodName: simStatusMethodNames) {
// try with sim 0 first
try {
first = getSIMStateBySlot(context, methodName, 0);
// no exception thrown, means method exists
second = getSIMStateBySlot(context, methodName, 1);
return first && second;
} catch (GeminiMethodNotFoundException e) {
// method does not exist, nothing to do but test the next
}
}
return false;
}
This way, if a new method name is suggested for some device, you can simply add it to the array and it should work.
There are several native solutions I've found while searching the way to check network operator.
For API >=17:
TelephonyManager manager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
// Get information about all radio modules on device board
// and check what you need by calling #getCellIdentity.
final List<CellInfo> allCellInfo = manager.getAllCellInfo();
for (CellInfo cellInfo : allCellInfo) {
if (cellInfo instanceof CellInfoGsm) {
CellIdentityGsm cellIdentity = ((CellInfoGsm) cellInfo).getCellIdentity();
//TODO Use cellIdentity to check MCC/MNC code, for instance.
} else if (cellInfo instanceof CellInfoWcdma) {
CellIdentityWcdma cellIdentity = ((CellInfoWcdma) cellInfo).getCellIdentity();
} else if (cellInfo instanceof CellInfoLte) {
CellIdentityLte cellIdentity = ((CellInfoLte) cellInfo).getCellIdentity();
} else if (cellInfo instanceof CellInfoCdma) {
CellIdentityCdma cellIdentity = ((CellInfoCdma) cellInfo).getCellIdentity();
}
}
In AndroidManifest add permission:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
</manifest>
To get network operator you can check mcc and mnc codes:
https://en.wikipedia.org/wiki/Mobile_country_code (general information).
https://clients.txtnation.com/hc/en-us/articles/218719768-MCCMNC-mobile-country-code-and-mobile-network-code-list- (quite full and quite latest list of operators).
For API >=22:
final SubscriptionManager subscriptionManager = SubscriptionManager.from(context);
final List<SubscriptionInfo> activeSubscriptionInfoList = subscriptionManager.getActiveSubscriptionInfoList();
for (SubscriptionInfo subscriptionInfo : activeSubscriptionInfoList) {
final CharSequence carrierName = subscriptionInfo.getCarrierName();
final CharSequence displayName = subscriptionInfo.getDisplayName();
final int mcc = subscriptionInfo.getMcc();
final int mnc = subscriptionInfo.getMnc();
final String subscriptionInfoNumber = subscriptionInfo.getNumber();
}
For API >=23. To just check if phone is dual/triple/many sim:
TelephonyManager manager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
if (manager.getPhoneCount() == 2) {
// Dual sim
}
I am able to read both the IMEI's from OnePlus 2 Phone
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
TelephonyManager manager = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
Log.i(TAG, "Single or Dual Sim " + manager.getPhoneCount());
Log.i(TAG, "Default device ID " + manager.getDeviceId());
Log.i(TAG, "Single 1 " + manager.getDeviceId(0));
Log.i(TAG, "Single 2 " + manager.getDeviceId(1));
}
I was taking a look at the call logs and I noticed that apart from the usual fields in the contents of managedCursor, we have a column "simid" in Dual SIM phones (I checked on Xolo A500s Lite), so as to tag each call in the call log with a SIM. This value is either 1 or 2, most probably denoting SIM1/SIM2.
managedCursor = context.getContentResolver().query(contacts, null, null, null, null);
managedCursor.moveToNext();
for(int i=0;i<managedCursor.getColumnCount();i++)
{//for dual sim phones
if(managedCursor.getColumnName(i).toLowerCase().equals("simid"))
indexSIMID=i;
}
I did not find this column in a single SIM phone (I checked on Xperia L).
So although I don't think this is a foolproof way to check for dual SIM nature, I am posting it here because it could be useful to someone.
Tips:
You can try to use
ctx.getSystemService("phone_msim")
instead of
ctx.getSystemService(Context.TELEPHONY_SERVICE)
If you have already tried Vaibhav's answer and telephony.getClass().getMethod() fails, above is what works for my Qualcomm mobile.
I have found these system properties on Samsung S8
SystemProperties.getInt("ro.multisim.simslotcount", 1) > 1
Also, according to the source: https://android.googlesource.com/platform/frameworks/base/+/master/telephony/java/com/android/internal/telephony/TelephonyProperties.java
getprop persist.radio.multisim.config returns "dsds" or "dsda" on multi sim.
I have tested this on Samsung S8 and it works
for sdk api 26+ (Build.VERSION_CODES.O):
val telephony = context.getSystemService(Service.TELEPHONY_SERVICE) as? TelephonyManager
// check telephony on null
val simCount = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
telephony.activeModemCount
} else {
telephony.phoneCount
}
Commonsware says this is not possible. Please see the following:
Detecting Dual SIM using Android SDK is not possible.
Here is further dialog on the subject:
Google dev team guy says detecting Dual SIM using Android SDK is not possible.
I would like to implement an application for block a mobile number for receiving or sending calls and messages. In my application I am entering mobile number at EditText box then I am clicking a button for block the mobile number which has entered by the user.
I have implemented an activity class as follows:
public class BlockNumberActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button)findViewById(R.id.block)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String mobileNumer = ((EditText)findViewById(R.id.mobileNum)).getText().toString();
//How to block entered mobileNumber
}
});
((Button)findViewById(R.id.unblock)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String mobileNumer = ((EditText)findViewById(R.id.mobileNum)).getText().toString();
//How to unblock entered mobileNumber
}
});
}
}
I think we may use BroadcastReceiver. But I don't have more knowledge on it. Please give me an idea how to implement blocking or unblocking mobile number.
Please any body help me.....
create PhoneCallReceiver .java
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 PhoneCallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
PhoneCallStateListener customPhoneListener = new PhoneCallStateListener(context);
telephony.listen(customPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}}
now create PhoneCallStateListener .java
import java.lang.reflect.Method;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;
import com.android.internal.telephony.ITelephony;
public class PhoneCallStateListener extends PhoneStateListener {
private Context context;
public PhoneCallStateListener(Context context){
this.context = context;
}
#Override
public void onCallStateChanged(int state, String incomingNumber) {
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(context);
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
String block_number = prefs.getString("block_number", null);
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
//Turn ON the mute
audioManager.setStreamMute(AudioManager.STREAM_RING, true);
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try {
Toast.makeText(context, "in"+block_number, Toast.LENGTH_LONG).show();
Class clazz = Class.forName(telephonyManager.getClass().getName());
Method method = clazz.getDeclaredMethod("getITelephony");
method.setAccessible(true);
ITelephony telephonyService = (ITelephony) method.invoke(telephonyManager);
//Checking incoming call number
System.out.println("Call "+block_number);
if (incomingNumber.equalsIgnoreCase("+91"+block_number)) {
//telephonyService.silenceRinger();//Security exception problem
telephonyService = (ITelephony) method.invoke(telephonyManager);
telephonyService.silenceRinger();
System.out.println(" in "+block_number);
telephonyService.endCall();
}
} catch (Exception e) {
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
}
//Turn OFF the mute
audioManager.setStreamMute(AudioManager.STREAM_RING, false);
break;
case PhoneStateListener.LISTEN_CALL_STATE:
}
super.onCallStateChanged(state, incomingNumber);
}}
Now in src create this package com.android.internal.telephony now in this package Right Click -> New -> File now give name ITelephony.aidl and paste this code
package com.android.internal.telephony;
interface ITelephony {
boolean endCall();
void answerRingingCall();
void silenceRinger();
}
NOTE: Code is tested in Android 2.2 (Froyo),2.3 (GingerBread)
to block incoming call use this http://androidsourcecode.blogspot.in/2010/10/blocking-incoming-call-android.html and also this http://www.codeproject.com/Questions/333253/Block-Incoming-calls-in-android-without-single-rin ,http://www.anddev.org/post52643.html?hilit=incoming%20call#p52643 or to block outgoing see How to Block outgoing calls and Text SMS and Blocking outgoing calls and texts (BroadcastReceiver or Service?) , Android: Taking complete control of phone(kiosk mode), is it possible? How?
This Code works for me
try {
String serviceManagerName = "android.os.ServiceManager";
String serviceManagerNativeName = "android.os.ServiceManagerNative";
String telephonyName = "com.android.internal.telephony.ITelephony";
Class<?> telephonyClass;
Class<?> telephonyStubClass;
Class<?> serviceManagerClass;
Class<?> serviceManagerNativeClass;
Method telephonyEndCall;
Object telephonyObject;
Object serviceManagerObject;
telephonyClass = Class.forName(telephonyName);
telephonyStubClass = telephonyClass.getClasses()[0];
serviceManagerClass = Class.forName(serviceManagerName);
serviceManagerNativeClass = Class.forName(serviceManagerNativeName);
Method getService =
serviceManagerClass.getMethod("getService", String.class);
Method tempInterfaceMethod = serviceManagerNativeClass.getMethod(
"asInterface", IBinder.class);
Binder tmpBinder = new Binder();
tmpBinder.attachInterface(null, "fake");
serviceManagerObject = tempInterfaceMethod.invoke(null, tmpBinder);
IBinder retbinder = (IBinder) getService.invoke(
serviceManagerObject, "phone");
Method serviceMethod = telephonyStubClass.getMethod("asInterface",
IBinder.class);
telephonyObject = serviceMethod.invoke(null, retbinder);
telephonyEndCall = telephonyClass.getMethod("endCall");
telephonyEndCall.invoke(telephonyObject);
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Unable to Block Call", Toast.LENGTH_SHORT).show();
}
To block a call of any specific contact number, then this tutorial will help you in solving your problem.
http://androiddesk.wordpress.com/2012/08/02/blocking-a-call-without-user-intervention-in-android/
this code is working...
first download this class ITelephony
if ((state != null)
&& (state.equals(TelephonyManager.EXTRA_STATE_RINGING))) {
CallLogReceiver.phoneNo = intent.getExtras().getString(
"incoming_number");
if (CallLogReceiver.blockNo.equals(CallLogReceiver.phoneNo)) {
Intent blockCallIntent = new Intent();
blockCallIntent.setClassName("com.example.calllogdemo",
"com.example.calllogdemo.BlockCallActivity");
blockCallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
blockCallIntent
.putExtra("blockNo", CallLogReceiver.phoneNo);
context.startActivity(blockCallIntent);
try {
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
Class<?> classTelephony = Class
.forName(telephonyManager.getClass().getName());
Method methodGetITelephony = classTelephony
.getDeclaredMethod("getITelephony");
methodGetITelephony.setAccessible(true);
ITelephony telephonyService = (ITelephony) methodGetITelephony
.invoke(telephonyManager);
telephonyService.endCall();
} catch (Exception e) {
e.printStackTrace();
}
}
}
and use this permission in manifest file
<uses-permission android:name="android.permission.CALL_PHONE" />