Skip to content

Instantly share code, notes, and snippets.

@mtvbrianking
Forked from ibstelix/MainActivity.java
Created March 27, 2023 09:57
Show Gist options
  • Save mtvbrianking/41e2d1377f78b2076b8701041ea101a1 to your computer and use it in GitHub Desktop.
Save mtvbrianking/41e2d1377f78b2076b8701041ea101a1 to your computer and use it in GitHub Desktop.
Android: How to collect the response of a USSD request (Including multi-session requests)
//Get the instance of TelephonyManager
final TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
try {
if (tm != null) {
Class telephonyManagerClass = Class.forName(tm.getClass().getName());
if (telephonyManagerClass != null) {
Method getITelephony = telephonyManagerClass.getDeclaredMethod("getITelephony");
getITelephony.setAccessible(true);
Object iTelephony = getITelephony.invoke(tm); // Get the internal ITelephony object
Method[] methodList = iTelephony.getClass().getMethods();
Method handleUssdRequest = null;
/*
* Somehow, the method wouldn't come up if I simply used:
* iTelephony.getClass().getMethod('handleUssdRequest')
*/
for (Method _m : methodList)
if (_m.getName().equals("handleUssdRequest")) {
handleUssdRequest = _m;
break;
}
/*
* Now the real reflection magic happens
*/
if (handleUssdRequest != null) {
handleUssdRequest.setAccessible(true);
handleUssdRequest.invoke(iTelephony, SubscriptionManager.getDefaultSubscriptionId(), ussdRequest, new ResultReceiver(l) {
@Override
protected void onReceiveResult(int resultCode, Bundle ussdResponse) {
/*
* Usually you should the getParcelable() response to some Parcel
* child class but that's not possible here, since the "UssdResponse"
* class isn't in the SDK so we need to
* reflect again to get the result of getReturnMessage() and
* finally return that!
*/
Object p = ussdResponse.getParcelable("USSD_RESPONSE");
CharSequence message = "";
String request = "";
if (p != null) {
Method getReturnMessage, getUssdRequest;
try {
getReturnMessage = p.getClass().getMethod("getReturnMessage");
if (getReturnMessage != null) {
message = (CharSequence) getReturnMessage.invoke(p);
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
t.setText(message);
}
}
});
}
}
}
} catch (ClassNotFoundException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) {
e1.printStackTrace();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment