<activity-alias>的意图因ActivityNotFoundException而失败

时间:2016-12-09 18:34:07

标签: android android-manifest android-activity-alias

我为活动写了一个活动别名:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.company.htmlapp">

    <application
        android:name=".AppController">

        <activity
            android:name=".main.MainActivity" />

       <activity-alias
           android:name=".main.MainActivityAlias"
           android:targetActivity=".main.MainActivity">
    </application>

</manifest>

关注this answer,我正在尝试启动该活动别名:

void goToMainActivity(String server) {
    Intent i;
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        i = new Intent();
        String activityPackage = MainActivity.class.getPackage().getName();
        ComponentName componentName = new ComponentName(activityPackage, ".MainActivityAlias");
        i.setComponent(componentName);
    } else {
        i = new Intent(this, MainActivity.class);
    }

    i.putExtra( ... );
    startActivity(i);
}

MainActivity.class.getPackage().getName()生成的名称为com. company.htmlapp.main

但它在使用ActivityNotFoundException:

的行startActivity(i)中失败了
android.content.ActivityNotFoundException: Unable to find explicit activity class 
   {com.company.htmlapp.main/.MainActivityAlias}; have you declared this 
   activity in your AndroidManifest.xml?

编辑:

尝试使用ComponentName(activityPackage,“。main.MainActivityAlias”);结果错误与不同的包相同:

android.content.ActivityNotFoundException: Unable to find 
    explicit activity class {com.company.htmlapp.main/.main.MainActivityAlias}; 
    have you declared this activity in your AndroidManifest.xml?

1 个答案:

答案 0 :(得分:0)

对于这样声明的<activity-alias>

<activity-alias
  android:name=".main.MainActivityAlias"
  android:targetActivity=".main.MainActivity">

可以像这样创建ComponentName

ComponentName componentName = new ComponentName("com.company.htmlapp", "com.company.htmlapp.main.MainActivityAlias");

在我的情况下,我也可以动态地做到这一点:

    try {
        PackageManager pm = getPackageManager();
        PackageInfo packageInfo = pm.getPackageInfo(this.getPackageName(), 0);

        ComponentName componentName = new ComponentName(packageInfo.packageName,
                MainActivity.class.getPackage().getName() + ".MainActivityAlias");
        i.setComponent(componentName);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }