在应用程序启动时绑定并启动服务

Binding and starting a service when application starts

我在 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);
    }
}

我还有一个桥接 class 可以调用该服务:

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 class 在 onCreate:

上调用网桥的启动方法
public class MyApplication extends Application {

    @Override
    public void onCreate() {

        super.onCreate();

        getServiceBridge().start(null);
    }
}

这个,according to the docs就是"Called when the application is starting, before any activity, service, or receiver objects (excluding content providers) have been created."。确实如此,因为服务没有启动,而是在我关闭应用程序时启动(至少是奇怪的)。如果我将调用移动到 activity 的 onCreate 方法,这会起作用,但这并不理想,因为我也可以停止服务,并且我希望服务在 运行 的生命周期内应用程序。也就是说,服务应该在应用程序启动时启动,并在应用程序终止时停止。这有意义吗?还有其他方法吗?

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

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

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