应用程序启动时绑定和启动服务

时间:2016-06-22 09:08:31

标签: android android-service android-service-binding

我在Android中有一项服务,它封装了一个具有start方法的框架。服务归结为这样的事情,省略了许多事情:

public class MyService extends Service {

    private IBinder thisBinder;

    public MyService(){
        thisBinder = new LocalBinder();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return thisBinder;
    }

    public void start(Map<String, Object> options)
    {
        getDriverManager().start(options);
    }
}

我还有一个桥接类来调用服务:

public class MyServiceBridge implements ServiceConnection {

    private boolean started = false;
    private boolean bound = false;
    private MyService myService;

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

    public void bindService(){
        Intent intent = new Intent(getContext(), MyService.class);

        getContext().bindService(intent, this, getContext().BIND_AUTO_CREATE);
        getContext().startService(intent);
    }

    // Here's a sample call, and the one that is relevant
    public void start(Map<String, Object> options){
        setOptions(options);
        if(bound == true){
            getMyService().start(options);
        }
        else{
            started = true;
        }
    }
}

我调用了网桥的start方法来运行该服务。这种方法很好,除了在这种特殊情况下(到目前为止)。 MyApplication类在onCreate上调用网桥的启动方法:

public class MyApplication extends Application {

    @Override
    public void onCreate() {

        super.onCreate();

        getServiceBridge().start(null);
    }
}

这个,according to the docs在应用程序启动时调用,在创建任何活动,服务或接收者对象(不包括内容提供者)之前调用。&#34;。事实上它似乎是这样,因为服务没有启动,而是在我关闭应用程序时启动(奇数,至少)。如果我将呼叫转移到活动的onCreate方法,这是有效的,但这并不理想,因为我也可以停止服务,我希望服务在应用的生命周期内运行。也就是说,服务应该在应用程序启动时启动,并在应用程序终止时停止。这有意义吗?还有另一种方法吗?

1 个答案:

答案 0 :(得分:2)

在我看来,当你决定在Application onCreate中运行服务时,你做得很好。但是当你关闭应用程序时听到服务启动是很奇怪的。 我已经多次这样做了,服务开始于应用onCreate,必须被调用。

您是否检查过您的应用程序是否存活并在后台运行?请确保在测试前杀死了您的应用程序。使用Task Killer或类似的东西,以确保应用程序始终是新开始的。

可悲的是,Android没有适当的机制在退出应用程序时通知您,因为它在系统决定终止并释放资源之前仍然存在。

相关问题