为了简化部分监控能力的接入,实现无侵入式接入,默认可以通过Apm Plugin插桩的方式进行启动、网络监控的初始化代码插入。
在插桩插件和宿主环境冲突导致编译失败的场景下,也可以优先通过非插桩方式尝试接入这部分监控能力。
注释如下代码:
apply plugin: 'apm-plugin' ApmPlugin { } classpath "com.volcengine:apm_insight_plugin:1.4.1"
通过调用OkHttp3Instrumentation.build()
方法生成OkHttpClient实例,即可自动监控Okhttp的网络请求。
OkHttpClient.Builder builder = new OkHttpClient.Builder(); //调用OkHttp3Instrumentation方法生成OkHttpClient即可自动监控Okhttp的网络请求。 OkHttpClient okHttpClient = OkHttp3Instrumentation.build(builder);
初始化设置debug模式,过滤ApmInsight可以看到Receive:NetData
即非插桩模式获取网络监控数据成功。
2021-09-17 21:18:20.031 8698-9358/com.example.apm.insight.demo D/ApmInsight: Receive:NetData
在的Application里配置启动监控的代码:
public class App extends Application { public App(){ super(); //打开页面监控开关 InstructOperationSwitch.sPageLoadSwitch=true; //监控App构造函数 AppAgent.onTrace(AppAgent.CONSTRUCT,true); AppAgent.onTrace(AppAgent.CONSTRUCT,false); } @Override protected void attachBaseContext(Context base) { //监控启动attachBaseContext()方法 AppAgent.onTrace(AppAgent.ATTACH_BASE_CONTEXT,true); super.attachBaseContext(base); AppAgent.onTrace(AppAgent.ATTACH_BASE_CONTEXT,false); } @Override public void onCreate() { //监控启动onCreate()方法 AppAgent.onTrace(AppAgent.ON_CREATE,true); super.onCreate(); //这里可以初始化业务其他代码 AppAgent.onTrace(AppAgent.ON_CREATE,false); } }
如果找不到常量AppAgent.CONSTRUCT
可以配置:
public static final String CONSTRUCT = "<init>"; public static final String ATTACH_BASE_CONTEXT = "attachBaseContext"; public static final String ON_CREATE = "onCreate";
用Application初始化时注册监听添加如下代码:
注意下面的registerActivityLifecycleCallbacks只注册一次。
app.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() { @Override public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) { ActivityAgent.onTrace(activity.getLocalClassName(), "onCreate", true); ActivityAgent.onTrace(activity.getLocalClassName(), "onCreate", false); } @Override public void onActivityStarted(@NonNull Activity activity) { ActivityAgent.onTrace(activity.getLocalClassName(), "onStart", true); ActivityAgent.onTrace(activity.getLocalClassName(), "onStart", false); } @Override public void onActivityResumed(@NonNull Activity activity) { ActivityAgent.onTrace(activity.getLocalClassName(), "onResume", true); ActivityAgent.onTrace(activity.getLocalClassName(), "onResume", false); ActivityAgent.onTrace(activity.getLocalClassName(), "onWindowFocusChanged", true); } @Override public void onActivityPaused(@NonNull Activity activity) { } @Override public void onActivityStopped(@NonNull Activity activity) { } @Override public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) { } @Override public void onActivityDestroyed(@NonNull Activity activity) { } });
初始化设置debug模式,过滤ApmInsight可以看到Receive:StartData
即非插桩模式获取启动数据成功。
2021-09-17 21:15:07.351 8698-8781/com.example.apm.insight.demo D/ApmInsight: Receive:StartData 2021-09-17 21:15:08.714 8698-8781/com.example.apm.insight.demo D/ApmInsight: Receive:PageData