8

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.

Sahlo
  • 83
  • 1
  • 2
  • 5
  • The same question with: http://stackoverflow.com/questions/5449464/calling-a-ussd-number-without-opening-the-phone-app-in-android – Plugie Aug 18 '15 at 09:54

1 Answers1

3

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);
}
zeeali
  • 1,524
  • 20
  • 31
  • 13
    I don't understand why this answer is accepted. Your code is the same as the OP has written in question. Your code just has more lines. – Mr.D Aug 08 '17 at 09:34
  • And you could've just used a string builder or even done `String.replace("#", Uri.encore("#"))` instead.. – Lorenzo Nov 14 '21 at 11:09