Search code examples
androidtelephonymanagerandroid-context

Telephony manager in Application class


When I try to use telephony manager to retrieve the phone number from an Activity class, I am able to do it successfully. But I will be using the phone number in multiple places of the app, therefore I shifted the phone number to be a static field in my application class.

    public class FourApplication extends Application {

    static String phonenumber ;
    @Override
    public void onCreate() {
        super.onCreate();
        ParseObject.registerSubclass(Post.class);
        // Add your initialization code here
        Parse.initialize(this, "**********", "*********");


        ParseACL defaultACL = new ParseACL();

        // If you would like all objects to be private by default, remove this
        // line.
        defaultACL.setPublicReadAccess(true);

        ParseACL.setDefaultACL(defaultACL, true);
        phonenumber = getPhoneNumber();
    }

    public String getPhoneNumber()
    {
        TelephonyManager tMgr =(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
        String mPhoneNumber = tMgr.getLine1Number(); ;


          Log.i("mPhoneNumber : ", mPhoneNumber);
        return mPhoneNumber;
    }
}

What is the mistake I am making here? I read through a few Context related questions and threads, Not able to figure out what's going wrong in my code as I am noob here.

Edit : My question is, When I move the telephony manager part to the application class, it doesn't return a phone number. Why is that?


Solution

  • @55597

    Please use the following piece of code.You got your problem

    TelephonyManager tMgr =(TelephonyManager)getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
    

    You are not passing the correct context of Activity for TelephonyManager, So that its return null.