android - IntentService 和绑定(bind)模式

标签 android

我有 IntentService 应该通过绑定(bind)使用来自另一个服务的引用:

public class BaseIntentService extends IntentService implements ServiceConnection {

    protected NetworkApi network;

    public BaseIntentService() {
        super("BaseIntentService");
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        network = ((NetworkApiBinder) service).getApi();
        // never be invoked
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        bindService(new Intent(this, NetworkApi.impl), this, BIND_AUTO_CREATE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbindService(this);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // network always null!!!
    }
}

但是当我像这样使用绑定(bind)时,永远不会调用 onServiceConnected。我知道 IntentService 不是为绑定(bind)模式设计的,但可能有针对此类任务的通用解决方案?

谢谢!

最佳答案

But when I'm using binding like this onServiceConnected never be invoked

那是因为您的 IntentService 在绑定(bind)请求开始之前就被销毁了。当 onHandleIntent() 完成所有未完成的命令时,IntentService 会自动销毁。

but may be there is a common solution for such tasks

不要有两个服务。摆脱 IntentService 并将其逻辑移至其他服务。

关于android - IntentService 和绑定(bind)模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15159689/

相关文章:

android - 我需要一个完整的 promise 内容提供者吗?

SimonVT menuDrawer 中出现 java.lang.NullPointerException?

android - 如何使用 SHA256 算法对 .apk 进行签名

java - AES 算法安全吗?

android - 如何删除 textView 上的默认填充?

java - 使用 volley 从 php 页面发送和接收

java - Android Java - 防止使用大量位图的 GC_FOR_ALLOC

android - 玩游戏 loadLeaderboardMetadata() 返回过时的数据

android - 无法在当前上下文中执行任务集上的 DefaultTaskContainer#register(String, Class, Action)

android - 如何根据字符串变量按名称获取资源?