0

一直在尝试将 android 与 byte-buddy 联系起来,但我的目标有问题;该目标是拦截 onCreate,然后将 Log.d(TAG, "Message") 添加到所有正在创建的活动中。

使用导入更新

package he.herpa.autoloader;

import android.app.Application;
import android.content.Context;
import android.util.Log;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.ClassFileVersion;
import net.bytebuddy.android.AndroidClassLoadingStrategy;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.bind.annotation.SuperCall;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.utility.RandomString;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.Callable;

public class App extends Application {

private static final String TAG = "TEST";
@Override
public void onCreate() {
    super.onCreate();

            ByteBuddy byteBuddy;
            byteBuddy = new ByteBuddy(ClassFileVersion.JAVA_V6);

            try {
                File file = this.getDir(RandomString.make(), Context.MODE_PRIVATE);
                if (!file.isDirectory()) {
                    throw new IOException("Not a directory: " + file);
                }
                try {

                    byteBuddy
                            .redefine(Activity.class)
                            .method(ElementMatchers.named("onCreate"))
                            .intercept(MethodDelegation.to(Interceptor.class))
                            .make()
                            .load(Activity.class.getClassLoader(), new AndroidClassLoadingStrategy(file));

                } catch (Throwable e) {
                    Log.w(TAG, e);
                    return;
                }
            } catch (Throwable e) {
                Log.w(TAG, e);
            }

}

@Override
public void onTerminate() {
    super.onTerminate();
}


public static class Interceptor {

    public static Void intercept(@SuperCall Callable<Void> zuper) throws Exception {
        Log.d("Test", "Should have placed a log in all onCreates");
        return zuper.call();
    }
}

第一个问题是似乎找不到类 Activity 。

编辑 java.lang.IllegalArgumentException: Cannot locate the class file for class he.herpa.autoloader.Activity using ClassFileLocator.ForClassLoader

第二个问题是,我是否走在正确的轨道上?

4

1 回答 1

2

Byte Buddy 不支持在 Android 上重新定义或变基。您只能在构建期间执行此操作,但 Android 运行时不提供对 Java 字节码的标准化访问。

于 2016-02-07T11:34:33.177 回答