如果存在,则绑定到服务

Mr.*_*.Me 4 android android-intent android-service android-activity

我正在开发一个项目,如果该服务正在运行,则需要一个活动来连接到本地服务,如果它没有运行则启动它.这种方法的适用标志是什么.

Jen*_*ens 6

这可以通过例如传入0最后一个参数来完成#bindService(Intent, ServiceConnection, int).

例如

bindService(new Intent(this, MrMeService.class), new ServiceConnection(){
        public void onServiceDisconnected(ComponentName name) {
            System.out.println("Service disconnected");
        }
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("Service connected");
        }
    }, 0);
Run Code Online (Sandbox Code Playgroud)

#bindService(..)调用将返回true,但该服务将不会真正开始,你的服务连接不会触发,直到有人用实际启动该服务,例如#startService(Intent).至少这是它在ICS和Gingerbread上的工作方式.