在下图中,我有3个模块(作为android库),它扩展了基本的“公共组件模块”,所有这3个模块都将添加到一个android应用程序中。所有三个模块都是独立的模块,但当它作为一个应用程序时,它将需要共享一些数据,启动其他模块,并需要更多的相互通信。
那么,谁能让我知道我们如何在这种架构中实现“数据共享层”和“导航控制器”呢?
例如: Module1 -> Login、Module2 -> Profile Management等,可以根据应用程序的需要有"n“个模块的数量。

发布于 2016-03-09 18:52:52
您所要寻找的基本上是一种清晰的方法,用于如何与其他类通信。它们是否在不同的模块中并没有真正的区别。
下面的示例描述了LoginActivity如何导航到某些配置文件活动。这只是一个基本的例子,以改善你实际需要和打算做的事情!
编写所需的接口。您的登录应该能够打开配置文件页吗?这听起来像是需要一个LoginNavigator!
interface LoginNavigator {
void showProfile();
}将这些接口包括在共享组件中。没有定义接口是不可能的。您可以使它们更抽象或更细粒度,这完全取决于您。
还记得您的登录需要一个LoginNavigator吗?真正的问题是如何把它提供给你的班级。您应该看看依赖注入,因为有一些框架(比如匕首-2 )可以使这更容易。现在,我们为公共组件定义一个接口,以便检索所需的依赖项。
interface NavigatorProvider {
LoginNavigator provideNavigator();
}您可能会猜到--这个方法用于获取实际的LoginNavigator,您可以使用它来获得接口的实现。通常,您只需在构造函数中声明这个依赖项,但是由于android有点特殊,所以您需要自己从某个地方获得它。
最简单的方法是让应用程序实现这个接口(或者持有一个这样做的对象)。
class MyApp extends Application implements NavigatorProvider {
LoginNavigator provideNavigator() {
return new LoginNavigator() {
void showProfile() {
// just some sample code. You should probably not use an
// anonymous class
startActivity(new Intent(this, MyProfileActivity.class));
}
};
}
}同样,还可以返回实现此接口的对象。这只是一个基本的样本。
现在,依赖项注入已经接近完成。我们有一个我们需要的接口,我们有某种方法来提供依赖,剩下的就是获取并使用它。
class LoginActivity extends Activity {
LoginNavigator mNavigator;
void onCreate() {
// get the dependency
mNavigator = ((NavigatorProvider) getApplicationContext()).provideNavigator();
// use it where needed. (again, just sample code)
findShowProfileView().setOnClickListener(new OnClickListener() {
void onClick(View view) {
mNavigator.showProfile();
}
});
}
}现在提供了依赖项,并准备使用它。
这个示例展示的是如何基本上使用接口来分离逻辑。您仍然需要一些入口点,因为android不允许实现您自己的构造函数--这就是使用应用程序类的原因。
发布于 2021-09-02 10:01:15
我发现该解决方案使用Local Broadcast,在Application Class中实现,在Local Broadcast上发送事件,在Application Class中接收。
class AppApplication : Application() {
override fun onCreate() {
super.onCreate()
registerBroadcast()
}
private fun startProfileActivity() {
val intent = newIntent<MyProfileActivity>(this)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
this.startActivity(intent)
}
private fun registerBroadcast() {
LocalBroadcastManager.getInstance(this)
.registerReceiver(broadCastReceiver,IntentFilter(BROADCAST_VIEW_PROFILE))
}
private fun unregisterBroadcast() {
LocalBroadcastManager.getInstance(this)
.unregisterReceiver(broadCastReceiver)
}
private val broadCastReceiver = object : BroadcastReceiver() {
override fun onReceive(contxt: Context?, intent: Intent?) {
when (intent?.action) {
BROADCAST_VIEW_PROFILE -> {
startProfileActivity()
}
}
}
}
override fun onTerminate() {
super.onTerminate()
unregisterBroadcast()
}
} 当您在像下面这样的应用程序中发送事件时,
private fun viewProfileEventSend() {
// Send Broadcast for view profile to `APP`
val intent = Intent(BROADCAST_VIEW_PROFILE)
LocalBroadcastManager.getInstance(requireContext()).sendBroadcast(intent)
}因为您的模块不需要获取Application实例或任何接口。
https://stackoverflow.com/questions/35723666
复制相似问题