├── .gitignore
├── .idea
├── compiler.xml
├── copyright
│ └── profiles_settings.xml
├── gradle.xml
├── misc.xml
├── modules.xml
└── runConfigurations.xml
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── seek
│ │ └── test
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── seek
│ │ │ └── test
│ │ │ ├── App.java
│ │ │ └── MainActivity.java
│ └── res
│ │ ├── layout
│ │ └── activity_main.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ └── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── seek
│ └── test
│ └── ExampleUnitTest.java
├── build.gradle
├── caton_design.png
├── caton_log.png
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── library
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── seek
│ │ └── caton
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── seek
│ │ │ └── caton
│ │ │ ├── BlockHandler.java
│ │ │ ├── Caton.java
│ │ │ ├── Collector.java
│ │ │ ├── Config.java
│ │ │ ├── FPSFrameCallBack.java
│ │ │ ├── StackTraceCollector.java
│ │ │ └── UILooperObserver.java
│ └── res
│ │ └── values
│ │ └── strings.xml
│ └── test
│ └── java
│ └── com
│ └── seek
│ └── caton
│ └── ExampleUnitTest.java
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 | .externalNativeBuild
10 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
18 |
19 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 | 1.8
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://jitpack.io/#pruas/Caton)
2 | # Caton
3 | Caton是一个android卡顿监测模块。当UI线程卡顿(得不到执行、无反应)达到预定阈值时,将把卡顿期间线程堆栈打印出来,以便开发人员分析和优化App的性能。
4 | Caton由于本身有个收集线程堆栈的后台线程工作,所以会带来一定的性能消耗,这个大概在百分之2%-3%左右。设置收集堆栈时间越小,消耗越大。触发卡顿时间范围是500ms\~4000ms,默认为3000ms;收集时间间隔范围为500ms\~2000ms,默认为1000ms。注意:自定义时,不要把收集时间间隔设置大于触发卡顿时间间隔。
5 | # Usage
6 | Add it to your build.gradle with:
7 | ```gradle
8 | allprojects {
9 | repositories {
10 | maven { url "https://jitpack.io" }
11 | }
12 | }
13 | ```
14 | and:
15 |
16 | ```gradle
17 | dependencies {
18 | compile 'com.github.pruas:Caton:v1.0.1'
19 | }
20 | ```
21 | 默认情况下,你在Application的onCreate方法中这样写就可以。
22 | ```java
23 | Caton.initialize(this);//default
24 | ```
25 |
26 | 你也可以使用Builder来自定义
27 |
28 | ```java
29 | // use builder build your custom way
30 | Caton.Builder builder = new Caton.Builder(this)
31 | .monitorMode(Caton.MonitorMode.FRAME)//默认监测模式为Caton.MonitorMode.LOOPER,这样指定Caton.MonitorMode.FRAME
32 | .loggingEnabled(true)// 是否打印log
33 | .collectInterval(1000) //监测采集堆栈时间间隔
34 | .thresholdTime(2000) // 触发卡顿时间阈值
35 | .callback(new Caton.Callback() { //设置触发卡顿时回调
36 | @Override
37 | public void onBlockOccurs(String[] stackTraces, String anr, long... blockArgs) {
38 | // stackTraces : 收集到的堆栈,以便分析卡顿原因。 anr : 如果应用发生ANR,这个就我ANR相关信息,没发生ANR,则为空。
39 | //采用Caton.MonitorMode.FRAME模式监测时,blockArgs的size为1,blockArgs[0] 即是发生掉帧的数。
40 | //采用Caton.MonitorMode.LOOPER模式监测时,blockArgs的size为2,blockArgs[0] 为UI线程卡顿时间值,blockArgs[1]为在此期间UI线程能执行到的时间。
41 | //这里你可以把卡顿信息上传到自己服务器
42 | }
43 | });
44 | Caton.initialize(builder);
45 | ```
46 |
47 | 1、监测模式
48 |
49 | 监测模式有两种:
50 |
51 |
Caton.MonitorMode.FRAME
52 | 这种模式是通过监测绘制帧间隔时间来判断是否卡顿。也就是给Choreographer设置FrameCallback的方式。这种方式只能在API 16上才能使用,否则默认使用LOOPER模式。
53 |
54 | Caton.MonitorMode.LOOPER
55 | 这种模式是通过监测主线程消息处理时间来判断。也就是给主线程Looper设置Printer,来计算消息处理开始前和处理后的时间间隔判断。
56 |
57 | 2、结构原理图
58 |
59 | 
60 |
61 | 3、测试。
62 |
63 | 我们人为在MainActivity中制造卡顿:
64 | ```java
65 | public void pause(View view){
66 | try {
67 | Thread.sleep(3000);
68 | } catch (InterruptedException e) {
69 | e.printStackTrace();
70 | }
71 | }
72 | ```
73 | logcat将打印出如下图:
74 |
75 | 
76 |
77 |
78 | 4、好了,是时候去测试一把了!
79 |
80 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 25
5 | buildToolsVersion "25.0.2"
6 | defaultConfig {
7 | applicationId "com.seek.test"
8 | minSdkVersion 15
9 | targetSdkVersion 25
10 | versionCode 1
11 | versionName "1.0"
12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(include: ['*.jar'], dir: 'libs')
24 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
25 | exclude group: 'com.android.support', module: 'support-annotations'
26 | })
27 | compile 'com.android.support:appcompat-v7:25.3.1'
28 | compile 'com.android.support.constraint:constraint-layout:1.0.2'
29 | testCompile 'junit:junit:4.12'
30 | compile project(':library')
31 | }
32 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/seek/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/seek/test/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.seek.test;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.seek.test", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/app/src/main/java/com/seek/test/App.java:
--------------------------------------------------------------------------------
1 | package com.seek.test;
2 |
3 | import android.app.Application;
4 |
5 | import com.seek.caton.Caton;
6 |
7 | /**
8 | * Created by seek on 2017/6/21.
9 | */
10 |
11 | public class App extends Application {
12 | @Override
13 | public void onCreate() {
14 | super.onCreate();
15 | // Caton.initialize(this);//default
16 | // Caton.setLoggingEnabled(false);//close log
17 | // use builder build your custom way
18 | Caton.Builder builder = new Caton.Builder(this)
19 | .monitorMode(Caton.MonitorMode.FRAME)//默认监测模式为Caton.MonitorMode.LOOPER,这样指定Caton.MonitorMode.FRAME
20 | .loggingEnabled(true)// 是否打印log
21 | .collectInterval(1000) //监测采集堆栈时间间隔
22 | .thresholdTime(2000) // 触发卡顿时间阈值
23 | .callback(new Caton.Callback() { //设置触发卡顿时回调
24 | @Override
25 | public void onBlockOccurs(String[] stackTraces, String anr, long... blockArgs) {
26 | // stackTraces : 收集到的堆栈,以便分析卡顿原因。 anr : 如果应用发生ANR,这个就我ANR相关信息,没发生ANR,则为空。
27 | //采用Caton.MonitorMode.FRAME模式监测时,blockArgs的size为1,blockArgs[0] 即是发生掉帧的数。
28 | //采用Caton.MonitorMode.LOOPER模式监测时,blockArgs的size为2,blockArgs[0] 为UI线程卡顿时间值,blockArgs[1]为在此期间UI线程能执行到的时间。
29 | //这里你可以卡顿信息上传到自己服务器
30 | }
31 | });
32 | Caton.initialize(builder);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/app/src/main/java/com/seek/test/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.seek.test;
2 |
3 | import android.support.v7.app.AppCompatActivity;
4 | import android.os.Bundle;
5 | import android.view.View;
6 |
7 | public class MainActivity extends AppCompatActivity {
8 |
9 | @Override
10 | protected void onCreate(Bundle savedInstanceState) {
11 | super.onCreate(savedInstanceState);
12 | setContentView(R.layout.activity_main);
13 | }
14 |
15 | public void pause(View view){
16 | try {
17 | Thread.sleep(3000);
18 | } catch (InterruptedException e) {
19 | e.printStackTrace();
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gru110110110/Caton/0c777772dbd7e6ade090593b51157b1980ea3ce2/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gru110110110/Caton/0c777772dbd7e6ade090593b51157b1980ea3ce2/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gru110110110/Caton/0c777772dbd7e6ade090593b51157b1980ea3ce2/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gru110110110/Caton/0c777772dbd7e6ade090593b51157b1980ea3ce2/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gru110110110/Caton/0c777772dbd7e6ade090593b51157b1980ea3ce2/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gru110110110/Caton/0c777772dbd7e6ade090593b51157b1980ea3ce2/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gru110110110/Caton/0c777772dbd7e6ade090593b51157b1980ea3ce2/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gru110110110/Caton/0c777772dbd7e6ade090593b51157b1980ea3ce2/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gru110110110/Caton/0c777772dbd7e6ade090593b51157b1980ea3ce2/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gru110110110/Caton/0c777772dbd7e6ade090593b51157b1980ea3ce2/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Caton
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/com/seek/test/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.seek.test;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.3.2'
9 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
10 | // NOTE: Do not place your application dependencies here; they belong
11 | // in the individual module build.gradle files
12 | }
13 | }
14 |
15 | allprojects {
16 | repositories {
17 | jcenter()
18 | }
19 | }
20 |
21 | task clean(type: Delete) {
22 | delete rootProject.buildDir
23 | }
24 |
--------------------------------------------------------------------------------
/caton_design.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gru110110110/Caton/0c777772dbd7e6ade090593b51157b1980ea3ce2/caton_design.png
--------------------------------------------------------------------------------
/caton_log.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gru110110110/Caton/0c777772dbd7e6ade090593b51157b1980ea3ce2/caton_log.png
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Gru110110110/Caton/0c777772dbd7e6ade090593b51157b1980ea3ce2/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Jun 21 11:43:48 CST 2017
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/library/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/library/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.github.dcendents.android-maven'
3 |
4 | group='com.github.pruas'
5 |
6 | android {
7 | compileSdkVersion 25
8 | buildToolsVersion "25.0.2"
9 |
10 | defaultConfig {
11 | minSdkVersion 15
12 | targetSdkVersion 25
13 | versionCode 1
14 | versionName "1.0.1"
15 |
16 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
17 |
18 | }
19 | buildTypes {
20 | release {
21 | minifyEnabled false
22 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
23 | }
24 | }
25 | }
26 |
27 | dependencies {
28 | compile fileTree(dir: 'libs', include: ['*.jar'])
29 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
30 | exclude group: 'com.android.support', module: 'support-annotations'
31 | })
32 | compile 'com.android.support:appcompat-v7:25.3.1'
33 | testCompile 'junit:junit:4.12'
34 | }
35 |
--------------------------------------------------------------------------------
/library/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/seek/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/library/src/androidTest/java/com/seek/caton/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.seek.caton;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.seek.caton.test", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
5 |
6 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/library/src/main/java/com/seek/caton/BlockHandler.java:
--------------------------------------------------------------------------------
1 | package com.seek.caton;
2 |
3 | import android.app.ActivityManager;
4 | import android.content.Context;
5 |
6 | import java.util.List;
7 |
8 | import static com.seek.caton.Config.log;
9 |
10 | /**
11 | * Created by seek on 2017/6/20.
12 | */
13 |
14 | public class BlockHandler {
15 |
16 | private static final String TAG = "BlockHandler";
17 | private Context mContext;
18 | private Collector mCollector;
19 | private Caton.Callback mCallback;
20 |
21 | public BlockHandler(Context context, Collector collector, Caton.Callback callback) {
22 | mContext = context;
23 | mCollector = collector;
24 | mCallback = callback;
25 | }
26 |
27 | public void notifyBlockOccurs(boolean needCheckAnr, long... blockArgs) {
28 | String[] stackTraces = mCollector.getStackTraceInfo();
29 | printStackTrace(stackTraces);
30 | String anr = "";
31 | if (needCheckAnr) {
32 | anr = checkAnr();
33 | }
34 | if (mCallback != null) {
35 | mCallback.onBlockOccurs(stackTraces, anr, blockArgs);
36 | }
37 | }
38 |
39 | private String checkAnr() {
40 | ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
41 | List errorStateInfos = activityManager.getProcessesInErrorState();
42 | if (errorStateInfos != null) {
43 | for (ActivityManager.ProcessErrorStateInfo info : errorStateInfos) {
44 | if (info.condition == ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING) {
45 | StringBuilder anrInfo = new StringBuilder();
46 | anrInfo.append(info.processName)
47 | .append("\n")
48 | .append(info.shortMsg)
49 | .append("\n")
50 | .append(info.longMsg);
51 | log(TAG, anrInfo.toString());
52 | return anrInfo.toString();
53 | }
54 | }
55 | }
56 | return "";
57 | }
58 |
59 | private void printStackTrace(String[] stackTraces) {
60 | for (String item : stackTraces) {
61 | log(TAG, item);
62 | }
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/library/src/main/java/com/seek/caton/Caton.java:
--------------------------------------------------------------------------------
1 | package com.seek.caton;
2 |
3 | import android.content.Context;
4 | import android.os.Build;
5 | import android.view.Choreographer;
6 |
7 | /**
8 | * Created by seek on 2017/6/19.
9 | */
10 |
11 | public class Caton {
12 | private static Caton sCaton;
13 | final static long DEFAULT_THRESHOLD_TIME = 3000;
14 | final static long DEFAULT_COLLECT_INTERVAL = 1000;
15 | final static long MIN_THRESHOLD_TIME = 500;
16 | final static long MIN_COLLECT_INTERVAL = 500;
17 | final static long MAX_THRESHOLD_TIME = 4000;
18 | final static long MAX_COLLECT_INTERVAL = 2000;
19 | static MonitorMode DEFAULT_MODE = MonitorMode.LOOPER;
20 |
21 | private Caton(Context context, long thresholdTimeMillis, long collectIntervalMillis, MonitorMode mode, boolean loggingEnabled, Callback callback) {
22 | long thresholdTime = Math.min(Math.max(thresholdTimeMillis, MIN_THRESHOLD_TIME), MAX_THRESHOLD_TIME);
23 | long collectInterval = Math.min(Math.max(collectIntervalMillis, MIN_COLLECT_INTERVAL), MAX_COLLECT_INTERVAL);
24 | Config.LOG_ENABLED = loggingEnabled;
25 | Config.THRESHOLD_TIME = thresholdTime;
26 | Collector mTraceCollector = new StackTraceCollector(collectInterval);
27 | BlockHandler mBlockHandler = new BlockHandler(context, mTraceCollector, callback);
28 | if (mode == MonitorMode.LOOPER) {
29 | new UILooperObserver(mBlockHandler);
30 | } else if (mode == MonitorMode.FRAME) {
31 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
32 | FPSFrameCallBack fpsFrameCallBack = new FPSFrameCallBack(context, mBlockHandler);
33 | Choreographer.getInstance().postFrameCallback(fpsFrameCallBack);
34 | } else {
35 | new UILooperObserver(mBlockHandler);
36 | }
37 | }
38 | }
39 |
40 | public static void initialize(Context context) {
41 | initialize(new Builder(context));
42 | }
43 |
44 | public static void initialize(Builder builder) {
45 | if (sCaton == null) {
46 | synchronized (Caton.class) {
47 | if (sCaton == null) {
48 | sCaton = builder.build();
49 | }
50 | }
51 | }
52 | }
53 |
54 | public static void setLoggingEnabled(boolean enabled) {
55 | Config.LOG_ENABLED = enabled;
56 | }
57 |
58 |
59 | public static class Builder {
60 | private long mThresholdTime = DEFAULT_THRESHOLD_TIME;
61 | private long mCollectInterval = DEFAULT_COLLECT_INTERVAL;
62 | private Context mContext;
63 | private MonitorMode mMonitorMode = DEFAULT_MODE;
64 | private boolean loggingEnabled = true;
65 | private Callback mCallback;
66 |
67 | public Builder(Context context) {
68 | mContext = context;
69 | }
70 |
71 | public Builder thresholdTime(long thresholdTimeMillis) {
72 | mThresholdTime = thresholdTimeMillis;
73 | return this;
74 | }
75 |
76 | public Builder collectInterval(long collectIntervalMillis) {
77 | mCollectInterval = collectIntervalMillis;
78 | return this;
79 | }
80 |
81 | public Builder monitorMode(MonitorMode mode) {
82 | this.mMonitorMode = mode;
83 | return this;
84 | }
85 |
86 | public Builder loggingEnabled(boolean enable) {
87 | loggingEnabled = enable;
88 | return this;
89 | }
90 |
91 | public Builder callback(Callback callback) {
92 | mCallback = callback;
93 | return this;
94 | }
95 |
96 | Caton build() {
97 | return new Caton(mContext, mThresholdTime, mCollectInterval, mMonitorMode, loggingEnabled, mCallback);
98 | }
99 | }
100 |
101 | public enum MonitorMode {
102 | LOOPER(0), FRAME(1);
103 | int value;
104 |
105 | MonitorMode(int mode) {
106 | this.value = mode;
107 | }
108 | }
109 |
110 | public interface Callback {
111 | void onBlockOccurs(String[] stackTraces, String anr, long... blockArgs);
112 | }
113 | }
114 |
--------------------------------------------------------------------------------
/library/src/main/java/com/seek/caton/Collector.java:
--------------------------------------------------------------------------------
1 | package com.seek.caton;
2 |
3 | /**
4 | * Created by seek on 2017/6/19.
5 | */
6 |
7 | public interface Collector {
8 |
9 | String[] getStackTraceInfo();
10 |
11 | void add(String stackTrace);
12 | }
13 |
--------------------------------------------------------------------------------
/library/src/main/java/com/seek/caton/Config.java:
--------------------------------------------------------------------------------
1 | package com.seek.caton;
2 |
3 | import android.util.Log;
4 |
5 | /**
6 | * Created by seek on 2017/6/20.
7 | */
8 |
9 | public class Config {
10 | public static long THRESHOLD_TIME = 0;
11 | public static boolean LOG_ENABLED = true;
12 |
13 | public static void log(String tag, String msg) {
14 | if (LOG_ENABLED) {
15 | Log.e(tag, msg);
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/library/src/main/java/com/seek/caton/FPSFrameCallBack.java:
--------------------------------------------------------------------------------
1 | package com.seek.caton;
2 |
3 | import android.content.Context;
4 | import android.os.Build;
5 | import android.support.annotation.RequiresApi;
6 | import android.view.Choreographer;
7 | import android.view.Display;
8 | import android.view.WindowManager;
9 |
10 | import static com.seek.caton.Config.log;
11 |
12 | /**
13 | * Created by seek on 2017/6/20.
14 | */
15 |
16 | @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
17 | public class FPSFrameCallBack implements Choreographer.FrameCallback {
18 | private static final String TAG = "FPSFrameCallBack";
19 | private static long SKIPPED_FRAME_ANR_TRIGGER = 0;
20 | private static long SKIPPED_FRAME_WARNING_LIMIT = 0;
21 | private long mLastFrameTimeNanos;
22 | private long mFrameIntervalNanos;
23 | private BlockHandler mBlockHandler;
24 |
25 | public FPSFrameCallBack(Context context, BlockHandler blockHandler) {
26 | float mRefreshRate = getRefreshRate(context);
27 | mFrameIntervalNanos = (long) (1000000000l / mRefreshRate);
28 | SKIPPED_FRAME_WARNING_LIMIT = Config.THRESHOLD_TIME * 1000l * 1000l / mFrameIntervalNanos;
29 | SKIPPED_FRAME_ANR_TRIGGER = 5000000000l / mFrameIntervalNanos;
30 | log(TAG, "SKIPPED_FRAME_WARNING_LIMIT : " + SKIPPED_FRAME_WARNING_LIMIT + " ,SKIPPED_FRAME_ANR_TRIGGER : " + SKIPPED_FRAME_ANR_TRIGGER);
31 | mBlockHandler = blockHandler;
32 | }
33 |
34 | private float getRefreshRate(Context context) {
35 | Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
36 | return display.getRefreshRate();
37 | }
38 |
39 | @Override
40 | public void doFrame(long frameTimeNanos) {
41 | if (mLastFrameTimeNanos == 0) {
42 | mLastFrameTimeNanos = frameTimeNanos;
43 | Choreographer.getInstance().postFrameCallback(this);
44 | return;
45 | }
46 | final long jitterNanos = frameTimeNanos - mLastFrameTimeNanos;
47 | if (jitterNanos >= mFrameIntervalNanos) {
48 | final long skippedFrames = jitterNanos / mFrameIntervalNanos;
49 | if (skippedFrames >= SKIPPED_FRAME_WARNING_LIMIT) {
50 | log(TAG, "Skipped " + skippedFrames + " frames! "
51 | + "The application may be doing too much work on its main thread.");
52 | mBlockHandler.notifyBlockOccurs(skippedFrames >= SKIPPED_FRAME_ANR_TRIGGER, skippedFrames);
53 | }
54 | }
55 | mLastFrameTimeNanos = frameTimeNanos;
56 | Choreographer.getInstance().postFrameCallback(this);
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/library/src/main/java/com/seek/caton/StackTraceCollector.java:
--------------------------------------------------------------------------------
1 | package com.seek.caton;
2 |
3 | import android.os.Handler;
4 | import android.os.HandlerThread;
5 | import android.os.Looper;
6 | import android.os.Message;
7 | import android.os.Process;
8 |
9 | import java.util.ArrayDeque;
10 | import java.util.Map;
11 |
12 | /**
13 | * Created by seek on 2017/6/19.
14 | */
15 |
16 | public class StackTraceCollector implements Collector {
17 | private final static String TAG = "StackTraceCollector";
18 | private final static String THREAD_TAG = "------";
19 | private final static int COLLECT_MSG = 0x0037;
20 | private final static int COLLECT_SPACE_TIME = 5000;
21 | private final static int MIN_COLLECT_COUNT = 5;
22 | private long mCollectInterval;
23 | private volatile Looper mLooper;
24 | private volatile CollectorHandler mCollectorHandler;
25 | private ArrayDeque mStackQueue;
26 | private int mLimitLength;
27 |
28 | public StackTraceCollector(long collectInterval) {
29 | mCollectInterval = collectInterval;
30 | HandlerThread thread = new HandlerThread(TAG);
31 | thread.setPriority(Process.THREAD_PRIORITY_BACKGROUND);
32 | thread.start();
33 | mLooper = thread.getLooper();
34 | mCollectorHandler = new CollectorHandler(mLooper);
35 | int space = (int) (COLLECT_SPACE_TIME / mCollectInterval);
36 | mLimitLength = space <= MIN_COLLECT_COUNT ? MIN_COLLECT_COUNT : space;
37 | mStackQueue = new ArrayDeque<>(mLimitLength);
38 | trigger();
39 | }
40 |
41 | public void trigger() {
42 | Message message = mCollectorHandler.obtainMessage();
43 | message.obj = this;
44 | message.what = COLLECT_MSG;
45 | mCollectorHandler.sendMessageDelayed(message, mCollectInterval);
46 | }
47 |
48 | @Override
49 | public String[] getStackTraceInfo() {
50 | return mStackQueue.toArray(new String[0]);
51 | }
52 |
53 | @Override
54 | public void add(String stackTrace) {
55 | if (mStackQueue.size() >= mLimitLength) {
56 | mStackQueue.poll();
57 | }
58 | mStackQueue.offer(stackTrace);
59 | }
60 |
61 |
62 | private static class CollectorHandler extends Handler {
63 |
64 | public CollectorHandler(Looper looper) {
65 | super(looper);
66 | }
67 |
68 | @Override
69 | public void handleMessage(Message msg) {
70 | if (msg.what == COLLECT_MSG) {
71 | StackTraceCollector traceCollector = (StackTraceCollector) msg.obj;
72 | traceCollector.add(traceCollector.getAllStackInfo());
73 | traceCollector.trigger();
74 | }
75 | }
76 | }
77 |
78 | private String getAllStackInfo() {
79 | Thread main = Looper.getMainLooper().getThread();
80 | Map allLiveThreadStackMap = main.getAllStackTraces();
81 | StringBuilder stackBuilder = new StringBuilder(128);
82 | for (Thread item : allLiveThreadStackMap.keySet()) {
83 | StackTraceElement[] stackTraceElements = item.getStackTrace();
84 | if (stackTraceElements != null && stackTraceElements.length > 0) {
85 | stackBuilder.append(THREAD_TAG).append(item.getName()).append("\n");
86 | for (StackTraceElement stackTraceElement : stackTraceElements) {
87 | stackBuilder.append("\tat ").append(stackTraceElement.toString()).append("\n");
88 | }
89 | }
90 | }
91 | return stackBuilder.toString();
92 | }
93 |
94 | }
95 |
--------------------------------------------------------------------------------
/library/src/main/java/com/seek/caton/UILooperObserver.java:
--------------------------------------------------------------------------------
1 | package com.seek.caton;
2 |
3 | import android.os.Looper;
4 | import android.os.SystemClock;
5 | import android.util.Printer;
6 |
7 | import static com.seek.caton.Config.log;
8 |
9 | /**
10 | * Created by seek on 2017/6/19.
11 | */
12 |
13 | public class UILooperObserver implements Printer {
14 | private final static String TAG = "UILooperObserver";
15 | private final static String LOG_BEGIN = ">>>>> Dispatching to";
16 | private final static String LOG_END = "<<<<< Finished to";
17 | public final static long ANR_TRIGGER_TIME = 5000l;
18 | private long mPreMessageTime = 0;
19 | private long mPreThreadTime = 0;
20 | private BlockHandler mBlockHandler;
21 |
22 | public UILooperObserver(BlockHandler blockHandler) {
23 | this.mBlockHandler = blockHandler;
24 | Looper.getMainLooper().setMessageLogging(this);
25 | }
26 |
27 | @Override
28 | public void println(String x) {
29 | if (x.startsWith(LOG_BEGIN)) {
30 | mPreMessageTime = SystemClock.elapsedRealtime();
31 | mPreThreadTime = SystemClock.currentThreadTimeMillis();
32 | } else if (x.startsWith(LOG_END)) {
33 | if (mPreMessageTime != 0) {
34 | long messageElapseTime = SystemClock.elapsedRealtime() - mPreMessageTime;
35 | long threadElapseTime = SystemClock.currentThreadTimeMillis() - mPreThreadTime;
36 | if (messageElapseTime > Config.THRESHOLD_TIME) {
37 | log(TAG, String.format("messageElapseTime : %s, threadElapseTime : %s", messageElapseTime, threadElapseTime));
38 | mBlockHandler.notifyBlockOccurs(messageElapseTime >= ANR_TRIGGER_TIME, messageElapseTime, threadElapseTime);
39 | }
40 | }
41 | }
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/library/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Caton
3 |
4 |
--------------------------------------------------------------------------------
/library/src/test/java/com/seek/caton/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.seek.caton;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':library'
2 |
--------------------------------------------------------------------------------