【问题标题】:Where can Intents be called [duplicate]Intents在哪里可以调用[重复]
【发布时间】:2012-10-27 17:21:34
【问题描述】:

可能重复:
Launching intent from a class outside an activity

我只是想知道可以从 POJO 类中使用意图,还是必须在扩展 Activity 的类中使用它?如果可以的话,你将如何实现?

public class DataManager{

public DataManager (){}


public void get ()
{
    Intent intent = new Intent (null,Webservice.class);
    intent.putExtra("uri", "http://someuri/service/users/id/21001");
    startActivity (intent);
}

}

【问题讨论】:

    标签: android


    【解决方案1】:

    其实startActivity()是Activity类的方法。不是任何java类方法。因此,要在其他 pojo 类 中访问此方法,您必须使用活动的Context

    你可以这样做,

    public class DataManager{
    
     Context mContext;
    
     public DataManager (Context context){
     mContext = context;
     }    
    
     public void get ()
     {
        Intent intent = new Intent (mContext,Webservice.class);
        intent.putExtra("uri", "http://someuri/service/users/id/21001");
        mContext.startActivity (intent);
     }
    }
    

    更新:

    需要注意的一点是您的 Intent 代码行,

    Intent intent = new Intent (null,Webservice.class);
    

    什么是 null ?您必须将 Activity 类的引用作为 Intent 构造函数的第一个参数。看看就好。

    所以代码行将是,

    Intent intent = new Intent (mContext,Webservice.class);
    

    【讨论】:

    • intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); :)
    • @MMohsinNaeem - 只有当您想将活动放入新任务时才需要它。没必要。
    • @user370305 :我会将Context 传递给DataManagerget(...) 方法,以防止内存泄漏的可能性。
    • @user370305 a Broadcast ReceiveronRecive 中也有Context。您可以使用该上下文启动Activity...
    【解决方案2】:

    是的,您可以从任何其他班级拨打Activity。在将Current ActivityContext 的引用传递给该类之后。比如……

    Intent myIntent = new Intent(mContext, newActivity.class);
    myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    mContext.startActivity(myIntent);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-11
      • 2011-09-15
      • 2018-06-14
      相关资源
      最近更新 更多