I have been searching and found this post useful in getting the telephone number of my device. In my main service file, I have a public static variable that is set to the phone number found using the method in the aforementioned post.
class MyService extends Service implements... {
//Phone number of the device
public static String phoneNumber;
public void onCreate() {
//Grab phone number of device
TelephonyManager tMgr = (TelephonyManager)getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
phoneNumber=mPhoneNumber;
}
}
I am by no means an advanced software developer but I know that using a public static variable is not the best solution since it can be changed from outside the class. This public static phone number is being accessed in another class which sends it to a server. And it is being accessed like so:
String devicePhoneNumber;
devicePhoneNumber = MyService.phoneNumber;
I wouldn't have to worry about this problem if there a way to get the phone number and IMEI without using TelephonyManager, or more specifically without needing the application context. If that is not possible, perhaps there is a workaround for using a public static variable?
Thanks for all the help
There isn't a workaround for getting phonenumbers without the Context because the Context is your gateway into the users phone. It gives you access to storage, Location, display, almost everything.
If you use the phonenumber a lot I think you should make a getter for it in the mainActivity, that's where your getting it from anyway. In your mainActivity onCreate() method initialize
to be the phone number and in your mainActivity make a
To access it from your Service, and in other parts of the app you can call
unless your working in a static method. You'll still need access to the MainActivity though. I usually do this in the mainActivity:
hopefully that syntax is right, try merging the above into your mainActivity and calling it from your Service with