从不扩展Activity的类的startService

时间:2012-12-14 15:59:03

标签: android android-activity service android-context

我创建了一个扩展IntentService的类,我想从一个不是Activity的类启动服务,因此,我无法访问Context对象。我在文档或网络上找不到这样的例子。有可能吗?

2 个答案:

答案 0 :(得分:19)

您需要将当前的Activity上下文传递给非Activity类,以便从非活动类启动服务:

public class NonActivity {
  public Context context;

  public NonActivity(Context context){
    this.context=context;
  }

  public void startServicefromNonActivity(){
     Intent intent=new Intent(context,yourIntentService.class);
     context.startService(intent);
  }
}

并将当前上下文传递为:

public class AppActivity extends Activity {
    NonActivity nonactiityobj;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
                 nonactiityobj=new NonActivity(CuttentActivity.this);
                 //start service here
                 nonactiityobj.startServicefromNonActivity();
    }
}

答案 1 :(得分:2)

使用此代码启动和停止服务

public class MyService {

Context context ;

public MyService(Context cont) {
    this.context = context ;
}

public void StartMyService()
{
    Intent i = new Intent(context,YourService.class);
    context.startService(i);
}
public void StopMyService()
{
    Intent i = new Intent(context,YourService.class);
    context.stopService(i);
}
}

这只是创建这个类的对象

  MyService mySevice ;
  @Override
  public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  myService = new MyService(this);
  //For Startting Service
  myService.StartMyService();

  //For Stopping Service
  myService.StopMyService();
}