从Application类传递活动

时间:2014-12-29 20:12:28

标签: android

我正在使用以下代码在应用程序中创建一个类:

public class Trackers extends Application
{
       private static Connection connection;
       public Connection getConnectionInstance() {
           if (connection == null)
               connection = new Connection();
           return connection;
       }
}

我需要将Main活动传递给Connection类。这可能吗?如果有可能,怎么样?

1 个答案:

答案 0 :(得分:1)

您可以将主活动作为参数添加到连接构造函数中:

public class Trackers extends Application
{
       private static Connection connection;

       public Connection getConnectionInstance(MainActivity main) {
           if (connection == null){
               connection = new Connection(main);
           }
           return connection;
       }
}

当然,我认为如果你想将活动传递给Connction,连接需要支持获取主要活动

如果你想从activty调用方法,请看这里: How to call a method in activity from a service

或在这里: android start activity from service