Hiam
Hiam

Reputation: 303

Intercepting all Android Activity onCreate

Been trying to hook up android with byte-buddy but having issues with my goal; That goal being to intercept onCreate, and then to add a Log.d(TAG, "Message") to all Activities getting created.

Updated with imports

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();
    }
}

First issue is that the class Activity does not seem to be found.

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

Second issue is, am I even on the right track?

Upvotes: 0

Views: 550

Answers (1)

Rafael Winterhalter
Rafael Winterhalter

Reputation: 44042

Byte Buddy does not support redefinition or rebasement on Android. You can only do this during build time but the runtime for Android does not provide standardized access to Java byte code.

Upvotes: 2

Related Questions