Friday, 27 November 2015

How to read/parse USSD messages in Android .?



What is USSD.?

USSD is a communication technology that is used to send text between a mobile phone and an application program(network operator) in the network.


What are USSD codes.?

USSD codes are used by network users to get usage infromation from the current operator. USSD codes start with *, preceeding with numbers and end up with #. Ex : *123#
Different network operators have different USSD codes. Ex :
*123# is used to get usage information for Airtel
*111# is used to get usage information for Vadafone


How do we get this USSD information in android application.?

The below code will display a USSD popup, showing the balance information for the current sim

// Get vadafone balance(*111*2for vadafone)

private void dailNumber(String code) {
    String ussdCode = "*" + code + Uri.encode("#");
    startActivity(new Intent("android.intent.action.CALL", Uri.parse("tel:" + ussdCode)));
}

Add the following permission (to make a call) in the manifest

<uses-permission android:name="android.permission.CALL_PHONE" />


How to handle/read/parse USSD messages from popup.?

An accessibility service runs in the background and receives callbacks by the system when AccessibilityEvents are fired. Such events denote some state transition in the user interface, for example, the focus has changed, a button has been clicked, a popup dialog etc.

So the trick is, this service will deliver us an event, from which we can get the USSD message.


Steps to implement


1. Write a class named "XXXX"


public class XXXX extends AccessibilityService {


    public static String TAG = "XXXX";


    @Override

    public void onAccessibilityEvent(AccessibilityEvent event) {
        Log.d(TAG, "onAccessibilityEvent");
        String text = event.getText().toString();

        if (event.getClassName().equals("android.app.AlertDialog")) {

            performGlobalAction(GLOBAL_ACTION_BACK);
            Log.d(TAG, text);
            Intent intent = new Intent("com.times.ussd.action.REFRESH");
            intent.putExtra("message", text);
       // write a broad cast receiver and call sendbroadcast() from here, if you want to parse the message for balance, date
        }

    }


    @Override

    public void onInterrupt() {
    }

    @Override

    protected void onServiceConnected() {
        super.onServiceConnected();
        Log.d(TAG, "onServiceConnected");
        AccessibilityServiceInfo info = new AccessibilityServiceInfo();
        info.flags = AccessibilityServiceInfo.DEFAULT;
        info.packageNames = new String[]{"com.android.phone"};
        info.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
        info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
        setServiceInfo(info);
    }

}



2. Add an entry for the above service in the manifest


<service android:name=".XXXX"

    android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
    <intent-filter>
        <action android:name="android.accessibilityservice.AccessibilityService" />
    </intent-filter>
    <meta-data android:name="android.accessibilityservice"
        android:resource="@xml/config_service" /> // created below
</service>


3. Create a folder 'xml' under res, and then create file named "config_service.xml" in xml folder.


<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"

    android:accessibilityEventTypes="typeAllMask"
    android:accessibilityFeedbackType="feedbackSpoken"
    android:accessibilityFlags="flagDefault"
    android:canRetrieveWindowContent="true"
    android:description="This service records pop ups sent by your mobile operator, and saves them in XXXX App. It is absolutely safe to use." //declare this in string.xml
    android:notificationTimeout="100"
    android:packageNames="com.times.ussd"
    android:settingsActivity="com.example.android.accessibility.ServiceSettingsActivity" />

To run a accessibility service, user permissions are needed. The above xml is used to provide the necessary description to the user .



4. Now in your activity, invoke this


    startService(new Intent(this, XXXX.class));
    dailNumber("*111*2");


5. Launch your application.


6. After the launch, change the settings manually


Setting->Accessibility Setting -> You can see a option 'your app name'. Turn it on. (This has to be done from as a part of application flow(not manual))


7. Restart your application, and check the logs, that I wrote in Service class



Happy to see the USSD logs.. CHEERS :)


Feel free to ask if you face any difficulties with the above explanation..


Please give your feedback on this post as a like, comment, share..



159 comments:

  1. Replies
    1. hi ji .. you have full code .. how to display ussd messsage in textview .. share my mail id tamiladz@gmail.com

      Delete
    2. if you get full code of same senario please share me on dayib12@gmail.com

      Delete
    3. please share sitaram.gupta99@gmail.com

      Delete
    4. please share naphtalint@yahoo.fr

      Delete
    5. please share basepa_tonny@yahoo.fr

      Delete
    6. Please mail me the complete code at prkharsingh.2918@gmail.com

      Delete
    7. Hi I need the complete codes, email me, pogimista@gmail.com, thanks very much

      Delete
    8. hi very nice work .thanks .. you have full code .. how to display ussd messsage in textview .. share my mail id gideonkeremeh47@yahoo.com

      Delete
  2. It is not showing USSD response in the app :(

    ReplyDelete
    Replies
    1. It works.. Plz check if u followed all the above steps and let me know if you are getting the following logs on app execution..
      Log.d(TAG, "onServiceConnected");
      Log.d(TAG, "onAccessibilityEvent");

      Delete
    2. No I am not getting these logs on app execution. What should I do?

      Delete
    3. me too.. im not getting any logs

      Delete
    4. I can't run the codes, the error said Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:xxxxx cmp=com.android.server.telecom/.components.UserCallActivity } from ProcessRecord{66bd9c0 31432/u0a138} (pid=31432, uid=10138) with revoked permission android.permission.CALL_PHONE help me please

      Delete
  3. Awesome! But is it possible to avoid the service from closing ussd dialogs when using the phone's dialer app?

    ReplyDelete
    Replies
    1. Thank you Robert! To find a solution for your problem, I would like to know how are you closing the USSD dialogs. You can write me at umesh.isran405@gmail.com

      Delete
    2. hi robert and umesh, i want to know how to close ussd dialogs directly from the apps?

      Delete
    3. I followed what's written in this blog and success capturing the ussd message inside the log, but the problem is the ussd dialog doesnt automatically close ,

      Delete
    4. Hello umesh and robery, i also want to know how to close ussd dialog programmatically please let me know.

      Delete
    5. dear Robert and Umesh how to show the ussd dialogs plz send me sitaram.gupta99@gmail.com its urgent please help me

      Delete
    6. dear Robert and Umes. could u send me the code, I have some error I need the source code, would u send me the source code hildapamungkas71@gmail.com

      Delete
  4. Umesh, great post!
    We were having trouble handling USSD response. We are trying to write an android wrapper over an USSD application which collects multiple level of response from user. Can we have a brief discussion around that please?

    ReplyDelete
    Replies
    1. Sure Pankaj, First let me understand, what do you mean by 'multiple level of response from user'. Write me your trouble clearly and mail me at umesh.isran405@gmail.com

      Delete
    2. can you add me in same loop?

      Delete
    3. Please add me in this loop Umesh

      Delete
    4. hello Umesh, please let me see the complete code which dissmiss the ussd dialog automatically,
      my email: wanedenis3@gmail.com

      Delete
    5. Please add me in this loop Umesh

      Delete
  5. Hi,
    On some devices the class is USSDAlertActivtiy (https://github.com/anomalchik/alps_packages_services_Telephony/blob/master/src/com/mediatek/phone/UssdAlertActivity.java) instead of AlertDialog. And in such cases gettext() returns only activity title no ussd response.
    Link for reference. Can you please give me some suggestion on this?
    Thanks,
    Ishaan

    ReplyDelete
    Replies
    1. Hey Ishaan, Even I have come across this issue. Will get back on this..

      Delete
    2. Okay that makes two of us, thanks. By the way why is the permission read logs required?

      Delete
    3. Good point. Its not necessary. Plz check the updated blog.

      Delete
    4. (https://github.com/anomalchik/alps_packages_services_Telephony/blob/master/src/com/mediatek/phone/UssdAlertActivity.java

      Plz can you help me with how to use this in my project

      Delete
  6. Hi sir,
    i tried on 4.4.2 but not working, i don't even see log at onServiceConnected.
    Do you have full code?
    Thanks

    ReplyDelete
    Replies
    1. The above code does not work on all the devices. Test it on some other device and let me know..

      Delete
    2. Hey Umesh ... Nice finding ... Its possible to change the accssebility programatically? Urgent !!

      Delete
  7. Hi sir,
    Can i set my service ON when installing my application, not manually !? and thank you.

    ReplyDelete
  8. Hey Umesh, thanks for the great example.
    My main problem now is that, since this code does not work on every device, is there a particular aspect of it that makes it not to work on the other devices. In this way one can decide to use nested try catch blocks to be able to test various possibilities for the problem, so as to ensure that at least one possiblity will work for the various devices.

    ReplyDelete
  9. I can't even see my app on accessibility, I'm not sure what is wrong. Any help?

    ReplyDelete
    Replies
    1. I´ve got the same problem in Nexus4 android 5.1.1, please help?

      Delete
    2. Any luck with this? Even I am not able to see my app on accessiblity.

      Delete
  10. This comment has been removed by the author.

    ReplyDelete
  11. Lovely demo. You are awesome man

    ReplyDelete
  12. How to dismiss the ussd dialog after reading the response. performglobalaction() is not working in android L. Please help.

    ReplyDelete
    Replies
    1. can you solved your problem? then kindly send me the link

      Delete
  13. how to get USSD response in a string that not issue but the my problem is how to get updated response of ussd from log...my aim can i clear the log file after getting ussd response to get next time fresh data.

    ReplyDelete
  14. I have problem geting text of ussd alertdialog .. i am getting 'PHONE' using event.getText();

    ReplyDelete
    Replies
    1. So plz help me how to get ussd alertdialog text in my own app.

      Delete
  15. Hi Umesh,

    I need a help regarding sending back a response to the ussd result.

    Like when i get menu as a response for Ussd *111#

    1. xxx
    2. xxxx
    3. xxxxx

    Need to send 2 programmatically in the same session.

    Thanks In Advance

    ReplyDelete
    Replies
    1. Try *111*2 in function dialNumber() for sending 2 programmatically.

      Delete
  16. hi, how i can parse ussd message, wants to extract balance and validity from ussd text string.

    ReplyDelete
    Replies
    1. hi , in case of dual sim phone, how i can detect that the response id for which sim? in reverse can i get the outgoing ussd code calling sim? (sim1 or sim 2)?

      Delete
  17. Hello, do you have a full complete source code? I'm following your guidance but I still raise a dialog box. I'm using android api version 16. Any other info would be great. Thank you.

    ReplyDelete
  18. Dear Sir,
    I need a help regarding sending back a response to the ussd result.I am dineshvasan Ussd response value showing null value. please kindly send me sample project to my mail id dineshvasanmca@gmail.com

    ReplyDelete
  19. Hello,
    I'm using an AT&T devoce (SM-P907A) and i tried your code but i\m getting an error (no empty constructor
    at android.app.ActivityThread.handleCreateService(ActivityThread.java:2709) )

    My device doesn't like making phone calls or SMS normally but i obtained an example from the "Expert Android" book and managed to send text messages. Will test receiving messages later...

    ReplyDelete
  20. Hi Umesh - can this be used to completely alter the default UI for ALL USSD messages on a particular device ? Also, can it work on latest Andorid Editions ?

    ReplyDelete
  21. Hey can you please tell me how to parse the data and save it into a string. This tutorial worked fine for me.

    ReplyDelete
  22. Please need full USSD project to get a menu and respond accordingly after get the final reply. Like: *123# after we get choice 1, 2 3 ... we chose 1 and we can parse the final answer from USSD message . Thanks a lot. My email is l.ouadjaout@gmail.com . Thanks in advance

    ReplyDelete
  23. Hi Sir...I want to show USSD popup in textView.How it is Possible?
    Thanks in Advance.

    ReplyDelete
  24. where should i write the dailNumber method in the same class XXXX??. Please respond urgent

    ReplyDelete
  25. can you provide download link for project , thanks for sharing great work

    ReplyDelete
  26. Hi Umesh,how to display USSD messsage in textview

    ReplyDelete
  27. "Setting->Accessibility Setting -> You can see a option 'your app name'. Turn it on. (This has to be done from as a part of application flow(not manual))"

    I don't my app name in there.

    ReplyDelete
  28. This comment has been removed by the author.

    ReplyDelete
  29. how to close ussd result dialog?

    ReplyDelete
  30. Hi Umesh
    how to display USSD messsage in textview??
    Can you provide the link for the project ?
    Thanks in advance

    ReplyDelete
  31. Could you please put here some link to this project? I have an error message with revoked permission android.permission.CALL_PHONE" and trying to solve it. Or could you please send this project on my email(pezelazo@gmail.com)?

    ReplyDelete
  32. what about getting the response when using GSM Modem? please help

    ReplyDelete
  33. please share : abdo.allah.webdevlpr@gmail.com

    ReplyDelete
  34. Thanks a lot! You made a new blog entry to answer my question; I really appreciate your time and effort.Android Training in velachery | Android Training in chennai | Android Training in chennai with placement

    ReplyDelete
  35. please share : djidiop89@gmail.com

    ReplyDelete
  36. Hello Umesh , please share (evaristusmaduhu@gmail.com). How did you guys hide the dialog ??? Thanks

    ReplyDelete
  37. Hi, thanks for the flow. Can I get the full code to this mail id. swethamr@junotele.com

    ReplyDelete
  38. Please mail me the complete code at beconfidentghaek@gmail.com

    ReplyDelete
  39. Hello everybody, is it possible to get ussd response in textview?
    If it's possible, please mail me the code or issues at rapide755@gmail.com

    ReplyDelete
  40. i have tested this code and working like a charm. thanks for this. Can i send ussd option like 1 or 2 through code and capture dialog of ussd.

    ReplyDelete
  41. This service records pop ups sent by your mobile operator, and saves them in XXXX App. It is absolutely safe to use. where in String.xml?
    how I can do it

    ReplyDelete
  42. android:description="This service records pop ups sent by your mobile operator, and saves them in XXXX App. It is absolutely safe to use." //declare this in string.xml
    not done

    ReplyDelete
    Replies
    1. Replace this words 'This service records pop ups sent by your mobile operator, and saves them in XXXX App. It is absolutely safe to use.' with @string/description
      Now, in your strings.xml under values folder(under res folder) add this line:
      This service records pop ups sent by your mobile operator, and saves them in XXXX App. It is absolutely safe to use.
      Done!!!

      Delete
    2. not done
      please help me

      Delete
    3. Error:(8, 26) No resource found that matches the given name (at 'description' with value '@String/description').

      Delete
    4. This comment has been removed by the author.

      Delete
    5. In app > res > xml > config_service.xml add line android:description="@string/desc"

      In app > res > values > stings.xml add line < string name="desc" > This service records pop ups sent by your mobile operator, and saves them in XXXX App. It is absolutely safe to use. < /string >

      Unistall application, install again, run once, close, go to Setting > (Advanced Setting) > Accessibility Setting > Your Application

      Delete
  43. I can read the data but the can not block the ussd dialog. The dialog appears on the screen. I want to block/dismiss the dialog but i can not. I used ACTION_CLOSE_SYSTEM_DIALOG. But it is not working. Any suggestions??
    Thanks in advance

    ReplyDelete
    Replies
    1. si pudiste resolverte te animas a compartirlo?

      Delete
  44. I can't see the name of My App in Accessibility, Pls Help

    ReplyDelete
  45. Is there a Way to Respond to USSD that returns Menus?

    ReplyDelete
  46. hi thanks a lot.. you have full code .. how to display ussd messsage in textview .. share my mail id gideonkyeremeh47@yahoo.com

    ReplyDelete
  47. pls send me the working code on (damana.dasta@gmail.com)
    with regards

    ReplyDelete
  48. Hello, please send me the source code ( nfaical3@gmail.com )

    ReplyDelete
  49. Can anyone pls tell me how to hide the alert dialog when getting the response

    if its pls send me the source code to vnktmech792@gmail.com

    Thanks in advance pls do the needfulll

    ReplyDelete
  50. Hello, please send me the source code ( caibinglong1987@gmail.com )

    ReplyDelete
  51. This post is absolutely fantastic. Thanks for sharing a lots of great information and inspiration, both of which we all need. Thank you so much!!
    android app development perth | wordpress development sydney

    ReplyDelete
  52. Thanks to share the classic blog to understand the parse application Development quality. Thanks for sharing the this blog. it is help full for us.

    ReplyDelete
  53. hi!
    Thanks for your tuto!
    So how can disable my service onDestroy()? Because, if my service turn on, i cann't ussd by native phone dial

    ReplyDelete
  54. Is there a Way to Respond to USSD that returns Menus?

    ReplyDelete
  55. Intent intent = new Intent("com.times.ussd.action.REFRESH");
    please I have a problem with this line of code. where is this com.times.ussd.action.REFRESH commig from or going to
    As far as I know, we are not using this action in our manifest to perform anything.
    I will like for you to explain that part very well, thanks

    ReplyDelete
  56. would u please send me the source code through my email:somiman73@gmail.com

    ReplyDelete
  57. would u please send me the source code through my email:ssapptech90@gmail.com

    ReplyDelete
  58. Can you please send me source code on labovic.nikola@gmail.com
    Thanksss

    ReplyDelete
  59. Dear Sir,

    Can i get project source code : naylin.sc@gmail.com

    ReplyDelete
  60. A copy of source would be awesome!!
    Please send: ephraimm@gmail.com

    ReplyDelete
  61. I want the whole source code natnael.awel@gmail.com. please

    ReplyDelete
  62. Please share the project in my mail jkaguo@gmail.com

    ReplyDelete
  63. An ingenious code. Thanks for sharing. Works with USSD Menu, no need to restart the phone.
    Greetings from Poland.

    ReplyDelete
    Replies
    1. is not working for me please help me share the source code thank you bro
      mchamoudaDev@gmail.com

      Delete
  64. a copy of source code to qteckk@gmail.com would be awesome

    ReplyDelete
  65. Please send me a copy of source code to ramymokako@live.com

    ReplyDelete
  66. The Best Mobile Game Developers in India is Colour Moon Technologies, it has the Experience in developing various types of Apps like Pubg Tournaments, Rummy Games etc.

    Colour Moon Technologies offers you with high value of App Development services at competent range. We will develop Platform for conducting pubg game tournaments Mobile apps & website as well. We all know how PUBG is in spotlight these days. It captivated many players within very less period of time. And now, you can incarnate with this PUBG Tournament App to sub- limely generate good income from this most trending game in this Hi-tech era.

    https://bit.ly/2EMJ0sQ

    ReplyDelete
  67. Thanks for sharing such informative and useful tutorial guidelines regarding parse Android app development.

    ReplyDelete
  68. can you please share this code on qamarkhan2166@gmail.com
    thank you so much in advance .
    i want to display ussd respone in textview .

    ReplyDelete
  69. Show a snip of your Service.java file and also your main activity calling the dialNumber() method.

    ReplyDelete
  70. The website loading speed is amazing. It kind of feels that you're doing any distinctive trick. Moreover, The contents are masterpiece. you have done a fantastic activity on this subject! https://ussdcodes.in

    ReplyDelete
  71. This comment has been removed by the author.

    ReplyDelete
  72. Its working, great job!

    But, is there a way to select an item from the menu list and achieve an other request programmatically?

    ReplyDelete
  73. This comment has been removed by the author.

    ReplyDelete
  74. Thanks, it works but what is the use of com.times.ussd.action.REFRESH ?

    ReplyDelete
  75. after executing above code the dialog box is continuously blinking on mobile screen how can i dismiss ..... i am very thankfull to you if you can send the complete code (abubakarhussain2013@gmail.com) .. thanks

    ReplyDelete
  76. Hi what a very informative tutorial could you please send me the Source code thanks
    Oanguome@gmail.com

    ReplyDelete
  77. Hi Thank, it work for me ! Thank

    ReplyDelete
  78. Nice Blog Post!

    Today every users love to play games on their mobile. Every day we get the encounter with a new game, in the category of fantasy, adventure, or treasure hunt. There is the pool of game to choose from the existing one and the new concept of games are developing every day by the professionals in the field of game development. If you have any idea related to the gaming industry discuss with our leading game developers India to run your project successfully.

    ReplyDelete
  79. Look at the way my colleague Wesley Virgin's report launches with this SHOCKING AND CONTROVERSIAL video.

    As a matter of fact, Wesley was in the military-and soon after leaving-he unveiled hidden, "SELF MIND CONTROL" secrets that the government and others used to get everything they want.

    As it turns out, these are the EXACT same tactics tons of celebrities (especially those who "became famous out of nowhere") and the greatest business people used to become rich and successful.

    You've heard that you use less than 10% of your brain.

    Really, that's because the majority of your brain's power is UNCONSCIOUS.

    Maybe that expression has even occurred IN YOUR own head... as it did in my good friend Wesley Virgin's head around seven years back, while driving a non-registered, trash bucket of a car without a license and $3 on his bank card.

    "I'm so frustrated with going through life paycheck to paycheck! Why can't I turn myself successful?"

    You took part in those conversations, isn't it right?

    Your success story is going to start. All you have to do is in YOURSELF.

    CLICK HERE To Find Out How To Become A MILLIONAIRE

    ReplyDelete
  80. Nice Information shared about Android Development Practice. Very helpful article for app developers to learn more and more things from here. Thanks for sharing, Keep posting...! Sales CRM Software

    ReplyDelete
  81. Hi can you please share the full source code rkgupta.mrt@gmail.com

    ReplyDelete
  82. Hi
    Is it possible to add a code which can help parse out specific information from the ussd response already in the app's log by matching it with parser (File name already in the app's cache)

    ReplyDelete
  83. Hi,
    I would like to know if anyone could make this code work. I would like to integrate it into my app to process the ussd code in the background.

    Thank's

    ReplyDelete
  84. Courier booking is an online medium for shipping couriers across the globe. If you intend to deliver goods internationally, make sure that you choose the most reliable courier services shipping your goods on time. Our company focuses on meeting up your requirements efficiently.

    ReplyDelete
  85. Hızlı takipçi almak için takipçi satın al
    Organik takipçi almak için takipçi satın al
    Bilgisayardan takipçi almak için takipçi satın al
    Mobil cihazdan takipçi almak için takipçi satın al
    Gerçek ve orijinal takipçi almak için takipçi satın al
    Yazarkasa ile takipçi almak için takipçi satın al
    Bitcoin takipçi almak için takipçi satın al
    Pos ile takipçi almak için takipçi satın al
    EFT ile takipçi almak için takipçi satın al
    Havale ile takipçi almak için takipçi satın al
    Mobil ödeme ile takipçi almak için takipçi satın al
    Tamamı orijinal takipçi almak için takipçi satın al
    Organik ile takipçi almak için takipçi satın al
    Türkiye takipçi almak için takipçi satın al
    Global takipçi almak için takipçi satın al
    En hızlı instagram takipçi satın al
    En uygun instagram takipçi satın al
    En telafili instagram takipçi satın al
    En gerçek spotify takipçi satın al
    En ucuz instagram takipçi satın al
    En otomatik instagram takipçi satın al
    En sistematik tiktok takipçi satın al
    En otantik instagram takipçi satın al
    En opsiyonel instagram takipçi satın al
    En güçlü instagram takipçi satın al
    En kuvvetli instagram takipçi satın al
    En seri instagram takipçi satın al
    En akıcı instagram takipçi satın al
    En akıcı instagram takipçi satın al
    En akıcı instagram takipçi satın al
    En akıcı instagram takip etmeyenler

    ReplyDelete
  86. Great post, if you are looking mobile app development company for your business application, then visit ThinkStart Private Limited.
    Thanks!

    ReplyDelete
  87. Hey Admin , This is very informative Article . Thank you from skip hire near me for this great informative and knowledgeful post. I want more learn like this post. Thank you again...



    ReplyDelete
  88. Helpful information about app development company & services! Nice blog.
    app development company perth

    ReplyDelete
  89. Please send me a copy of source code to test549355@gmail.com I would really appreciated

    ReplyDelete