Adb
Adb

Reputation: 195

How to get getSystemService using myConext

i am doing given below but it is giving exception unable to instantiate activity

java.lang.InstantiationException

below is my code>

 public class GetDeviceIdActivity extends Activity{

Context myContext;
public GetDeviceIdActivity(Context myContext)
{
    this.myContext = myContext;

}

TelephonyManager telephonyManager = (TelephonyManager)myContext.getSystemService(Context.TELEPHONY_SERVICE);
String imei = telephonyManager.getDeviceId();

Upvotes: 2

Views: 10187

Answers (2)

AAnkit
AAnkit

Reputation: 27549

Your approach is wrong, you are already in Activity, you don't need context to get Telephony manager context, Use below code. or instantiate tm in oncreate method. or by using this keyword, or by using activityname.this keyword.

    public class GetDeviceIdActivity extends Activity{

     Context myContext;
     public GetDeviceIdActivity(Context myContext)
       {
          this.myContext = myContext;

                }

TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String imei = telephonyManager.getDeviceId();

Upvotes: 2

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132982

try as:

TelephonyManager telephonyManager = (TelephonyManager)getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
String imei = telephonyManager.getDeviceId();

Upvotes: 1

Related Questions