获取当前android.intent.category.LAUNCHER活动的实例

时间:2013-01-02 21:15:03

标签: android android-intent android-manifest

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

登录屏幕活动是我的主要活动,因此在清单中它看起来像这样:

<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”,我想以编程方式确定主类的名称,然后将用户引导到该活动......有人可以帮助我吗?

提前致谢!

修改

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

<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);
}

我知道这是一个可怕的解决方案,但它确实有效。就像我说的,无论如何我必须为每个新的应用程序做一些配置,所以添加一个字符串并不是一件很大的事情,它不是很优雅。我很感激任何可以在不使用我的黑客的情况下实现同一目标的建议。

2 个答案:

答案 0 :(得分:14)

您可以使用以下命令从PackageManager请求启动Intent

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

这将返回一个Intent,您可以使用它来启动“main”活动(我假设您的“登录”活动)。只需添加Intent.FLAG_ACTIVITY_CLEAR_TOP就可以了,你应该好好去。

答案 1 :(得分:0)

如何在意图过滤器上使用mime-type。

    <activity android:name=".LoginActivity"
              android:exported="true" android:launchMode="singleTop" android:label="@string/MT">
        <intent-filter>
            <category android:name="android.intent.category.DEFAULT"/>
            <action android:name="com.foo.ACTION_LOGIN" />
            <data android:mimeType="application/x.foo.com.mobile.login" /> 
     </intent-filter>
    </activity>

按以下方式启动活动:

Intent intent = new Intent();
intent.setAction("com.foo.ACTION_LOGIN");
intent.setType("application/x.foo.com.mobile.login");
startActivity(myIntent);

因此,意图将通过在此动作/ mime类型对中注册的任何活动来提供服务。我不确定,但我认为如果该活动托管在同一个应用程序中,则可以先选择它。

相关问题