gpt4 book ai didi

android - 在不复制相同代码的情况下,在我的应用程序的每个 Activity 中与服务通信的最佳方式是什么?

转载 作者:行者123 更新时间:2023-11-30 00:45:19 25 4
gpt4 key购买 nike

我实现了一个服务,并使用 Messenger 及其处理程序作为通信桥梁。每次我开始一项 Activity 时,我都必须遵循以下步骤:

1) 创建服务连接

private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mService = new Messenger(service);
try {
Message msg = Message.obtain(null, ConstantStuff.MSG_REGISTER_CLIENT);
msg.replyTo = mMessenger;
egoService.send(msg);
} catch (RemoteException e) {
Log.e("HELPER", "FAIL - Service crashed" + e.getMessage());
}
}

public void onServiceDisconnected(ComponentName className) {
mService = null;
}
};

2) 创建信使

final Messenger mMessenger = new Messenger(new ActivityOne.IncomingMessageHandler());

class IncomingMessageHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case ConstantStuff.MACRO_SEND_PWD:
if (msg.arg1 == 1) {
Log.e("PWD", "SUCCESS");
} else if (msg.arg1 == 0) {
Log.e("PWD", "FAIL");
}
break;
default:
super.handleMessage(msg);
}
}
}

3) 将服务绑定(bind)到我的 Activity

public void doBindService() {
this.bindService(new Intent(this, NetworkService.class), mConnection, Context.BIND_AUTO_CREATE);
isBound = true;
Log.e("HELPER", "DO BIND");
}

4) 开始使用服务

private void sendPwd(String pwd) {
if (isBound) {
if (mService != null) {
try {
Bundle b = new Bundle();
b.putByte("Command", (byte) ConstantStuff.MACRO_SEND_PWD);
b.putString("Password", password);
b.putString("Param0", password);
b.putString("Param1", "dummy");
b.putString("Param2", "dummy");
b.putString("Param3", "dummy");
Message msg = Message.obtain(null, ConstantStuff.MSG_MACRO);
msg.setData(b);
msg.replyTo = mMessenger;
mService.send(msg);
} catch (Exception e) {}
}
}
}

5) 在我的任务结束时解除服务与我的 Activity 的绑定(bind)

public void doUnbindService() {
if (isBound) {
if (mService != null) {
try {
Message msg = Message.obtain(null, ConstantStuff.MSG_UNREGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
} catch (RemoteException e) {
Log.e("HELPER", "FAIL - DO UnBIND" + e.getMessage());
}
}
this.unbindService(mConnection);
isBound = false;
Log.e("HELPER", "DO UnBIND");
}
}

我需要在我的应用程序的几乎所有 Activity 中与我的服务进行通信,我不想每次都重复所有代码。将所有 Activity 扩展到父亲 Activity 是一个好的解决方案吗?是不是可以把所有的通讯代码都写在“Application”里?

最佳答案

在您希望服务与 UI 交互的任何 Activity 中,对这些 Activity 使用“bindService”及其回调方法“onServiceConnected”和“onServiceDisconnected”。如果您希望服务即使在应用程序关闭时也能运行,请将 startService 与 startsticky/startnonsticky/startforeground 一起使用。对于所有的 Activity ,您只需要一个服务等级。在您的情况下,您已经编写了完美的服务类以及一个 Activity 。现在绑定(bind)开头提到的其余 Activity 。我还没有使用过 Messenger,所以请确保这一点。

关于android - 在不复制相同代码的情况下,在我的应用程序的每个 Activity 中与服务通信的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41890096/

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