How to start a non existent Activity mentioned in Manifest?

前端 未结 2 1237
长情又很酷
长情又很酷 2021-01-17 22:55

I am attempting to develop a \"Dynamic\" Android application.

Dynamic in the sense that I have an activity listed in the manifest that is \"built\" at runtime.

2条回答
  •  旧时难觅i
    2021-01-17 23:23

    I have managed to call a dynamically instantiated Activity and set the required layout content using ByteBuddy.

    Heres how

    final DynamicType.Unloaded dynamicType = new ByteBuddy(ClassFileVersion.JAVA_V8)
            .subclass(AppCompatActivity.class)
            .name(CLASS_NAME)
            .method(named("onCreate").and(takesArguments(1)))
            .intercept(MethodDelegation.to(TargetActivity.class).andThen(SuperMethodCall.INSTANCE))
            .make();
    
    final Class dynamicTypeClass = dynamicType.load(getClassLoader(), new AndroidClassLoadingStrategy.Injecting(this.getDir("dexgen", Context.MODE_PRIVATE))).getLoaded();
    
    final Intent intent = new Intent(this, dynamicTypeClass);
    startActivity(intent);
    

    The method delegation class

    public class TargetActivity {
    
        public static void intercept(Bundle savedInstanceState, @This AppCompatActivity thiz) {
            thiz.setContentView(R.layout.activity_fourth);
        }
    }
    

    Even though this gives the desired result it still has issues as the super.onCreate(savedInstanceState) call is made after I have called setContent (I think).

    Using the excellent ByteBuddy library is a much better approach IMHO than working with DEX manipulation.

提交回复
热议问题