Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ;
          }
}
like image 288
Ehsan Avatar asked Dec 20 '13 17:12

Ehsan


2 Answers

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())
    }
});
like image 124
petey Avatar answered Nov 11 '22 12:11

petey


What about...

Context ctx = getActivity().getApplicationContext();
like image 38
Phantômaxx Avatar answered Nov 11 '22 12:11

Phantômaxx