gpt4 book ai didi

android - 为什么在主要 Activity 关闭时远程服务会被破坏?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:40:01 24 4
gpt4 key购买 nike

我写了一个 android 程序:有一个 UI 的主要 Activity ,它启动了一个服务。该服务及时回调 UI Activity 以更新 View 。它工作正常,除了:如果 Activity 关闭(使用 BACK)并再次启动,服务也将再次启动(服务播放音频文件,因此有两个重叠的声音)。我使用带有 BIND_AUTO_CREATE 标志的 bindService 来启动和连接到服务。根据文档,只有当它不存在时才应该创建服务,但显然它在第二次打开时会启动另一个实例。我想要的只是当 Activity 关闭时,服务继续运行,当 Activity 再次打开时,它可以重新连接到服务。那可能吗?或者我只是误解了服务的用法?

尝试了更多:在 bindService Intent 中使用 ICountService(在 .aidl 中描述)而不是 CountService。它的 onDestroyed 在 Activity 关闭时被调用。

如果有帮助,下面是服务创建代码。

    ServiceConnection conn = new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName c, IBinder b) {
Log.d("TK","Connected");
//binder = (ICountService.Stub) b;
service = ICountService.Stub.asInterface(b);
try {
service.setCallback(new ICountCallback.Stub(){

@Override
public void alert() {
Log.d("TK","alert!");
}

@Override
public void updateTime(final int sec) {
handler.post(new Runnable(){

@Override
public void run() {
indicator.setText(toText(sec));
}

});
}
});
} catch (RemoteException e) {
e.printStackTrace();
}
}

@Override
public void onServiceDisconnected(ComponentName c) {
Log.d("TK","Disconnected");
}
};

private void startCountService(){
Intent i = new Intent(ICountService.class.getName());
boolean ok = context.bindService(i, conn, Context.BIND_AUTO_CREATE);
Log.d("TK", "bindService="+ok);
}

最佳答案

According to the document, it should create service only if it doesn't exist, but obviously it starts another instance when opened second time.

bindService() 将在服务未运行时创建服务实例。如果没有其他绑定(bind)连接并且没有人调用 startService()unbindService() 将销毁服务实例。如果服务在 unbindService() 上被销毁,则后续的 bindService() 将创建一个新的服务实例。

恕我直言,理想情况下,unbindService() 不会立即销毁该服务,而是先让它停留几秒钟,以防很快有 bindService()unbindService() 之后。然而,这并不是他们实现的方式。

All I want is when the activity is closed, the service goes on running, and when the activity opens again, it can reconnect to the service.

你应该使用 startService()stopService() 而不是(或者可以想象除了) bindService()unbindService().

关于android - 为什么在主要 Activity 关闭时远程服务会被破坏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4225847/

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