如何从一个类运行服务?

时间:2012-04-18 18:02:40

标签: android service android-activity

我有一个这样的课程:

public class ExpandableListAdapter extends BaseExpandableListAdapter {

我想从这个类运行一个服务。但据我所知,服务只能从Activitys运行。那么解决方案是什么?

如何启动服务并从另一个类控制它?

2 个答案:

答案 0 :(得分:1)

  
    

但据我所知,服务只能从活动

运行   

那不是真的。为了运行服务,您只需要一个上下文,通常是对您的活动的引用。

因此,在ExpandableListAdapter中,您只需确保构造函数接收您的活动实例:

public ExpandableListAdapter(Context context){
    mContext = context;
}

// somewhere else
mContext.startService(theIntent);

答案 1 :(得分:0)

大多数适配器都有一个上下文,因此您可以调用getContext(),它将为您提供上下文。此适配器没有上下文,因此您应该有一个自定义构造函数,它接受上下文并调用其超级。使用您传入的上下文,您可以像在活动中一样调用startService(Intent intent)