场景:
在app中,要能根据不同的客户加载不同的activity,具体哪个客户对应哪些activity配置在后台数据库中。
这样,不管有多少客户,只需要维护一个app版本就可以了。
实现思路:
1.既然是做xarmarin.android的开发,就想先借鉴下android的方法,网上查到了一些,大致是先创建一个基类activity,然后其它activiy从它派生,再在入口的地方创建各子类的实例,象我这种场景,就可以把各客户的activity做成子类activity,在运行时加载。这种方法对现有程序改动较大,未测试
2.发现在xarmarin中有Activitor这个类,想是否可以用c#中的方法呢?如下:
tempAssembly = Assembly.LoadFrom(startPath);
Type typeofControl = tempAssembly.GetType(typeName);
if (typeofControl != null)
{
Intent intent = new Intent(ApplicationContext, typeofControl );
.......
但测试时发现这种通过加载dll的方式有问题,不知是linux下的路径有什么不同,另外在实际运行时,dll不知还有没有?没太深究。
3.折衷的方式
做动态加载的目的,是设计框架时,避免因业务的增加而频繁地调整框架的结构。只要能基本达到这个目标,我认为就可以了。所以用了一种土办法:
设计一个类加载管理器:ClassManager,当增加了一个新的activity时,在它里面注册一下,然后加载时将activtity字符串传给它,返回对应的type就可以了。
public class ClassManager
{
private static Dictionary<string, Type> _dicClass;
private static Dictionary<string, Type> ClassDictoinary
{
get
{
if (_dicClass == null)
{
_dicClass = new Dictionary<string, Type>();
//入口类
_dicClass.Add("xxxxxxxx_Activity", typeof(xxxxxxxx_Activity));
_dicClass.Add("vvvvvvvv_Activity", typeof(vvvvvvvv_Activity));
..........
}
public static Type GetClassType(string className)
{
if (ClassDictoinary.ContainsKey(className))
return ClassDictoinary[className];
else
return null;
}
//动态加载activity
Type tpModuleClass= ClassManager.GetClassType(entryClass);
if (tpModuleClass != null)
{
btn.Click += (sender, e) =>
{
Intent intent = new Intent(ApplicationContext, tpModuleClass);
StartActivity(intent);
};
btn.Visibility = ViewStates.Visible;
}
else
{
ShowMessage(entryClass+"未注册");
}