gpt4 book ai didi

android - 为什么不调用 onServiceConnected?

转载 作者:行者123 更新时间:2023-11-29 00:49:50 25 4
gpt4 key购买 nike

我是一个初学者,我编写了一个简单的程序来展示服务的工作原理。

.....
toStartService = new Intent(this, SimpleService.class);
sc = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Toast.makeText(MoreService.this, "SC: Binded", Toast.LENGTH_SHORT).show();
}

@Override
public void onServiceDisconnected(ComponentName name) {
Toast.makeText(MoreService.this, "SC: Unbinded", Toast.LENGTH_SHORT).show();
}
};


startService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MoreService.this, "Starting Service", Toast.LENGTH_SHORT).show();
startService(toStartService);
}
});

stopService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopService(toStartService);
}
});

bindService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if((isBound = bindService(toStartService, sc, BIND_AUTO_CREATE))) {

}
}
});

unbindService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(isBound) {
unbindService(sc);
isBound = false;
}
}
});

}

为什么不传递 sc 变量(在 bindService() 上)调用 sc.onServiceConnected() 方法?代码有什么问题?

我满足了以下条件:

  • 当我按下 [startService] 时服务开始很好,然后[stopService]服务正常停止。

  • 当我按下 [startService] 时,[bindService] 什么都不做,[unbindService] 也不做。

  • 当我按下 [bindService] 时,它创建了服务,[stopService] 没有工作。我按 [unbindService] 服务正在调用 onDestroy() 方法。

为什么bindService创建的服务在解除绑定(bind)时会被销毁?我尝试用 startService 启动服务,但它无法绑定(bind)。

啊帮帮我,如果我错了抱歉。

最佳答案

这是所有这些方法的设计行为。例如,在 bindService(Intent service, ServiceConnection conn, int flags) 方法中根据 the documentation ,服务只会在调用上下文存在时运行:

The service will be considered required by the system only for as long as the calling context exists. For example, if this Context is an Activity that is stopped, the service will not be required to continue running until the Activity is resumed.

对于 unbindService (ServiceConnection conn)文档说:

Disconnect from an application service. You will no longer receive calls as the service is restarted, and the service is now allowed to stop at any time.

startService (Intent service) documentation它说:

Using startService() overrides the default service lifetime that is managed by bindService(Intent, ServiceConnection, int): it requires the service to remain running until stopService(Intent) is called, regardless of whether any clients are connected to it. Note that calls to startService() are not nesting: no matter how many times you call startService(), a single call to stopService(Intent) will stop it.

关于android - 为什么不调用 onServiceConnected?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3792344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com