Cannot start new Intent by setClassName with different package in Android

前端 未结 9 1533
独厮守ぢ
独厮守ぢ 2020-12-06 11:30

I want to start a new Intent dynamically. Therefore setClassName seems the best choice.

First, I define 3 activity in Manifest



        
9条回答
  •  眼角桃花
    2020-12-06 11:55

    The most likely cause of the problem is that the given class name is not a class linked into pkg2. Here's snippet of code that I was using to start an intent in an AndroidInstumentationTest app.

        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setClassName("com.xxx.android.app",
                "com.xxx.android.app.MainActivity")
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mActivity = instrumentation.startActivitySync(intent);
    

    This code works perfectly fine running it from my app module which has the MainActivity class in it. It does not work if I try to use it in a module that doesn't have MainActivity class linked to it. From my read of the original problem statement, that seem likely what user "anticafe" says he was trying to do. My guess is that internally there is a call to "Class.forName(className, classLoader) where classLoader is the ClassLoader for the given package. And of course that'll fail since that package is not linked in.

    And yes, you do need to add the flag "FLAG_ACTIVITY_NEW_TASK", as others have suggested, at least for the situations where you do have the class linked in!

提交回复
热议问题