gpt4 book ai didi

Android:如何实现 "distributed control"

转载 作者:太空宇宙 更新时间:2023-11-03 10:30:41 25 4
gpt4 key购买 nike

{对于与 android-developers 论坛的交叉发帖表示歉意。那里没有收到任何答复

我有一个有趣的设计挑战:

我有一个前端( Activity )和一个后端(用 native C/C++ 编写)代码。后端是一个复杂的对象,它部分控制应用程序流程一旦启动就在它自己的线程中运行。所以我有“分布式控制”场景。

Activity 需要能够异步发送消息到后端然后采取某些行动。但是 后台也需要能够异步发送消息到 Activity ,它通过更改 UI、触发方法等进行响应。

本质上,我需要的是一个双向监听器。

所以后端向屏幕发送消息(拍照,提示用户,获取位置,现在拍另一张照片等)和屏幕做它需要的去做。但除此之外,屏幕还应该可以调用后端监听器发送回消息(捕获的相机图像,系统生成 - “我被暂停/销毁”消息等)在回调中这些事件。主要问题是这都是异步的。

这在没有紧耦合的情况下可能吗?这可能吗?

我想到了 Asynctask/handlers(但这是一条单向的道路通知 UI 线程),观察者模式(两个对象都将observer/observable?) 但不知道从哪里开始。有什么想法吗,链接会很有帮助。

最佳答案

在您的 native 代码中,您可以使用 JNI 从您的 VM 获取类(和对象),并且一旦您获得类(或对象),您就可以找到方法并调用它们(类的静态方法,所有对象的方法)。在我看来,简单的解决方案是在您的 java 类中提供一个帮助器,它封装了 native 方法并让 native 代码调用它。

过去,我需要让 native 代码确定其线程是否已在 Java 级别中断。 Java 提供 java.lang.Thread.currentThread() 作为一个静态来找到你自己的线程,和 java.lang.Thread.isInterrupted() [非破坏性] 确定中断状态。我使用以下方法在 native 级别解决了这个问题;也许您可以根据您的需要使用它(当然,要适本地适应消息发送):

/* JavaThread: this class is a simple wrapper to be used around    */
/* JNI's Thread class. It locates the provided functions as needed */
/* and when it is destroyed (such as going out of scope) it will */
/* release its local references. */
class JavaThread
{
public:
JavaThread(JNIEnv *env)
{
mEnv = env;

/* find the Java Thread class within the JVM: */
mThread = mEnv->FindClass("java/lang/Thread");

/* find the Thread.currentThread() method within the JVM: */
mCurrentThreadMID = mEnv->GetStaticMethodID(mThread, "currentThread", "()Ljava/lang/Thread;");

/* find the current thread's isInterrupted() method: */
mIsInterruptedMID = mEnv->GetMethodID(mThread, "isInterrupted", "()Z");
}
~JavaThread()
{
if (mThread)
{
mEnv->DeleteLocalRef(mThread);
mThread = 0;
}
}

bool isInterrupted() {
bool bResult;
if (!mThread) return false;
if (!mIsInterruptedMID) return false;

/* find the current thread (from the JVM's perspective): */
jobject jCurrentThread = (jobject)mEnv->CallStaticObjectMethod(mThread, mCurrentThreadMID);
if (NULL == jCurrentThread) return false;

/* see if the current thread is interrupted */
bResult = (bool)mEnv->CallBooleanMethod(jCurrentThread, mIsInterruptedMID);

/* delete the current thread reference */
mEnv->DeleteLocalRef(jCurrentThread);

/* and return the result */
return bResult;
}

private:
JNIEnv *mEnv;
jclass mThread;
jmethodID mCurrentThreadMID;
jmethodID mIsInterruptedMID;
};

实例化基于提供给您的 native 方法的 JNIEnv *,调用 isInterrupted() 方法的简单分配/调用/解除分配代码行是:

if (JavaThread(env).isInterrupted()) { ... }

关于Android:如何实现 "distributed control",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6142351/

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