【问题标题】:ServiceConnection::onServiceConnected not called even though Context::bindService returns true?即使 Context::bindService 返回 true,也没有调用 ServiceConnection::onServiceConnected?
【发布时间】:2009-10-17 04:47:44
【问题描述】:

我一直在尝试绑定从活动启动时启动的服务。开机启动代码大部分取自instant messenger

这是 3 个主要组件的 AndroidManifest.xml 定义:

    <!-- Receiver -->
    <receiver android:name=".receiver.LifestylePPAutoStarter"
        android:process="android.process.lifestylepp">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
        </intent-filter>
    </receiver>

    <!-- Service -->
    <service android:name=".service.LifestylePPService"
        android:process="android.process.lifestylepp"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="edu.gatech.lifestylepp.ILifestylePPService" />
            <action android:name="edu.gatech.lifestylepp.SERVICE" />
        </intent-filter>
    </service>

    <!-- Activity -->
    <activity android:name=".app.LifestylePPActivity"
        android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

接收器在启动时启动服务没有任何问题。但是,当我尝试从我的活动绑定服务时,Context::bindService 返回 true,但从不调用 ServiceConnection::onServiceConnected。此外,当我从 Activity 启动服务时,它按预期工作(调用 ServiceConnection::onServiceConnected)。

【问题讨论】:

    标签: android service


    【解决方案1】:

    另外,当我从 它按预期工作的活动 (ServiceConnection::onServiceConnected 被调用)。

    startService() 不涉及ServiceConnection 对象。

    从清单中删除 android:process="android.process.lifestylepp" 这两行。这可能是您遇到困难的根源,更重要的是,您不太可能真的需要两个进程以及所需的所有开销。

    【讨论】:

    • 我知道 startService() 不涉及 ServiceConnection。我一直想说的是:当我从 Activity 启动服务时,我可以使用 bindService(intent, connection, 0) 绑定它而没有任何问题。仅当从接收方启动服务时才会出现此问题。不过还是谢谢你的建议!不幸的是,我已经尝试在同一个进程上运行活动和服务,但它没有改变任何东西。
    • 在您的 bindService() 调用中添加 BIND_AUTO_CREATE 标志。
    • 这不会导致启动新服务吗?该服务已经在运行,它是由接收器在启动时创建的。我只想从活动中绑定它。
    • 如果没有相应的 startService(),bindService() 不起作用,那么您的服务不会启动。时期。您可能认为您是在启动时启动它,但要么不起作用,要么您尝试绑定到服务的方式导致 Android 认为您正在绑定到不同的服务,或者其他什么。
    • 你是对的,服务没有运行。我觉得很愚蠢。它确实在启动时启动,但似乎在部署应用程序包时它被杀死了。活动开始时它已经死了。我想我唯一能说的就是奇怪地 bindService() 确实返回了 true。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多