how to use getBaseContext() in class which is not extends Activity
Asked Answered
I

2

6

I am creating a module that extends from another class but i need to use getBaseContext(). how can I use it in my own module? If I have to run the activity then how to do that if not how to solve the problem thanks

public class TelcoModule extends KrollModule
{
...

        // Methods
    @Kroll.method
    public String GetTelco()
    {
           TelephonyManager tm =(TelephonyManager)getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
           String operatorName = tm.getNetworkOperatorName();
           return operatorName ;
          }
}
Inion answered 20/12, 2013 at 17:22 Comment(2)
just pass the context in your constructor for the classDyslogistic
Context mContext;public TelcoModule(Context context) {mContext =context;// use mContext..}. pass like new TelcoModule(ActivityName.this)Boswell
H
3

Change GetTelco to include a context param. Then call it using your available context from anywhere

public String GetTelco(final Context context)
{
       TelephonyManager tm =(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
       String operatorName = tm.getNetworkOperatorName();
}

Example of calling it:

someView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String telcoName = myTelcoInstance.GetTelco(v.getContext())
    }
});
Helse answered 20/12, 2013 at 17:25 Comment(1)
Whit the help of your comment i could solve it :) Context appContext = (Context) TiApplication.getInstance(); TelephonyManager tm =(TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE); String operatorName = tm.getNetworkOperatorName(); return operatorName;Inion
T
1

What about...

Context ctx = getActivity().getApplicationContext();
Tedda answered 20/12, 2013 at 17:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.