android - 获取当前 android.intent.category.LAUNCHER Activity 的实例

标签 android android-intent android-manifest

我创建了一个库项目,我将在多个应用程序之间共享该项目。我实现了一个简单的 session 过期功能,它将在一段时间后将用户踢回登录屏幕。

登录屏幕 Activity 是我的主要 Activity ,因此在 list 中它看起来像这样:

<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>

当 session 过期时,我想将用户踢回到登录屏幕,但我不想硬编码 Activity 的名称,因为它可能会有所不同,具体取决于使用该库的特定应用程序。这是我之前所做的:

Intent intent = new Intent(context, LoginScreenActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);

如果应用的主要 Activity 与 LoginScreenActivity 不同,这将不起作用。我不想硬编码“LoginScreenActivity.class”,我想以编程方式确定主类的名称,然后将用户定向到该 Activity ...有人可以帮我吗?

提前致谢!

编辑

我找到了一种方法来实现相同的最终结果,但绝对不是很好。由于我需要一定数量的配置才能使用相同的库(字符串、 bool 等)部署新应用程序,因此我在 strings.xml 文件中为定义“主” Activity 名称的特定应用程序添加了一个字符串对于那个应用程序:

<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 的情况下实现相同的目标,我将不胜感激。

最佳答案

您可以从 PackageManager 请求一个launch Intent,使用:

Intent launchIntent = PackageManager.getLaunchIntentForPackage(context.getPackageName());

这将返回一个 Intent,您可以使用它来启动“主要” Activity (我假设这是您的“登录” Activity )。只需向其中添加 Intent.FLAG_ACTIVITY_CLEAR_TOP,您就可以开始了。

关于android - 获取当前 android.intent.category.LAUNCHER Activity 的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14129274/

相关文章:

java - 如何使用 Intent() 无参数构造函数

android - 使用PhoneGap Media startRecord录制音频时如何使用SD卡?

java - 使用 Endless 适配器的 ListView

java - 发送日期参数到另一个Activity但值为零//android studio

android - 在 android 上使用 com.android.camera.action.CROP 裁剪保存的图像

android - 如何通过 Intent 打开画廊而没有结果?

android - AlarmManager 在 sleep 模式下不工作

java - 未解析的类 : Validates resource reference inside Android XML files

android - Android Manifest 中如何声明 Intent 服务?

android - "android.permission.MOUNT_UNMOUNT_FILESYSTEMS"权限问题