{对android开发者论坛的交叉帖子表示歉意。还没有收到任何答案}
我有一个有趣的设计挑战:
我有一个前端(活动)和一个后端(用本机C/C++编写)代码。后端是一个复杂的对象,它部分地控制应用程序的流&一旦启动,就在它自己的线程中运行。所以我有一个“分布式控制”的场景。
活动需要能够异步地向后端发送消息,然后后端执行某些操作。但是,后端还需要能够异步地向活动发送消息,并通过chnaging、激发方法等对其进行响应。
本质上我需要的是一个双向的倾听者。
因此后端会向屏幕发送一条消息(拍照、提示用户、获取位置、现在再拍一张照片等等),然后屏幕就会做它需要做的事情。此外,屏幕还应该能够调用后台侦听器在这些事件的回调中发送回消息(捕获的摄像机图像、系统生成的消息--“我暂停/销毁”消息等等)。主要问题是这都是异步的。
如果没有紧耦合,这是可能的吗?这有可能吗?
我已经想到了Asynctask/处理程序(但这是通知UI线程的单向方式),观察者模式(这两个对象都是观察者/可观察的?)但不知从何说起。任何想法,链接都会很有帮助。
发布于 2011-05-26 17:22:38
在本机代码中,可以使用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()) { ... }发布于 2011-05-26 17:21:23
使用阻塞队列如何,因为您的描述让我想起了并行编程类中典型的生产者-消费者问题。
http://en.wikipedia.org/wiki/Producer-consumer_problem
而且Java1.5似乎有一个阻塞队列的实现,如果它在Android上可用的话,我就记不起来了。
http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html
我想你可以设置两个单向阻塞队列来进行通信。Q1将有前端作为生产者,后端作为消费者。Q2将有前端作为消费者,后端作为生产者。
此外,您也可以使用“命令”设计模式的通信‘消息’。
http://en.wikipedia.org/wiki/Command_pattern
HTH
https://stackoverflow.com/questions/6142351
复制相似问题