在活动中启动当前服务实例

时间:2016-06-07 06:20:37

标签: java android service

我有这样的服务:

public class MyService extends Service{
    .
    .
    .
    private Activity source;
    public setActivity(Activity source){
        this.source=source;
    }
}

和这样的活动:

public class MyActivity extends Activity{
    .
    .
    .
    @Override
    public void onCreate(Bundle savedInstanceState){
        .
        .
        MyService service=new MyService();
        service.setActivity(this);
        //in this place I want start my service.
        //but if I use Intent, it run another instance of my service.
        Intent intent = new Intent(this,MyService.class);
        startService(intent);
    }
}

如何启动当前实例服务?在这个地方,我想要开始service

1 个答案:

答案 0 :(得分:0)

在服务中保留活动实例并不是一个好主意。

Android指南说:

  

服务是一个应用程序组件,可以在后台执行长时间运行的操作,但不提供用户界面。

您可以使用意图在后台启动服务。

Intent intent = new Intent(this,MyService.class);
startService(intent);

如果您尝试使用此服务作出回复,请结帐tutorials related to service以便更好地了解该服务。