如何解决Android:如何实现“分布式控件”
| {与android-developers论坛交叉发布的道歉。那里没有收到任何答案} 我面临一个有趣的设计挑战: 我有一个前端(活动)和一个后端(用本机C / C ++编写) 码。后端是一个复杂的对象,它部分地控制 应用程序流和启动后便在其自己的线程中运行。所以我有 一个“分布式控件”方案。 活动需要能够异步发送消息到 后端,然后采取某些措施。但是后端也需要 能够异步地向活动发送消息, 它通过更改UI,触发方法等进行响应。 本质上,我需要的是双向监听器。 因此后端向屏幕发送一条消息(拍照,提示用户,获取 位置,现在再拍一张照片,等等),然后屏幕执行所需的操作 去做。但除此之外,屏幕还应该能够调用 后端侦听器发送回消息(捕获的摄像机图像,系统 产生-\“我被暂停/销毁\”消息,等等)的回调 这些事件。主要问题是这都是异步的。 如果没有紧密耦合,这可能吗?这有可能吗? 我已经想到了Asynctask / handlers(但这是一条通往 通知UI线程),观察者模式(两个对象都是 观察者/可观察的?),但对从何处开始感到困惑。有什么想法吗, 链接将非常有帮助。解决方法
在您的本机代码中,您可以使用JNI从VM中获取类(和对象),一旦获得了类(或对象),您就可以找到方法并调用它们(类的静态方法,一个东西)。在我看来,简单的解决方案是在java类中提供一个帮助器,该帮助器封装本机方法并调用本机代码。
过去,我需要让本机代码确定其线程是否已在Java级别被中断。 Java提供了java.lang.Thread.currentThread()作为静态变量来查找您自己的线程,而Java.lang.Thread.isInterrupted()可以[非破坏性地]确定中断状态。我使用以下方法在本机级别解决了此问题;也许您可以根据需要使用它(当然,可以适当地适应消息发送):
/* 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;
};
实例化基于提供给本机方法的JNIEnv *,用于调用isInterrupted()方法的简单分配/调用/解除分配代码行是:
if (JavaThread(env).isInterrupted()) { ... }
,如何使用阻塞队列,因为您的描述使我想起了并行编程类中的经典生产者-消费者问题。
http://en.wikipedia.org/wiki/Producer-consumer_problem
Java 1.5似乎也有阻塞队列的实现,如果它在Android上可用,我想不起来。
http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html
我想您可以设置2个单向阻塞队列以进行每种通信。第一季度将前端作为生产者,后端作为消费者。第二季度将前端作为消费者,后端作为生产者。
您也可以使用“命令”设计模式进行“消息”通信。
http://en.wikipedia.org/wiki/Command_pattern
高温超导
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。