Android Studio: Dial Ussd Code and Get Response inside App

0
117

If you are looking for how to dial ussd code in your android studio app and then get the dialog response message in your app, then you are at the right place.
The way it works is that in your app, you can click on a button which would dial the ussd code in background and give you the response in a callback. everything happens on the app. You no longer need to depend on your phone dialer or phone call app.

NB: This works only on android version 8 (Oreo) and above.

public void dialUssdToGetPhoneNumber(String ussdCode, int sim) {

    if (ussdCode.equalsIgnoreCase("")) return;



    if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, 234);
        return;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {


        TelephonyManager manager = (TelephonyManager) getActivity().getSystemService(TELEPHONY_SERVICE);
        TelephonyManager manager2 = manager.createForSubscriptionId(2);

        TelephonyManager managerMain = (sim == 0) ? manager : manager2;

        managerMain.sendUssdRequest(ussdCode, new TelephonyManager.UssdResponseCallback() {
            @Override
            public void onReceiveUssdResponse(TelephonyManager telephonyManager, String request, CharSequence response) {
                super.onReceiveUssdResponse(telephonyManager, request, response);

                Log.e("TAG", "onReceiveUssdResponse:  Ussd Response = " + response.toString().trim() );
        
               

            }

            @Override
            public void onReceiveUssdResponseFailed(TelephonyManager telephonyManager, String request, int failureCode) {
                super.onReceiveUssdResponseFailed(telephonyManager, request, failureCode);

                Log.e("TAG", "onReceiveUssdResponseFailed: " + "" + failureCode + request);
            }
        }, new Handler());
    }

}

LEAVE A REPLY

Please enter your comment!
Please enter your name here