【问题标题】:Issue starting activity from non-activity class从非活动类发出开始活动
【发布时间】:2012-09-07 14:00:31
【问题描述】:

我是 android 的菜鸟,我有一个也使用 OverlayItems 的 Map Activity。在我的覆盖类的 onButtonTap 方法中,我想执行 startActivity,这样我就可以使用 intent.ACTION_CALL。

Intent callIntent = new Intent(Intent.ACTION_CALL);   
callIntent.setData(Uri.parse("tel:"+MapActivity.phonenumber0));
startActivity(callIntent);

在上面的代码中,我被要求为 startActivity(Intent) 创建一个我不明白的方法。当我尝试...

Intent callIntent = new Intent(Intent.ACTION_CALL);   
callIntent.setData(Uri.parse("tel:"+MapActivity.phonenumber0));
MapActivity.startActivity(callIntent);

它说我不能对非静态方法的非静态引用进行静态引用。当我尝试使用对象的上下文时,即被点击的按钮,它不允许我这样做。

Intent callIntent = new Intent(Intent.ACTION_CALL);   
callIntent.setData(Uri.parse("tel:"+MapActivity.phonenumber0));
ContextObj.startActivity(callIntent);

当然,将这段代码移动到主 Activity 需要一个静态方法,该方法会出现一系列问题。

如何为 startActivity 设置合适的上下文?非常感谢任何帮助。

【问题讨论】:

    标签: android class android-intent android-activity static


    【解决方案1】:

    您可以像这样在 MapActivity 类中创建方法来获取上下文...

    编辑: 取一些像这样的静态变量...

    public static Context mContext;
    

    在 Activity 的 onCreate() 方法中为其分配基本上下文...

    mContext = getBaseContext();
    

    & 返回 mContext...

    public static Context getContext() {
        return mContext;
    }
    

    & 将其调用到您的非活动类中以开始活动...

    Intent callIntent = new Intent(Intent.ACTION_CALL);   
    callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    callIntent.setData(Uri.parse("tel:"+MapActivity.phonenumber0));
    MapActivity.getContext().startActivity(callIntent);
    

    【讨论】:

    • 编辑说我不能静态引用 getBasecontext
    • 开始工作了!只需添加 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);感谢您的帮助。
    【解决方案2】:

    在开始活动之前试试这个设置这个标志:

    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    

    希望它会起作用。

    【讨论】:

      【解决方案3】:

      您可以将活动的上下文(地图活动)传递给您的类,然后使用它..

      【讨论】:

      • 在其他类的构造函数中..如果您提供更多代码我可以提供帮助
      • 公共类 MapActivity 扩展 MapActivity 实现 View.OnClickListener、OnItemSelectedListener、LocationListener、OnCheckedChangeListener.. 是我对其他类的全部。我要为 startActivity 创建一个公共类吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多