ActivityNotFoundException when different package's targetClass in PreferenceScreen

左心房为你撑大大i 提交于 2019-11-27 23:35:00
ehartwell

I just ran into the same problem when trying to use a custom preference screen from a library project for the AccountManager account settings. No matter how I tried to tweak the targetPackage and targetClass attributes, it would throw an exception (except, since it's an account, it crashes the phone).

I think we'll just have to assume this is an Android limitation. It's clumsy, but all you really need to do is declare a wrapper class for the activity within your application's namespace:

public class MyPreferences extends ActualPreferences {
}

Declare it in your AndroidManifest.xml

<activity android:name=".MyPreferences"/>

Then you can specify the class in your intent

<intent android:targetPackage="com.my.package"
        android:targetClass="com.my.package.MyPreferences" />

By the way, the syntax is extremely fussy, at least for account preferences. All these variations fail:

<!-- fails --> <intent android:targetClass="com.my.package.MyPreferences" />
<!-- fails --> <intent android:targetClass="MyPreferences" 
                       android:targetPackage="com.my.package"/>
<!-- fails --> <intent android:targetClass=".MyPreferences"
                       android:targetPackage="com.my.package"/>
<!-- fails --> <intent android:targetClass="settings.MyPreferences"
                       android:targetPackage="com.my.package"/>
<!-- fails --> <intent android:targetClass=".settings.MyPreferences"
                       android:targetPackage="com.my.package"/>
<!-- fails --> <intent android:targetClass="com.my.other.package.MyPreferences"
                       android:targetPackage="com.my.package"/>

The critical factor is apparently that the android:targetPackage attribute matches the application package. If you want, you can put the activity in a sub-package. This works:

<intent android:targetPackage="com.my.package"
        android:targetClass="com.my.package.settings.MyPreferences" />

as already said its not working with libraries. Do it programatically, something like this:

preference_my_pref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                public boolean onPreferenceClick(Preference preference) {
                    Intent intent = new Intent(MyActivity.this, ActivityToStart.class);
                    startActivity(intent);
                    return true;
                }
            });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!