【问题标题】:how to use getBaseContext() in class which is not extends Activity如何在不扩展 Activity 的类中使用 getBaseContext()
【发布时间】:2014-01-09 14:59:08
【问题描述】:

我正在创建一个从另一个类扩展的模块,但我需要使用 getBaseContext()。如何在我自己的模块中使用它? 如果我必须运行活动,那么如果不是如何解决问题,该怎么做 谢谢

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 ;
          }
}

【问题讨论】:

  • 只需在类的构造函数中传递上下文
  • Context mContext;public TelcoModule(Context context) {mContext =context;// use mContext..}。通过像new TelcoModule(ActivityName.this)

标签: android module titanium


【解决方案1】:

更改 GetTelco 以包含上下文参数。然后使用您在任何地方的可用上下文调用它

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

调用示例:

someView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String telcoName = myTelcoInstance.GetTelco(v.getContext())
    }
});

【讨论】:

  • 借助您的评论,我可以解决它 :) Context appContext = (Context) TiApplication.getInstance(); TelephonyManager tm =(TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE); String operatorName = tm.getNetworkOperatorName(); return operatorName;
【解决方案2】:

怎么样……

Context ctx = getActivity().getApplicationContext();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-19
    相关资源
    最近更新 更多