Run USSD Code in Android and Keep the App in the firstground

Sahlo picture Sahlo · Aug 3, 2015 · Viewed 8.8k times · Source

I am creating a App in Android, which required run USSD Code in background. without send my application in background,

Whenever I am using Intent.ACTION_CALL to run USSD

String ussdCode = "*" + "123" + Uri.encode("#");
startActivity(new Intent("android.intent.action.CALL", Uri.parse("tel:" + ussdCode)));

it send my application in background, and open dialer Interface on my application.

So it is possible to run USSD code without open Dialer Interface in front.

Thanks.

Answer

zeeali picture zeeali · Feb 22, 2016

Use following code:

String ussdCode = "*123#";
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(ussdToCallableUri(ussdCode));
try{
    startActivity(intent);
} catch (SecurityException e){
    e.printStackTrace();
}

Here is the method to convert your ussd code to callable ussd:

private Uri ussdToCallableUri(String ussd) {

    String uriString = "";

    if(!ussd.startsWith("tel:"))
        uriString += "tel:";

    for(char c : ussd.toCharArray()) {

        if(c == '#')
            uriString += Uri.encode("#");
        else
            uriString += c;
    }

    return Uri.parse(uriString);
}