我创建了一个库项目,它在多个应用程序之间共享。我实现了一个简单的会话过期功能,可以在一定时间后将用户踢回登录界面。
登录界面活动是我的主要活动,因此在清单中它看起来像这样:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.Sherlock.Light.DarkActionBar"
android:name="com.blah.application.MyApplication" >
<activity
android:name="com.blah.activity.LoginScreenActivity"
android:label="@string/title_activity_main"
android:screenOrientation="portrait"
android:configChanges="orientation|keyboardHidden"
android:windowSoftInputMode="adjustPan">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
当会话过期时,我希望将用户踢回登录屏幕,但我不想硬编码活动的名称,因为它可能因使用库的特定应用程序而异。以下是之前我的做法:
Intent intent = new Intent(context, LoginScreenActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
这种方法在应用的主活动不是LoginScreenActivity时无法正常工作。我不想硬编码“LoginScreenActivity.class”,而是想以编程方式确定主类的名称,然后将用户重定向到该活动...有人能帮帮我吗?
提前感谢!
编辑
我找到了一种实现相同结果的方法,但它绝对不是最好的。由于部署使用相同库的新应用程序需要一定的配置(字符串,布尔值等),因此我添加了一个字符串到特定应用程序的strings.xml文件中,为该应用程序定义了“main”活动名称:
<string name="mainClassName">com.blah.specificapp.activity.SpecificAppLoginScreenActivity</string>
然后,我可以通过名称获取该类的句柄,并将用户重定向到那里:
Class<?> clazz = null;
try
{
clazz = Class.forName(context.getString(R.string.mainClassName));
}
catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
if(clazz != null)
{
Intent intent = new Intent(context, clazz);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
}
我知道这个解决方案很糟糕,但它能够实现功能。就像我说的那样,每次添加新应用都需要进行一定量的配置,所以再添加一个字符串并不是很麻烦,只是不太优雅。如果有任何可以实现相同目标而不使用我的hack的建议,我将不胜感激。
class
一样糟糕... - K-ballo