6 |
--------------------------------------------------------------------------------
/blockcanary-sample/src/main/res/drawable/btn_select.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/blockcanary-sample/src/main/res/drawable/background_splash.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
6 |
7 |
8 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/blockcanary-sample/src/main/res/drawable/btn_nor.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
11 |
12 |
--------------------------------------------------------------------------------
/blockcanary-sample/src/main/res/drawable/btn_pre.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
11 |
12 |
--------------------------------------------------------------------------------
/blockcanary-analyzer/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/blockcanary-sample/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 | 0dp
7 | 48dp
8 | 48dp
9 | 0.5dp
10 |
11 |
--------------------------------------------------------------------------------
/blockcanary-android/src/main/res/layout/block_canary_ref_top_row.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
--------------------------------------------------------------------------------
/blockcanary-sample/src/main/res/values-zh/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | BlockCanary
3 |
4 | 点击按钮后,会触发主线程耗时时间,从而被BlockCanary,并记录卡慢日志,弹出notification,可以点击对应消息查看
5 | 线程\n等待\n阻塞
6 | IO\n阻塞
7 | 计算\n阻塞
8 | 尽请\n期待\n更多
9 | Settings
10 |
11 |
--------------------------------------------------------------------------------
/blockcanary-sample/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | BlockCanary
3 |
4 | After click button, main-thread consuming event will be triggered, which would be caught be BlockCanary, write to log file, and use notification to display
5 | Thread\nwait\nblock
6 | IO\nblock
7 | Computation\nblock
8 | Wait\nfor\nmore
9 | Settings
10 |
11 |
--------------------------------------------------------------------------------
/blockcanary-android/src/main/java/com/github/moduth/blockcanary/ui/BlockInfoCorruptException.java:
--------------------------------------------------------------------------------
1 | package com.github.moduth.blockcanary.ui;
2 |
3 | import java.util.Locale;
4 |
5 | /**
6 | * @author markzhai on 16/8/24
7 | * @version 1.3.0
8 | */
9 | public class BlockInfoCorruptException extends Exception {
10 |
11 | public BlockInfoCorruptException(BlockInfoEx blockInfo) {
12 | this(String.format(Locale.US,
13 | "BlockInfo (%s) is corrupt.", blockInfo.logFile.getName()));
14 | }
15 |
16 | public BlockInfoCorruptException(String detailMessage) {
17 | super(detailMessage);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/blockcanary-sample/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
13 |
14 |
16 |
17 |
--------------------------------------------------------------------------------
/blockcanary-sample/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/yifan/dev/sdk/adt-bundle-mac-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 |
--------------------------------------------------------------------------------
/blockcanary-analyzer/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/yifan/dev/sdk/adt-bundle-mac-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 |
--------------------------------------------------------------------------------
/blockcanary-android-no-op/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/yifan/dev/sdk/adt-bundle-mac-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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # BlockCanaryCompat
2 | [  ](https://bintray.com/bzcoder/BlockCanaryCompat/blockcanarycompat-android/0.0.4/link)
3 |
4 | 修改自[BlockCanary](https://github.com/markzhai/AndroidPerformanceMonitor),适配Android 8.0以上版本。建议阅读源码后,根据生产实际需求修改后使用。
5 |
6 | 引入:
7 | ```
8 | debugImplementation('com.github.bzcoder:blockcanarycompat-android:0.0.4')
9 | releaseImplementation('com.github.bzcoder:blockcanarycompat-android-no-op:0.0.4')
10 | ```
11 |
12 | 兼容:
13 | - 高版本不能获取IMEI的问题
14 | - 高版本不弹出通知问题
15 | - 高版本无法获取CPU信息的问题
16 |
17 | 新增:
18 | - App是否在前台选项
19 | - GetSingleCpuRateInfoUtils工具类提取CPU信息单独选项
20 | - reportRecentOneMessage选项,作用为限制上报卡顿信息为一条(如果需要采集线上日志,可配合使用)
21 |
--------------------------------------------------------------------------------
/blockcanary-android/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/Abner/myData/mySoftware/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 | # Need if enable display in proguarded package
--------------------------------------------------------------------------------
/blockcanary-android/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/blockcanary-android/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Blocks
3 | Share info
4 | Share stack dump
5 | Share with…
6 | Blocks in %s
7 | Delete
8 | Delete all
9 | Are you sure to delete all records?
10 | blocked %s ms
11 | Click for more details
12 | Yes
13 | No
14 |
15 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Change Log
2 |
3 | You can watch releases [on Maven](https://oss.sonatype.org/content/groups/public/com/github/markzhai/).
4 |
5 | ## Version 1.5 *(2017-02-26)*
6 |
7 | Debug mode stop monitor.
8 |
9 | ## Version 1.4 *(2016-11-02)*
10 |
11 | - Bug fix.
12 | - Add onBlock interceptor.
13 |
14 | ### 1.4.1 (2017-01-19)
15 |
16 | - Bug fix
17 |
18 | ## Version 1.3 *(2016-08-24)*
19 |
20 | - Code refactor.
21 | - Support white-list and concern packages.
22 |
23 | ## Version 1.2 *(2016-03-16)*
24 |
25 | - Much faster! It now has almost none side-effect at run-time.
26 |
27 | ## Version 1.1 *(2016-01-23)*
28 |
29 | - Extract blockcanary to three modules.
30 | - Provide default implementation for BlockCanaryContext.
31 |
32 | ### 1.1.1 *(2016-01-25)*
33 | fix issue #19 and #23
34 |
35 | ## Version 1.0 *(2016-01-21)*
36 |
37 | Initial release.
38 |
39 | ### 1.0.1
40 | Fix no-op api not align bug.
41 |
42 | ### 1.0.2
43 | Add notification sound, fix 2.3 crash.
44 |
--------------------------------------------------------------------------------
/blockcanary-android/src/main/res/layout/block_canary_block_row.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
17 |
18 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/BlockInterceptor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 MarkZhai (http://zhaiyifan.cn).
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.moduth.blockcanary;
17 |
18 | import android.content.Context;
19 |
20 | import com.github.moduth.blockcanary.internal.BlockInfo;
21 |
22 | interface BlockInterceptor {
23 | void onBlock(Context context, BlockInfo blockInfo);
24 | }
25 |
--------------------------------------------------------------------------------
/blockcanary-sample/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
12 |
13 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | ## Project-wide Gradle settings.
2 | #
3 | # For more details on how to configure your build environment visit
4 | # http://www.gradle.org/docs/current/userguide/build_environment.html
5 | #
6 | # Specifies the JVM arguments used for the daemon process.
7 | # The setting is particularly useful for tweaking memory settings.
8 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
9 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
10 | #
11 | # When configured, Gradle will run in incubating parallel mode.
12 | # This option should only be used with decoupled projects. More details, visit
13 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
14 | # org.gradle.parallel=true
15 | #Sat Mar 05 00:07:08 CST 2016
16 | org.gradle.jvmargs=-Xmx8192M
17 | #org.gradle.jvmargs=-Xmx10248m -XX\:MaxPermSize\=512m -XX\:+HeapDumpOnOutOfMemoryError -Dfile.encoding\=UTF-8
18 | org.gradle.daemon=true
19 | org.gradle.configureondemand=true
20 | org.gradle.parallel=true
21 | android.useDeprecatedNdk=true
--------------------------------------------------------------------------------
/blockcanary-sample/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion LIBRARY_COMPILE_SDK_VERSION
5 | buildToolsVersion LIBRARY_BUILD_TOOLS_VERSION
6 |
7 | defaultConfig {
8 | applicationId "com.example.blockcanary"
9 | minSdkVersion LIBRARY_MIN_SDK_VERSION
10 | targetSdkVersion LIBRARY_TARGET_SDK_VERSION
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | implementation fileTree(dir: 'libs', include: ['*.jar'])
24 | // debugImplementation('com.github.bzcoder:blockcanarycompat-android:0.0.4')
25 | // releaseImplementation('com.github.bzcoder:blockcanarycompat-android-no-op:0.0.4')
26 | api project(':blockcanary-android-no-op')
27 | //
28 | implementation('com.android.support:appcompat-v7:27.1.1')
29 | implementation('com.android.support:design:27.1.1')
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/blockcanary-android/src/main/res/layout/block_canary_display_leak.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
16 |
17 |
24 |
25 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/blockcanary-android/src/main/res/layout/block_canary_ref_row.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
15 |
16 |
22 |
23 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/blockcanary-android/src/main/java/com/github/moduth/blockcanary/SingleThreadFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.moduth.blockcanary;
17 |
18 | import java.util.concurrent.ThreadFactory;
19 |
20 | /**
21 | * This is intended to only be used with a single thread executor.
22 | */
23 | final class SingleThreadFactory implements ThreadFactory {
24 |
25 | private final String threadName;
26 |
27 | SingleThreadFactory(String threadName) {
28 | this.threadName = "BlockCanary-" + threadName;
29 | }
30 |
31 | @Override
32 | public Thread newThread(Runnable runnable) {
33 | return new Thread(runnable, threadName);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/blockcanary-sample/src/main/java/com/example/blockcanary/DemoApplication.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 MarkZhai (http://zhaiyifan.cn).
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.blockcanary;
17 |
18 | import android.app.Application;
19 | import android.content.Context;
20 |
21 | import com.github.moduth.blockcanary.BlockCanary;
22 |
23 | public class DemoApplication extends Application {
24 |
25 | private static Context sContext;
26 |
27 | @Override
28 | public void onCreate() {
29 | super.onCreate();
30 | sContext = this;
31 | BlockCanary.install(this, new AppContext()).start();
32 | }
33 |
34 | public static Context getAppContext() {
35 | return sContext;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/blockcanary-sample/src/main/res/layout/activity_demo.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
9 |
10 |
15 |
16 |
22 |
23 |
31 |
--------------------------------------------------------------------------------
/blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/internal/BackgroundUtil.java:
--------------------------------------------------------------------------------
1 | package com.github.moduth.blockcanary.internal;
2 |
3 | import android.app.ActivityManager;
4 | import android.content.Context;
5 |
6 | import java.util.List;
7 |
8 | /**
9 | * 判断app是否在前台
10 | * @author : BaoZhou
11 | * @date : 2020/4/22 11:53 AM
12 | */
13 | public class BackgroundUtil {
14 | public static boolean isBackground(Context context) {
15 | ActivityManager activityManager = (ActivityManager) context
16 | .getSystemService(Context.ACTIVITY_SERVICE);
17 | List appProcesses = activityManager
18 | .getRunningAppProcesses();
19 | if (appProcesses != null && appProcesses.size() > 0) {
20 | for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
21 | if (appProcess.processName.equals(context.getPackageName())) {
22 | if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
23 | return true;
24 | } else {
25 | return false;
26 | }
27 | }
28 | }
29 | return false;
30 | } else {
31 | return false;
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/internal/GetSingleCpuRateInfoUtils.java:
--------------------------------------------------------------------------------
1 | package com.github.moduth.blockcanary.internal;
2 |
3 | public class GetSingleCpuRateInfoUtils {
4 | private static final String TAG = "GetSingleCpuRateInfoUti";
5 |
6 | public static CpuInfo getCpu(String info) {
7 | if (info == null || info.isEmpty()) {
8 | return new CpuInfo();
9 | }
10 | String[] split = info.split(BlockInfo.SEPARATOR);
11 | if (split.length > 0) {
12 | String[] cpuInfo = split[0].split(" ");
13 | if (cpuInfo.length == 7) {
14 | return new CpuInfo(deletePercentSymbol(cpuInfo[2]),
15 | deletePercentSymbol(cpuInfo[3]),
16 | deletePercentSymbol(cpuInfo[4]),
17 | deletePercentSymbol(cpuInfo[5]),
18 | deletePercentSymbol(cpuInfo[6]));
19 | }
20 | if (cpuInfo.length == 3) {
21 | return new CpuInfo(deletePercentSymbol(cpuInfo[2]));
22 | }
23 | }
24 | return null;
25 | }
26 |
27 | private static String deletePercentSymbol(String cpuInfo) {
28 | if (cpuInfo.endsWith("%")) {
29 | return cpuInfo.substring(0, cpuInfo.lastIndexOf("%"));
30 | } else {
31 | return cpuInfo;
32 | }
33 | }
34 |
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/internal/CpuInfo.java:
--------------------------------------------------------------------------------
1 | package com.github.moduth.blockcanary.internal;
2 |
3 | public class CpuInfo {
4 | private String cpu;
5 | private String app;
6 | private String user;
7 | private String system;
8 | private String ioWait;
9 |
10 |
11 | public CpuInfo() {
12 | }
13 |
14 | public CpuInfo(String app) {
15 | this.app = app;
16 | }
17 |
18 | public CpuInfo(String cpu, String app, String user, String system, String ioWait) {
19 | this.cpu = cpu;
20 | this.app = app;
21 | this.user = user;
22 | this.system = system;
23 | this.ioWait = ioWait;
24 | }
25 |
26 |
27 | public String getCpu() {
28 | return cpu;
29 | }
30 |
31 | public String getApp() {
32 | return app;
33 | }
34 |
35 | public String getUser() {
36 | return user;
37 | }
38 |
39 | public String getSystem() {
40 | return system;
41 | }
42 |
43 | public String getIoWait() {
44 | return ioWait;
45 | }
46 |
47 |
48 | @Override
49 | public String toString() {
50 | StringBuilder stringBuilder = new StringBuilder();
51 | if (cpu != null) {
52 | stringBuilder.append("cpu:").append(cpu).append("% ");
53 | }
54 | if (app != null) {
55 | stringBuilder.append("app:").append(app).append("% ");
56 | }
57 | if (user != null) {
58 | stringBuilder.append("user:").append(user).append("% ");
59 | }
60 | if (system != null) {
61 | stringBuilder.append("system:").append(system).append("% ");
62 | }
63 | if (ioWait != null) {
64 | stringBuilder.append("ioWait:").append(ioWait).append("% ");
65 | }
66 | return stringBuilder.toString();
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/blockcanary-android-no-op/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | build
4 | android {
5 | compileSdkVersion LIBRARY_COMPILE_SDK_VERSION
6 | buildToolsVersion LIBRARY_BUILD_TOOLS_VERSION
7 |
8 | defaultConfig {
9 | minSdkVersion LIBRARY_MIN_SDK_VERSION
10 | targetSdkVersion LIBRARY_TARGET_SDK_VERSION
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | lintOptions {
21 | abortOnError false
22 | }
23 | }
24 |
25 | dependencies {
26 | implementation fileTree(dir: 'libs', include: ['*.jar'])
27 | }
28 |
29 |
30 | //生成源文件
31 | task sourcesJar(type: Jar) {
32 | from android.sourceSets.main.java.srcDirs
33 | classifier = 'sources'
34 | }
35 |
36 | //生成Javadoc文档
37 | task javadoc(type: Javadoc) {
38 | source = android.sourceSets.main.java.srcDirs
39 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
40 | }
41 |
42 | //文档打包成jar
43 | task javadocJar(type: Jar, dependsOn: javadoc) {
44 | classifier = 'javadoc'
45 | from javadoc.destinationDir
46 | }
47 |
48 | //拷贝javadoc文件
49 | task copyDoc(type: Copy) {
50 | from "${buildDir}/docs/"
51 | into "docs"
52 | }
53 |
54 | //上传到JCenter所需要的源码文件
55 | artifacts {
56 | archives javadocJar
57 | archives sourcesJar
58 | }
59 |
60 | apply plugin: 'com.novoda.bintray-release'
61 |
62 |
63 | publish {
64 | userOrg = 'bzcoder'
65 | repoName = 'BlockCanaryCompat'
66 | groupId = 'com.github.bzcoder'
67 | artifactId = 'blockcanarycompat-android-no-op'
68 | publishVersion = '0.0.5'
69 | desc = 'blockcanarycompat-android-no-op'
70 | website = 'https://github.com/BzCoder/BlockCanaryCompat'
71 | }
72 |
--------------------------------------------------------------------------------
/blockcanary-analyzer/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | //
3 |
4 |
5 | android {
6 | compileSdkVersion LIBRARY_COMPILE_SDK_VERSION
7 | buildToolsVersion LIBRARY_BUILD_TOOLS_VERSION
8 |
9 | defaultConfig {
10 | minSdkVersion LIBRARY_MIN_SDK_VERSION
11 | targetSdkVersion LIBRARY_TARGET_SDK_VERSION
12 | versionCode 1
13 | versionName "1.0"
14 | }
15 | buildTypes {
16 | release {
17 | minifyEnabled false
18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
19 | }
20 | }
21 | lintOptions {
22 | abortOnError false
23 | }
24 | }
25 |
26 | dependencies {
27 | implementation fileTree(dir: 'libs', include: ['*.jar'])
28 | }
29 |
30 |
31 | //生成源文件
32 | task sourcesJar(type: Jar) {
33 | from android.sourceSets.main.java.srcDirs
34 | classifier = 'sources'
35 | }
36 |
37 | //生成Javadoc文档
38 | task javadoc(type: Javadoc) {
39 | source = android.sourceSets.main.java.srcDirs
40 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
41 | }
42 |
43 | //文档打包成jar
44 | task javadocJar(type: Jar, dependsOn: javadoc) {
45 | classifier = 'javadoc'
46 | from javadoc.destinationDir
47 | }
48 |
49 | //拷贝javadoc文件
50 | task copyDoc(type: Copy) {
51 | from "${buildDir}/docs/"
52 | into "docs"
53 | }
54 |
55 | //上传到JCenter所需要的源码文件
56 | artifacts {
57 | archives javadocJar
58 | archives sourcesJar
59 | }
60 |
61 | //apply plugin: 'com.novoda.bintray-release'
62 | //publish {
63 | // userOrg = 'bzcoder'
64 | // repoName = 'BlockCanaryCompat'
65 | // groupId = 'com.github.bzcoder'
66 | // artifactId = 'blockcanarycompat-analyzer'
67 | // publishVersion = '0.0.5'
68 | // desc = 'blockcanarycompat-analyzer'
69 | // website = 'https://github.com/BzCoder/BlockCanaryCompat'
70 | //}
71 |
72 |
--------------------------------------------------------------------------------
/blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/HandlerThreadFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 MarkZhai (http://zhaiyifan.cn).
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.moduth.blockcanary;
17 |
18 | import android.os.Handler;
19 | import android.os.HandlerThread;
20 |
21 | final class HandlerThreadFactory {
22 |
23 | private static HandlerThreadWrapper sLoopThread = new HandlerThreadWrapper("loop");
24 | private static HandlerThreadWrapper sWriteLogThread = new HandlerThreadWrapper("writer");
25 |
26 | private HandlerThreadFactory() {
27 | throw new InstantiationError("Must not instantiate this class");
28 | }
29 |
30 | public static Handler getTimerThreadHandler() {
31 | return sLoopThread.getHandler();
32 | }
33 |
34 | public static Handler getWriteLogThreadHandler() {
35 | return sWriteLogThread.getHandler();
36 | }
37 |
38 | private static class HandlerThreadWrapper {
39 | private Handler handler = null;
40 |
41 | public HandlerThreadWrapper(String threadName) {
42 | HandlerThread handlerThread = new HandlerThread("BlockCanary-" + threadName);
43 | handlerThread.start();
44 | handler = new Handler(handlerThread.getLooper());
45 | }
46 |
47 | public Handler getHandler() {
48 | return handler;
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/blockcanary-android/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 |
4 | android {
5 | compileSdkVersion LIBRARY_COMPILE_SDK_VERSION
6 | buildToolsVersion LIBRARY_BUILD_TOOLS_VERSION
7 |
8 | defaultConfig {
9 | minSdkVersion LIBRARY_MIN_SDK_VERSION
10 | targetSdkVersion LIBRARY_TARGET_SDK_VERSION
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | lintOptions {
21 | abortOnError false
22 | }
23 | }
24 |
25 | dependencies {
26 | implementation fileTree(include: ['*.jar'], dir: 'libs')
27 | api project(':blockcanary-analyzer')
28 | // api 'com.github.bzcoder:blockcanarycompat-analyzer:0.0.5'
29 | }
30 |
31 | //生成源文件
32 | task sourcesJar(type: Jar) {
33 | from android.sourceSets.main.java.srcDirs
34 | classifier = 'sources'
35 | }
36 |
37 | //生成Javadoc文档
38 | task javadoc(type: Javadoc) {
39 | source = android.sourceSets.main.java.srcDirs
40 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
41 | }
42 |
43 | //文档打包成jar
44 | task javadocJar(type: Jar, dependsOn: javadoc) {
45 | classifier = 'javadoc'
46 | from javadoc.destinationDir
47 | }
48 |
49 | //拷贝javadoc文件
50 | task copyDoc(type: Copy) {
51 | from "${buildDir}/docs/"
52 | into "docs"
53 | }
54 |
55 | //上传到JCenter所需要的源码文件
56 | artifacts {
57 | archives javadocJar
58 | archives sourcesJar
59 | }
60 |
61 | //apply plugin: 'com.novoda.bintray-release'
62 | //
63 | //publish {
64 | // userOrg = 'bzcoder'
65 | // repoName = 'BlockCanaryCompat'
66 | // groupId = 'com.github.bzcoder'
67 | // artifactId = 'blockcanarycompat-android'
68 | // publishVersion = '0.0.5'
69 | // desc = 'blockcanarycompat-android'
70 | // website = 'https://github.com/BzCoder/BlockCanaryCompat'
71 | //}
72 | //
73 |
--------------------------------------------------------------------------------
/blockcanary-android/src/main/java/com/github/moduth/blockcanary/ui/MoreDetailsView.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.moduth.blockcanary.ui;
17 |
18 | import android.content.Context;
19 | import android.graphics.Canvas;
20 | import android.graphics.Paint;
21 | import android.util.AttributeSet;
22 | import android.view.View;
23 |
24 | public final class MoreDetailsView extends View {
25 |
26 | private final Paint mIconPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
27 | private boolean mFolding = true;
28 |
29 | public MoreDetailsView(Context context, AttributeSet attrs) {
30 | super(context, attrs);
31 |
32 | mIconPaint.setStrokeWidth(BlockCanaryUi.dpToPixel(2f, getResources()));
33 | mIconPaint.setColor(BlockCanaryUi.ROOT_COLOR);
34 | }
35 |
36 | @Override protected void onDraw(Canvas canvas) {
37 | int width = getWidth();
38 | int height = getHeight();
39 | int halfHeight = height / 2;
40 | int halfWidth = width / 2;
41 |
42 | canvas.drawLine(0, halfHeight, width, halfHeight, mIconPaint);
43 | if (mFolding) {
44 | canvas.drawLine(halfWidth, 0, halfWidth, height, mIconPaint);
45 | }
46 | }
47 |
48 | public void setFolding(boolean folding) {
49 | if (folding != this.mFolding) {
50 | this.mFolding = folding;
51 | invalidate();
52 | }
53 | }
54 | }
--------------------------------------------------------------------------------
/blockcanary-android/src/main/java/com/github/moduth/blockcanary/ui/BlockCanaryUi.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.moduth.blockcanary.ui;
17 |
18 | import android.content.res.Resources;
19 | import android.graphics.PorterDuffXfermode;
20 | import android.util.DisplayMetrics;
21 | import static android.graphics.PorterDuff.Mode.CLEAR;
22 |
23 | final class BlockCanaryUi {
24 | static final int LIGHT_GREY = 0xFFbababa;
25 | static final int ROOT_COLOR = 0xFF84a6c5;
26 | static final int LEAK_COLOR = 0xFFb1554e;
27 |
28 | static final PorterDuffXfermode CLEAR_XFER_MODE = new PorterDuffXfermode(CLEAR);
29 |
30 | private BlockCanaryUi() {
31 | throw new AssertionError();
32 | }
33 |
34 | /**
35 | * Converts from device independent pixels (dp or dip) to
36 | * device dependent pixels. This method returns the input
37 | * multiplied by the display's density. The result is not
38 | * rounded nor clamped.
39 | *
40 | * The value returned by this method is well suited for
41 | * drawing with the Canvas API but should not be used to
42 | * set layout dimensions.
43 | *
44 | * @param dp The value in dp to convert to pixels
45 | * @param resources An instances of Resources
46 | */
47 | static float dpToPixel(float dp, Resources resources) {
48 | DisplayMetrics metrics = resources.getDisplayMetrics();
49 | return metrics.density * dp;
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/blockcanary-android-no-op/src/main/java/com/github/moduth/blockcanary/BlockCanary.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 MarkZhai (http://zhaiyifan.cn).
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.moduth.blockcanary;
17 |
18 | import android.content.Context;
19 | import android.util.Log;
20 |
21 | /**
22 | * No-op implementation.
23 | */
24 | public final class BlockCanary {
25 |
26 | private static final String TAG = "BlockCanary-no-op";
27 | private static BlockCanary sInstance = null;
28 |
29 | private BlockCanary() {
30 | }
31 |
32 | public static BlockCanary install(Context context, BlockCanaryContext blockCanaryContext) {
33 | BlockCanaryContext.init(context, blockCanaryContext);
34 | return get();
35 | }
36 |
37 | public static BlockCanary get() {
38 | if (sInstance == null) {
39 | synchronized (BlockCanary.class) {
40 | if (sInstance == null) {
41 | sInstance = new BlockCanary();
42 | }
43 | }
44 | }
45 | return sInstance;
46 | }
47 |
48 | public void start() {
49 | Log.i(TAG, "start");
50 | }
51 |
52 | public void stop() {
53 | Log.i(TAG, "stop");
54 | }
55 |
56 | public void upload() {
57 | Log.i(TAG, "upload");
58 | }
59 |
60 | public void recordStartTime() {
61 | Log.i(TAG, "recordStartTime");
62 | }
63 |
64 | public boolean isMonitorDurationEnd() {
65 | return true;
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/blockcanary-android/src/main/java/com/github/moduth/blockcanary/Uploader.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 MarkZhai (http://zhaiyifan.cn).
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.moduth.blockcanary;
17 |
18 | import android.util.Log;
19 |
20 | import java.io.File;
21 | import java.text.SimpleDateFormat;
22 | import java.util.Date;
23 | import java.util.Locale;
24 |
25 |
26 | final class Uploader {
27 |
28 | private static final String TAG = "Uploader";
29 | private static final SimpleDateFormat FORMAT =
30 | new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.US);
31 |
32 | private Uploader() {
33 | throw new InstantiationError("Must not instantiate this class");
34 | }
35 |
36 | private static File zip() {
37 | String timeString = Long.toString(System.currentTimeMillis());
38 | try {
39 | timeString = FORMAT.format(new Date());
40 | } catch (Throwable e) {
41 | Log.e(TAG, "zip: ", e);
42 | }
43 | File zippedFile = LogWriter.generateTempZip("BlockCanary-" + timeString);
44 | BlockCanaryInternals.getContext().zip(BlockCanaryInternals.getLogFiles(), zippedFile);
45 | LogWriter.deleteAll();
46 | return zippedFile;
47 | }
48 |
49 | public static void zipAndUpload() {
50 | HandlerThreadFactory.getWriteLogThreadHandler().post(new Runnable() {
51 | @Override
52 | public void run() {
53 | final File file = zip();
54 | if (file.exists()) {
55 | BlockCanaryInternals.getContext().upload(file);
56 | }
57 | }
58 | });
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/internal/ProcessUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 MarkZhai (http://zhaiyifan.cn).
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.moduth.blockcanary.internal;
17 |
18 | import android.app.ActivityManager;
19 | import android.content.Context;
20 |
21 | import com.github.moduth.blockcanary.BlockCanaryInternals;
22 |
23 | import java.util.List;
24 |
25 | public class ProcessUtils {
26 |
27 | private static volatile String sProcessName;
28 | private final static Object sNameLock = new Object();
29 |
30 | private ProcessUtils() {
31 | throw new InstantiationError("Must not instantiate this class");
32 | }
33 |
34 | public static String myProcessName() {
35 | if (sProcessName != null) {
36 | return sProcessName;
37 | }
38 | synchronized (sNameLock) {
39 | if (sProcessName != null) {
40 | return sProcessName;
41 | }
42 | sProcessName = obtainProcessName(BlockCanaryInternals.getContext().provideContext());
43 | return sProcessName;
44 | }
45 | }
46 |
47 | private static String obtainProcessName(Context context) {
48 | final int pid = android.os.Process.myPid();
49 | ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
50 | List listTaskInfo = am.getRunningAppProcesses();
51 | if (listTaskInfo != null && !listTaskInfo.isEmpty()) {
52 | for (ActivityManager.RunningAppProcessInfo info : listTaskInfo) {
53 | if (info != null && info.pid == pid) {
54 | return info.processName;
55 | }
56 | }
57 | }
58 | return null;
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/AbstractSampler.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 MarkZhai (http://zhaiyifan.cn).
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.moduth.blockcanary;
17 |
18 | import java.util.concurrent.atomic.AtomicBoolean;
19 |
20 | /**
21 | * {@link AbstractSampler} sampler defines sampler work flow.
22 | */
23 | abstract class AbstractSampler {
24 |
25 | private static final int DEFAULT_SAMPLE_INTERVAL = 300;
26 |
27 | protected AtomicBoolean mShouldSample = new AtomicBoolean(false);
28 | protected long mSampleInterval;
29 |
30 | private Runnable mRunnable = new Runnable() {
31 | @Override
32 | public void run() {
33 | doSample();
34 |
35 | if (mShouldSample.get()) {
36 | HandlerThreadFactory.getTimerThreadHandler()
37 | .postDelayed(mRunnable, mSampleInterval);
38 | }
39 | }
40 | };
41 |
42 | public AbstractSampler(long sampleInterval) {
43 | if (0 == sampleInterval) {
44 | sampleInterval = DEFAULT_SAMPLE_INTERVAL;
45 | }
46 | mSampleInterval = sampleInterval;
47 | }
48 |
49 | public void start() {
50 | if (mShouldSample.get()) {
51 | return;
52 | }
53 | mShouldSample.set(true);
54 |
55 | HandlerThreadFactory.getTimerThreadHandler().removeCallbacks(mRunnable);
56 | HandlerThreadFactory.getTimerThreadHandler().postDelayed(mRunnable,
57 | BlockCanaryInternals.getInstance().getSampleDelay());
58 | }
59 |
60 | public void stop() {
61 | if (!mShouldSample.get()) {
62 | return;
63 | }
64 | mShouldSample.set(false);
65 | HandlerThreadFactory.getTimerThreadHandler().removeCallbacks(mRunnable);
66 | }
67 |
68 | abstract void doSample();
69 | }
70 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/blockcanary-sample/src/main/java/com/example/blockcanary/AppContext.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 MarkZhai (http://zhaiyifan.cn).
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.blockcanary;
17 |
18 | import android.content.Context;
19 | import android.content.pm.PackageInfo;
20 | import android.content.pm.PackageManager;
21 | import android.util.Log;
22 |
23 | import com.github.moduth.blockcanary.BlockCanaryContext;
24 | import com.github.moduth.blockcanary.internal.BlockInfo;
25 |
26 | import java.util.List;
27 |
28 | public class AppContext extends BlockCanaryContext {
29 | private static final String TAG = "AppContext";
30 |
31 | @Override
32 | public String provideQualifier() {
33 | String qualifier = "";
34 | try {
35 | PackageInfo info = DemoApplication.getAppContext().getPackageManager()
36 | .getPackageInfo(DemoApplication.getAppContext().getPackageName(), 0);
37 | qualifier += info.versionCode + "_" + info.versionName + "_YYB";
38 | } catch (PackageManager.NameNotFoundException e) {
39 | Log.e(TAG, "provideQualifier exception", e);
40 | }
41 | return qualifier;
42 | }
43 |
44 | @Override
45 | public String provideUid() {
46 | return "87224330";
47 | }
48 |
49 | @Override
50 | public String provideNetworkType() {
51 | return "4G";
52 | }
53 |
54 | @Override
55 | public int provideMonitorDuration() {
56 | return 9999;
57 | }
58 |
59 | @Override
60 | public int provideBlockThreshold() {
61 | return 500;
62 | }
63 |
64 | @Override
65 | public boolean displayNotification() {
66 | return BuildConfig.DEBUG;
67 | }
68 |
69 | @Override
70 | public List concernPackages() {
71 | List list = super.provideWhiteList();
72 | list.add("com.example");
73 | return list;
74 | }
75 |
76 | @Override
77 | public List provideWhiteList() {
78 | List list = super.provideWhiteList();
79 | list.add("com.whitelist");
80 | return list;
81 | }
82 |
83 | @Override
84 | public void onBlock(Context context, BlockInfo blockInfo) {
85 | }
86 |
87 | @Override
88 | public boolean stopWhenDebugging() {
89 | return true;
90 | }
91 |
92 | @Override
93 | public boolean reportRecentOneMessage() {
94 | return true;
95 | }
96 | }
--------------------------------------------------------------------------------
/blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/StackSampler.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 MarkZhai (http://zhaiyifan.cn).
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.moduth.blockcanary;
17 |
18 | import com.github.moduth.blockcanary.internal.BlockInfo;
19 |
20 | import java.util.ArrayList;
21 | import java.util.LinkedHashMap;
22 |
23 | /**
24 | * Dumps thread stack.
25 | */
26 | class StackSampler extends AbstractSampler {
27 |
28 | private static final int DEFAULT_MAX_ENTRY_COUNT = BlockCanaryInternals.getContext().reportRecentOneMessage() ? 1 : 100;
29 | ;
30 | private static final LinkedHashMap sStackMap = new LinkedHashMap<>();
31 |
32 | private int mMaxEntryCount = DEFAULT_MAX_ENTRY_COUNT;
33 | private Thread mCurrentThread;
34 |
35 | public StackSampler(Thread thread, long sampleIntervalMillis) {
36 | this(thread, DEFAULT_MAX_ENTRY_COUNT, sampleIntervalMillis);
37 | }
38 |
39 | public StackSampler(Thread thread, int maxEntryCount, long sampleIntervalMillis) {
40 | super(sampleIntervalMillis);
41 | mCurrentThread = thread;
42 | mMaxEntryCount = maxEntryCount;
43 | }
44 |
45 | public ArrayList getThreadStackEntries(long startTime, long endTime) {
46 | ArrayList result = new ArrayList<>();
47 | synchronized (sStackMap) {
48 | for (Long entryTime : sStackMap.keySet()) {
49 | if (startTime < entryTime && entryTime < endTime) {
50 | result.add(BlockInfo.TIME_FORMATTER.format(entryTime)
51 | + BlockInfo.SEPARATOR
52 | + BlockInfo.SEPARATOR
53 | + sStackMap.get(entryTime));
54 | }
55 | }
56 | }
57 | return result;
58 | }
59 |
60 | @Override
61 | protected void doSample() {
62 | StringBuilder stringBuilder = new StringBuilder();
63 |
64 | for (StackTraceElement stackTraceElement : mCurrentThread.getStackTrace()) {
65 | stringBuilder
66 | .append(stackTraceElement.toString())
67 | .append(BlockInfo.SEPARATOR);
68 | }
69 |
70 | synchronized (sStackMap) {
71 | if (sStackMap.size() == mMaxEntryCount && mMaxEntryCount > 0) {
72 | sStackMap.remove(sStackMap.keySet().iterator().next());
73 | }
74 | sStackMap.put(System.currentTimeMillis(), stringBuilder.toString());
75 | }
76 | }
77 | }
--------------------------------------------------------------------------------
/blockcanary-android-no-op/src/main/java/com/github/moduth/blockcanary/BlockCanaryContext.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 MarkZhai (http://zhaiyifan.cn).
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.moduth.blockcanary;
17 |
18 | import android.content.Context;
19 |
20 | import com.github.moduth.blockcanary.internal.BlockInfo;
21 |
22 | import java.io.File;
23 | import java.util.List;
24 |
25 | /**
26 | * No-op context.
27 | */
28 | public class BlockCanaryContext {
29 |
30 | private static Context sApplicationContext;
31 | private static BlockCanaryContext sInstance = null;
32 |
33 | public BlockCanaryContext() {
34 | }
35 |
36 | static void init(Context c, BlockCanaryContext g) {
37 | sApplicationContext = c;
38 | sInstance = g;
39 | }
40 |
41 | public static BlockCanaryContext get() {
42 | if (sInstance == null) {
43 | throw new RuntimeException("BlockCanaryContext not init");
44 | } else {
45 | return sInstance;
46 | }
47 | }
48 |
49 | public Context provideContext() {
50 | return sApplicationContext;
51 | }
52 |
53 | public String provideQualifier() {
54 | return "Unspecified";
55 | }
56 |
57 | public String provideUid() {
58 | return "0";
59 | }
60 |
61 | public String provideNetworkType() {
62 | return "UNKNOWN";
63 | }
64 |
65 | public int provideMonitorDuration() {
66 | return 99999;
67 | }
68 |
69 | public int provideBlockThreshold() {
70 | return 1000;
71 | }
72 |
73 | public int provideDumpInterval() {
74 | return provideBlockThreshold();
75 | }
76 |
77 | public String providePath() {
78 | return "/blockcanary/";
79 | }
80 |
81 | public boolean displayNotification() {
82 | return false;
83 | }
84 |
85 | public boolean zip(File[] src, File dest) {
86 | return false;
87 | }
88 |
89 | public void upload(File zippedFile) {
90 | throw new UnsupportedOperationException();
91 | }
92 |
93 | public List concernPackages() {
94 | return null;
95 | }
96 |
97 | public boolean filterNonConcernStack() {
98 | return false;
99 | }
100 |
101 | public List provideWhiteList() {
102 | return null;
103 | }
104 |
105 | public boolean deleteFilesInWhiteList() {
106 | return false;
107 | }
108 |
109 | public void onBlock(Context context, BlockInfo blockInfo) {
110 |
111 | }
112 |
113 | public boolean stopWhenDebugging() {
114 | return true;
115 | }
116 |
117 | public boolean reportRecentOneMessage() {
118 | return false;
119 | }
120 | }
--------------------------------------------------------------------------------
/blockcanary-android/src/main/java/com/github/moduth/blockcanary/ui/BlockCanaryUtils.java:
--------------------------------------------------------------------------------
1 | package com.github.moduth.blockcanary.ui;
2 |
3 | import android.text.TextUtils;
4 |
5 | import com.github.moduth.blockcanary.BlockCanaryInternals;
6 | import com.github.moduth.blockcanary.internal.BlockInfo;
7 | import com.github.moduth.blockcanary.internal.ProcessUtils;
8 |
9 | import java.util.LinkedList;
10 | import java.util.List;
11 |
12 | public final class BlockCanaryUtils {
13 |
14 | private static final List WHITE_LIST = new LinkedList<>();
15 | private static final List CONCERN_LIST = new LinkedList<>();
16 |
17 | static {
18 | WHITE_LIST.addAll(BlockCanaryInternals.getContext().provideWhiteList());
19 |
20 | if (BlockCanaryInternals.getContext().concernPackages() != null) {
21 | CONCERN_LIST.addAll(BlockCanaryInternals.getContext().concernPackages());
22 | }
23 | if (CONCERN_LIST.isEmpty()) {
24 | CONCERN_LIST.add(ProcessUtils.myProcessName());
25 | }
26 | }
27 |
28 | /**
29 | * Get key stack string to show as title in ui list.
30 | */
31 | public static String concernStackString(BlockInfo blockInfo) {
32 | String result = "";
33 | for (String stackEntry : blockInfo.threadStackEntries) {
34 | if (Character.isLetter(stackEntry.charAt(0))) {
35 | String[] lines = stackEntry.split(BlockInfo.SEPARATOR);
36 | for (String line : lines) {
37 | String keyStackString = concernStackString(line);
38 | if (keyStackString != null) {
39 | return keyStackString;
40 | }
41 | }
42 | return classSimpleName(lines[0]);
43 | }
44 | }
45 | return result;
46 | }
47 |
48 | public static boolean isBlockInfoValid(BlockInfo blockInfo) {
49 | boolean isValid = !TextUtils.isEmpty(blockInfo.timeStart);
50 | isValid = isValid && blockInfo.timeCost >= 0;
51 | return isValid;
52 | }
53 |
54 | public static boolean isInWhiteList(BlockInfo info) {
55 | for (String stackEntry : info.threadStackEntries) {
56 | if (Character.isLetter(stackEntry.charAt(0))) {
57 | String[] lines = stackEntry.split(BlockInfo.SEPARATOR);
58 | for (String line : lines) {
59 | for (String whiteListEntry : WHITE_LIST) {
60 | if (line.startsWith(whiteListEntry)) {
61 | return true;
62 | }
63 | }
64 | }
65 | }
66 | }
67 | return false;
68 | }
69 |
70 | public static List getConcernPackages() {
71 | return CONCERN_LIST;
72 | }
73 |
74 | private static String concernStackString(String line) {
75 | for (String concernPackage : CONCERN_LIST) {
76 | if (line.startsWith(concernPackage)) {
77 | return classSimpleName(line);
78 | }
79 | }
80 | return null;
81 | }
82 |
83 | private static String classSimpleName(String stackLine) {
84 | int index1 = stackLine.indexOf('(');
85 | int index2 = stackLine.indexOf(')');
86 | if (index1 >= 0 && index2 >= 0) {
87 | return stackLine.substring(index1 + 1, index2);
88 | }
89 | return stackLine;
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/blockcanary-sample/src/main/java/com/example/blockcanary/DemoActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 MarkZhai (http://zhaiyifan.cn).
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.blockcanary;
17 |
18 | import android.Manifest;
19 | import android.content.pm.PackageManager;
20 | import android.os.Build;
21 | import android.os.Bundle;
22 | import android.support.design.widget.FloatingActionButton;
23 | import android.support.v4.app.ActivityCompat;
24 | import android.support.v4.content.ContextCompat;
25 | import android.support.v7.app.AlertDialog;
26 | import android.support.v7.app.AppCompatActivity;
27 | import android.view.Menu;
28 | import android.view.MenuItem;
29 | import android.view.View;
30 |
31 | public class DemoActivity extends AppCompatActivity {
32 |
33 | @Override
34 | protected void onCreate(Bundle savedInstanceState) {
35 | super.onCreate(savedInstanceState);
36 | setContentView(R.layout.activity_demo);
37 |
38 | getSupportFragmentManager().beginTransaction()
39 | .add(R.id.container, DemoFragment.newInstance())
40 | .commit();
41 |
42 | FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
43 | fab.setOnClickListener(new View.OnClickListener() {
44 | @Override
45 | public void onClick(View view) {
46 | showTipDialog();
47 | }
48 | });
49 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
50 | if ((ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)) != PackageManager.PERMISSION_GRANTED) {
51 | ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 0);
52 | }
53 | }
54 | }
55 |
56 | private void showTipDialog() {
57 | AlertDialog.Builder builder = new AlertDialog.Builder(this);
58 | builder.setTitle("Tip");
59 | builder.setMessage(getResources().getString(R.string.hello_world));
60 | builder.setNegativeButton("ok", null);
61 | builder.show();
62 | }
63 |
64 |
65 |
66 | @Override
67 | public boolean onCreateOptionsMenu(Menu menu) {
68 | // Inflate the menu; this adds items to the action bar if it is present.
69 | getMenuInflater().inflate(R.menu.menu_demo, menu);
70 | return true;
71 | }
72 |
73 | @Override
74 | public boolean onOptionsItemSelected(MenuItem item) {
75 | // Handle action bar item clicks here. The action bar will
76 | // automatically handle clicks on the Home/Up button, so long
77 | // as you specify a parent activity in AndroidManifest.xml.
78 | int id = item.getItemId();
79 |
80 | //noinspection SimplifiableIfStatement
81 | if (id == R.id.action_settings) {
82 | return true;
83 | }
84 |
85 | return super.onOptionsItemSelected(item);
86 | }
87 |
88 | }
89 |
--------------------------------------------------------------------------------
/blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/LooperMonitor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 MarkZhai (http://zhaiyifan.cn).
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.moduth.blockcanary;
17 |
18 | import android.os.Debug;
19 | import android.os.SystemClock;
20 | import android.util.Printer;
21 |
22 | class LooperMonitor implements Printer {
23 |
24 | private static final int DEFAULT_BLOCK_THRESHOLD_MILLIS = 3000;
25 |
26 | private long mBlockThresholdMillis = DEFAULT_BLOCK_THRESHOLD_MILLIS;
27 | private long mStartTimestamp = 0;
28 | private long mStartThreadTimestamp = 0;
29 | private BlockListener mBlockListener = null;
30 | private boolean mPrintingStarted = false;
31 | private final boolean mStopWhenDebugging;
32 |
33 | public interface BlockListener {
34 | void onBlockEvent(long realStartTime,
35 | long realTimeEnd,
36 | long threadTimeStart,
37 | long threadTimeEnd);
38 | }
39 |
40 | public LooperMonitor(BlockListener blockListener, long blockThresholdMillis, boolean stopWhenDebugging) {
41 | if (blockListener == null) {
42 | throw new IllegalArgumentException("blockListener should not be null.");
43 | }
44 | mBlockListener = blockListener;
45 | mBlockThresholdMillis = blockThresholdMillis;
46 | mStopWhenDebugging = stopWhenDebugging;
47 | }
48 |
49 | @Override
50 | public void println(String x) {
51 | if (mStopWhenDebugging && Debug.isDebuggerConnected()) {
52 | return;
53 | }
54 | if (!mPrintingStarted) {
55 | mStartTimestamp = System.currentTimeMillis();
56 | mStartThreadTimestamp = SystemClock.currentThreadTimeMillis();
57 | mPrintingStarted = true;
58 | startDump();
59 | } else {
60 | final long endTime = System.currentTimeMillis();
61 | mPrintingStarted = false;
62 | if (isBlock(endTime)) {
63 | notifyBlockEvent(endTime);
64 | }
65 | stopDump();
66 | }
67 | }
68 |
69 | private boolean isBlock(long endTime) {
70 | return endTime - mStartTimestamp > mBlockThresholdMillis;
71 | }
72 |
73 | private void notifyBlockEvent(final long endTime) {
74 | final long startTime = mStartTimestamp;
75 | final long startThreadTime = mStartThreadTimestamp;
76 | final long endThreadTime = SystemClock.currentThreadTimeMillis();
77 | HandlerThreadFactory.getWriteLogThreadHandler().post(new Runnable() {
78 | @Override
79 | public void run() {
80 | mBlockListener.onBlockEvent(startTime, endTime, startThreadTime, endThreadTime);
81 | }
82 | });
83 | }
84 |
85 | private void startDump() {
86 | if (null != BlockCanaryInternals.getInstance().stackSampler) {
87 | BlockCanaryInternals.getInstance().stackSampler.start();
88 | }
89 |
90 | if (null != BlockCanaryInternals.getInstance().cpuSampler) {
91 | BlockCanaryInternals.getInstance().cpuSampler.start();
92 | }
93 | }
94 |
95 | private void stopDump() {
96 | if (null != BlockCanaryInternals.getInstance().stackSampler) {
97 | BlockCanaryInternals.getInstance().stackSampler.stop();
98 | }
99 |
100 | if (null != BlockCanaryInternals.getInstance().cpuSampler) {
101 | BlockCanaryInternals.getInstance().cpuSampler.stop();
102 | }
103 | }
104 | }
--------------------------------------------------------------------------------
/blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/internal/PerformanceUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 MarkZhai (http://zhaiyifan.cn).
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.moduth.blockcanary.internal;
17 |
18 | import android.app.ActivityManager;
19 | import android.content.Context;
20 | import android.util.Log;
21 |
22 | import com.github.moduth.blockcanary.BlockCanaryInternals;
23 |
24 | import java.io.BufferedReader;
25 | import java.io.File;
26 | import java.io.FileFilter;
27 | import java.io.FileReader;
28 | import java.io.IOException;
29 | import java.util.regex.Pattern;
30 |
31 | class PerformanceUtils {
32 | private static final String TAG = "PerformanceUtils";
33 |
34 | private static int sCoreNum = 0;
35 | private static long sTotalMemo = 0;
36 |
37 | private PerformanceUtils() {
38 | throw new InstantiationError("Must not instantiate this class");
39 | }
40 |
41 | /**
42 | * Get cpu core number
43 | *
44 | * @return int cpu core number
45 | */
46 | public static int getNumCores() {
47 | class CpuFilter implements FileFilter {
48 | @Override
49 | public boolean accept(File pathname) {
50 | return Pattern.matches("cpu[0-9]", pathname.getName());
51 | }
52 | }
53 |
54 | if (sCoreNum == 0) {
55 | try {
56 | // Get directory containing CPU info
57 | File dir = new File("/sys/devices/system/cpu/");
58 | // Filter to only list the devices we care about
59 | File[] files = dir.listFiles(new CpuFilter());
60 | // Return the number of cores (virtual CPU devices)
61 | sCoreNum = files.length;
62 | } catch (Exception e) {
63 | Log.e(TAG, "getNumCores exception", e);
64 | sCoreNum = 1;
65 | }
66 | }
67 | return sCoreNum;
68 | }
69 |
70 | public static long getFreeMemory() {
71 | ActivityManager am = (ActivityManager) BlockCanaryInternals.getContext().provideContext().getSystemService(Context.ACTIVITY_SERVICE);
72 | ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
73 | am.getMemoryInfo(mi);
74 | return mi.availMem / 1024;
75 | }
76 |
77 | public static long getTotalMemory() {
78 | if (sTotalMemo == 0) {
79 | String str1 = "/proc/meminfo";
80 | String str2;
81 | String[] arrayOfString;
82 | long initial_memory = -1;
83 | FileReader localFileReader = null;
84 | try {
85 | localFileReader = new FileReader(str1);
86 | BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);
87 | str2 = localBufferedReader.readLine();
88 |
89 | if (str2 != null) {
90 | arrayOfString = str2.split("\\s+");
91 | initial_memory = Integer.valueOf(arrayOfString[1]);
92 | }
93 | localBufferedReader.close();
94 |
95 | } catch (IOException e) {
96 | Log.e(TAG, "getTotalMemory exception = ", e);
97 | } finally {
98 | if (localFileReader != null) {
99 | try {
100 | localFileReader.close();
101 | } catch (IOException e) {
102 | Log.e(TAG, "close localFileReader exception = ", e);
103 | }
104 | }
105 | }
106 | sTotalMemo = initial_memory;
107 | }
108 | return sTotalMemo;
109 | }
110 | }
--------------------------------------------------------------------------------
/blockcanary-sample/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
11 |
12 |
13 |
21 |
22 |
23 |
24 |
30 |
31 |
36 |
37 |
38 |
49 |
50 |
61 |
62 |
63 |
68 |
69 |
80 |
81 |
92 |
93 |
94 |
95 |
96 |
97 |
105 |
106 |
107 |
--------------------------------------------------------------------------------
/blockcanary-sample/src/main/java/com/example/blockcanary/DemoFragment.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 MarkZhai (http://zhaiyifan.cn).
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.blockcanary;
17 |
18 | import android.os.Bundle;
19 | import android.support.annotation.Nullable;
20 | import android.support.v4.app.Fragment;
21 | import android.util.Log;
22 | import android.view.LayoutInflater;
23 | import android.view.View;
24 | import android.view.ViewGroup;
25 | import android.widget.Button;
26 |
27 | import java.io.FileInputStream;
28 | import java.io.IOException;
29 |
30 | public class DemoFragment extends Fragment implements View.OnClickListener {
31 |
32 | private static final String DEMO_FRAGMENT = "DemoFragment";
33 |
34 | public static DemoFragment newInstance() {
35 | return new DemoFragment();
36 | }
37 |
38 | @Override
39 | public void onCreate(final Bundle savedInstanceState) {
40 | super.onCreate(savedInstanceState);
41 | }
42 |
43 | @Nullable
44 | @Override
45 | public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
46 | return inflater.inflate(R.layout.activity_main, null);
47 | }
48 |
49 | @Override
50 | public void onViewCreated(final View view, @Nullable final Bundle savedInstanceState) {
51 | super.onViewCreated(view, savedInstanceState);
52 | Button button1 = (Button) view.findViewById(R.id.button1);
53 | Button button2 = (Button) view.findViewById(R.id.button2);
54 | Button button3 = (Button) view.findViewById(R.id.button3);
55 |
56 | button1.setOnClickListener(this);
57 | button2.setOnClickListener(this);
58 | button3.setOnClickListener(this);
59 | }
60 |
61 | @Override
62 | public void onDestroyView() {
63 | super.onDestroyView();
64 | }
65 |
66 | @Override
67 | public void onActivityCreated(@Nullable final Bundle savedInstanceState) {
68 | super.onActivityCreated(savedInstanceState);
69 | }
70 |
71 | @Override
72 | public void onClick(View v) {
73 | switch (v.getId()) {
74 | case R.id.button1:
75 | try {
76 | Thread.sleep(2000);
77 | } catch (InterruptedException e) {
78 | e.printStackTrace();
79 | Log.e(DEMO_FRAGMENT, "onClick of R.id.button1: ", e);
80 | }
81 | break;
82 | case R.id.button2:
83 | for (int i = 0; i < 100; ++i) {
84 | readFile();
85 | }
86 | break;
87 | case R.id.button3:
88 | double result = compute();
89 | System.out.println(result);
90 | break;
91 | default:
92 | break;
93 | }
94 | }
95 |
96 | private static double compute() {
97 | double result = 0;
98 | for (int i = 0; i < 1000000; ++i) {
99 | result += Math.acos(Math.cos(i));
100 | result -= Math.asin(Math.sin(i));
101 | }
102 | return result;
103 | }
104 |
105 | private static void readFile() {
106 | FileInputStream reader = null;
107 | try {
108 | reader = new FileInputStream("/proc/stat");
109 | while (reader.read() != -1) ;
110 | } catch (IOException e) {
111 | Log.e(DEMO_FRAGMENT, "readFile: /proc/stat", e);
112 | } finally {
113 | if (reader != null) {
114 | try {
115 | reader.close();
116 | } catch (IOException e) {
117 | Log.e(DEMO_FRAGMENT, " on close reader ", e);
118 | }
119 | }
120 | }
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/blockcanary-android/src/main/java/com/github/moduth/blockcanary/ui/DisplayConnectorView.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.moduth.blockcanary.ui;
17 |
18 | import android.content.Context;
19 | import android.graphics.Bitmap;
20 | import android.graphics.Canvas;
21 | import android.graphics.Color;
22 | import android.graphics.Paint;
23 | import android.util.AttributeSet;
24 | import android.view.View;
25 |
26 | import static android.graphics.Bitmap.Config.ARGB_8888;
27 |
28 | public final class DisplayConnectorView extends View {
29 |
30 | private static final Paint iconPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
31 | private static final Paint rootPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
32 | private static final Paint leakPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
33 | private static final Paint clearPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
34 |
35 | static {
36 | iconPaint.setColor(BlockCanaryUi.LIGHT_GREY);
37 | rootPaint.setColor(BlockCanaryUi.ROOT_COLOR);
38 | leakPaint.setColor(BlockCanaryUi.LEAK_COLOR);
39 | clearPaint.setColor(Color.TRANSPARENT);
40 | clearPaint.setXfermode(BlockCanaryUi.CLEAR_XFER_MODE);
41 | }
42 |
43 | public enum Type {
44 | START, NODE, END
45 | }
46 |
47 | private Type type;
48 | private Bitmap cache;
49 |
50 | public DisplayConnectorView(Context context, AttributeSet attrs) {
51 | super(context, attrs);
52 |
53 | type = Type.NODE;
54 | }
55 |
56 | @SuppressWarnings("SuspiciousNameCombination")
57 | @Override
58 | protected void onDraw(Canvas canvas) {
59 | int width = getWidth();
60 | int height = getHeight();
61 |
62 | if (cache != null && (cache.getWidth() != width || cache.getHeight() != height)) {
63 | cache.recycle();
64 | cache = null;
65 | }
66 |
67 | if (cache == null) {
68 | cache = Bitmap.createBitmap(width, height, ARGB_8888);
69 |
70 | Canvas cacheCanvas = new Canvas(cache);
71 |
72 | float halfWidth = width / 2f;
73 | float halfHeight = height / 2f;
74 | float thirdWidth = width / 3f;
75 |
76 | float strokeSize = BlockCanaryUi.dpToPixel(4f, getResources());
77 |
78 | iconPaint.setStrokeWidth(strokeSize);
79 | rootPaint.setStrokeWidth(strokeSize);
80 |
81 | switch (type) {
82 | case NODE:
83 | cacheCanvas.drawLine(halfWidth, 0, halfWidth, height, iconPaint);
84 | cacheCanvas.drawCircle(halfWidth, halfHeight, halfWidth, iconPaint);
85 | cacheCanvas.drawCircle(halfWidth, halfHeight, thirdWidth, clearPaint);
86 | break;
87 | case START:
88 | float radiusClear = halfWidth - strokeSize / 2f;
89 | cacheCanvas.drawRect(0, 0, width, radiusClear, rootPaint);
90 | cacheCanvas.drawCircle(0, radiusClear, radiusClear, clearPaint);
91 | cacheCanvas.drawCircle(width, radiusClear, radiusClear, clearPaint);
92 | cacheCanvas.drawLine(halfWidth, 0, halfWidth, halfHeight, rootPaint);
93 | cacheCanvas.drawLine(halfWidth, halfHeight, halfWidth, height, iconPaint);
94 | cacheCanvas.drawCircle(halfWidth, halfHeight, halfWidth, iconPaint);
95 | cacheCanvas.drawCircle(halfWidth, halfHeight, thirdWidth, clearPaint);
96 | break;
97 | default:
98 | cacheCanvas.drawLine(halfWidth, 0, halfWidth, halfHeight, iconPaint);
99 | cacheCanvas.drawCircle(halfWidth, halfHeight, thirdWidth, leakPaint);
100 | break;
101 | }
102 | }
103 | canvas.drawBitmap(cache, 0, 0, null);
104 | }
105 |
106 | public void setType(Type type) {
107 | if (type != this.type) {
108 | this.type = type;
109 | if (cache != null) {
110 | cache.recycle();
111 | cache = null;
112 | }
113 | invalidate();
114 | }
115 | }
116 | }
--------------------------------------------------------------------------------
/blockcanary-android/src/main/java/com/github/moduth/blockcanary/DisplayService.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.moduth.blockcanary;
17 |
18 | import android.annotation.TargetApi;
19 | import android.app.Notification;
20 | import android.app.NotificationChannel;
21 | import android.app.NotificationManager;
22 | import android.app.PendingIntent;
23 | import android.content.Context;
24 | import android.content.Intent;
25 | import android.util.Log;
26 |
27 | import com.github.moduth.blockcanary.internal.BlockInfo;
28 | import com.github.moduth.blockcanary.ui.DisplayActivity;
29 |
30 | import java.lang.reflect.InvocationTargetException;
31 | import java.lang.reflect.Method;
32 |
33 | import static android.app.PendingIntent.FLAG_UPDATE_CURRENT;
34 | import static android.os.Build.VERSION.SDK_INT;
35 | import static android.os.Build.VERSION_CODES.HONEYCOMB;
36 | import static android.os.Build.VERSION_CODES.JELLY_BEAN;
37 | import static android.os.Build.VERSION_CODES.O;
38 |
39 | final class DisplayService implements BlockInterceptor {
40 | public static final String CHANNEL_NAME = "BLOCK_CANARY";
41 | private static final String TAG = "DisplayService";
42 |
43 | @Override
44 | public void onBlock(Context context, BlockInfo blockInfo) {
45 | Intent intent = new Intent(context, DisplayActivity.class);
46 | intent.putExtra("show_latest", blockInfo.timeStart);
47 | intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
48 | PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intent, FLAG_UPDATE_CURRENT);
49 | String contentTitle = context.getString(R.string.block_canary_class_has_blocked, blockInfo.timeStart);
50 | String contentText = context.getString(R.string.block_canary_notification_message);
51 | show(context, contentTitle, contentText, pendingIntent);
52 | }
53 |
54 | @TargetApi(HONEYCOMB)
55 | private void show(Context context, String contentTitle, String contentText, PendingIntent pendingIntent) {
56 | NotificationManager notificationManager = (NotificationManager)
57 | context.getSystemService(Context.NOTIFICATION_SERVICE);
58 |
59 | Notification notification;
60 | if (SDK_INT < HONEYCOMB) {
61 | notification = new Notification();
62 | notification.icon = R.drawable.block_canary_notification;
63 | notification.when = System.currentTimeMillis();
64 | notification.flags |= Notification.FLAG_AUTO_CANCEL;
65 | notification.defaults = Notification.DEFAULT_SOUND;
66 | try {
67 | Method deprecatedMethod = notification.getClass().getMethod("setLatestEventInfo", Context.class, CharSequence.class, CharSequence.class, PendingIntent.class);
68 | deprecatedMethod.invoke(notification, context, contentTitle, contentText, pendingIntent);
69 | } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException
70 | | InvocationTargetException e) {
71 | Log.w(TAG, "Method not found", e);
72 | }
73 | } else {
74 | Notification.Builder builder = new Notification.Builder(context)
75 | .setSmallIcon(R.drawable.block_canary_notification)
76 | .setWhen(System.currentTimeMillis())
77 | .setContentTitle(contentTitle)
78 | .setContentText(contentText)
79 | .setAutoCancel(true)
80 | .setContentIntent(pendingIntent)
81 | .setDefaults(Notification.DEFAULT_SOUND);
82 | if (SDK_INT >= O) {
83 | NotificationChannel notificationChannel = notificationManager.getNotificationChannel(CHANNEL_NAME);
84 | if (notificationChannel == null) {
85 | notificationChannel = new NotificationChannel(CHANNEL_NAME, CHANNEL_NAME,NotificationManager.IMPORTANCE_DEFAULT);
86 | notificationManager.createNotificationChannel(notificationChannel);
87 | }
88 | builder.setChannelId(CHANNEL_NAME);
89 | }
90 | notification = builder.build();
91 | }
92 | notificationManager.notify(0xDEAFBEEF, notification);
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/LogWriter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 MarkZhai (http://zhaiyifan.cn).
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.moduth.blockcanary;
17 |
18 | import android.util.Log;
19 |
20 | import com.github.moduth.blockcanary.internal.BlockInfo;
21 |
22 | import java.io.BufferedWriter;
23 | import java.io.File;
24 | import java.io.FileOutputStream;
25 | import java.io.OutputStreamWriter;
26 | import java.text.SimpleDateFormat;
27 | import java.util.Locale;
28 |
29 | /**
30 | * Log writer which runs in standalone thread.
31 | */
32 | public class LogWriter {
33 |
34 | private static final String TAG = "LogWriter";
35 |
36 | private static final Object SAVE_DELETE_LOCK = new Object();
37 | private static final SimpleDateFormat FILE_NAME_FORMATTER
38 | = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss.SSS", Locale.US);
39 | private static final SimpleDateFormat TIME_FORMATTER
40 | = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
41 | private static final long OBSOLETE_DURATION = 2 * 24 * 3600 * 1000L;
42 |
43 | private LogWriter() {
44 | throw new InstantiationError("Must not instantiate this class");
45 | }
46 |
47 | /**
48 | * Save log to file
49 | *
50 | * @param str block info string
51 | * @return log file path
52 | */
53 | public static String save(String str) {
54 | String path;
55 | synchronized (SAVE_DELETE_LOCK) {
56 | path = save("looper", str);
57 | }
58 | return path;
59 | }
60 |
61 | /**
62 | * Delete obsolete log files, which is by default 2 days.
63 | */
64 | public static void cleanObsolete() {
65 | HandlerThreadFactory.getWriteLogThreadHandler().post(new Runnable() {
66 | @Override
67 | public void run() {
68 | long now = System.currentTimeMillis();
69 | File[] f = BlockCanaryInternals.getLogFiles();
70 | if (f != null && f.length > 0) {
71 | synchronized (SAVE_DELETE_LOCK) {
72 | for (File aF : f) {
73 | if (now - aF.lastModified() > OBSOLETE_DURATION) {
74 | aF.delete();
75 | }
76 | }
77 | }
78 | }
79 | }
80 | });
81 | }
82 |
83 | public static void deleteAll() {
84 | synchronized (SAVE_DELETE_LOCK) {
85 | try {
86 | File[] files = BlockCanaryInternals.getLogFiles();
87 | if (files != null && files.length > 0) {
88 | for (File file : files) {
89 | file.delete();
90 | }
91 | }
92 | } catch (Throwable e) {
93 | Log.e(TAG, "deleteAll: ", e);
94 | }
95 | }
96 | }
97 |
98 | private static String save(String logFileName, String str) {
99 | String path = "";
100 | BufferedWriter writer = null;
101 | try {
102 | File file = BlockCanaryInternals.detectedBlockDirectory();
103 | long time = System.currentTimeMillis();
104 | path = file.getAbsolutePath() + "/"
105 | + logFileName + "-"
106 | + FILE_NAME_FORMATTER.format(time) + ".log";
107 |
108 | OutputStreamWriter out =
109 | new OutputStreamWriter(new FileOutputStream(path, true), "UTF-8");
110 |
111 | writer = new BufferedWriter(out);
112 |
113 | writer.write(BlockInfo.SEPARATOR);
114 | writer.write("**********************");
115 | writer.write(BlockInfo.SEPARATOR);
116 | writer.write(TIME_FORMATTER.format(time) + "(write log time)");
117 | writer.write(BlockInfo.SEPARATOR);
118 | writer.write(BlockInfo.SEPARATOR);
119 | writer.write(str);
120 | writer.write(BlockInfo.SEPARATOR);
121 |
122 | writer.flush();
123 | writer.close();
124 | writer = null;
125 |
126 | } catch (Throwable t) {
127 | Log.e(TAG, "save: ", t);
128 | } finally {
129 | try {
130 | if (writer != null) {
131 | writer.close();
132 | }
133 | } catch (Exception e) {
134 | Log.e(TAG, "save: ", e);
135 | }
136 | }
137 | return path;
138 | }
139 |
140 | public static File generateTempZip(String filename) {
141 | return new File(BlockCanaryInternals.getPath() + "/" + filename + ".zip");
142 | }
143 | }
144 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/blockcanary-android/src/main/java/com/github/moduth/blockcanary/ui/BlockInfoEx.java:
--------------------------------------------------------------------------------
1 | package com.github.moduth.blockcanary.ui;
2 |
3 | import android.util.Log;
4 |
5 | import com.github.moduth.blockcanary.internal.BlockInfo;
6 |
7 | import java.io.BufferedReader;
8 | import java.io.File;
9 | import java.io.FileInputStream;
10 | import java.io.InputStreamReader;
11 |
12 | final class BlockInfoEx extends BlockInfo {
13 |
14 | private static final String TAG = "BlockInfoEx";
15 |
16 | public File logFile;
17 | public String concernStackString;
18 |
19 | /**
20 | * Create {@link BlockInfoEx} from saved log file.
21 | *
22 | * @param file looper log file
23 | * @return LooperLog created from log file
24 | */
25 | public static BlockInfoEx newInstance(File file) {
26 | BlockInfoEx blockInfo = new BlockInfoEx();
27 | blockInfo.logFile = file;
28 |
29 | BufferedReader reader = null;
30 | try {
31 | InputStreamReader in = new InputStreamReader(new FileInputStream(file), "UTF-8");
32 |
33 | reader = new BufferedReader(in);
34 | for (String line = reader.readLine(); line != null; line = reader.readLine()) {
35 | if (line.startsWith(KEY_QUA)) {
36 | blockInfo.qualifier = line.split(KV)[1];
37 | } else if (line.startsWith(KEY_MODEL)) {
38 | blockInfo.model = line.split(KV)[1];
39 | } else if (line.startsWith(KEY_API)) {
40 | blockInfo.apiLevel = line.split(KV)[1];
41 | } else if (line.startsWith(KEY_IMEI)) {
42 | blockInfo.imei = line.split(KV)[1];
43 | } else if (line.startsWith(KEY_CPU_CORE)) {
44 | blockInfo.cpuCoreNum = Integer.parseInt(line.split(KV)[1]);
45 | } else if (line.startsWith(KEY_UID)) {
46 | blockInfo.uid = line.split(KV)[1];
47 | } else if (line.startsWith(KEY_TIME_COST_START)) {
48 | blockInfo.timeStart = line.split(KV)[1];
49 | } else if (line.startsWith(KEY_TIME_COST_END)) {
50 | blockInfo.timeEnd = line.split(KV)[1];
51 | } else if (line.startsWith(KEY_TIME_COST)) {
52 | blockInfo.timeCost = Long.parseLong(line.split(KV)[1]);
53 | } else if (line.startsWith(KEY_THREAD_TIME_COST)) {
54 | blockInfo.threadTimeCost = Long.parseLong(line.split(KV)[1]);
55 | } else if (line.startsWith(KEY_PROCESS)) {
56 | blockInfo.processName = line.split(KV)[1];
57 | } else if (line.startsWith(KEY_VERSION_NAME)) {
58 | blockInfo.versionName = line.split(KV)[1];
59 | } else if (line.startsWith(KEY_VERSION_CODE)) {
60 | blockInfo.versionCode = Integer.parseInt(line.split(KV)[1]);
61 | } else if (line.startsWith(KEY_NETWORK)) {
62 | blockInfo.network = line.split(KV)[1];
63 | } else if (line.startsWith(KEY_TOTAL_MEMORY)) {
64 | blockInfo.totalMemory = line.split(KV)[1];
65 | } else if (line.startsWith(KEY_FREE_MEMORY)) {
66 | blockInfo.freeMemory = line.split(KV)[1];
67 | } else if (line.startsWith(KEY_IS_BACKGROUND)) {
68 | blockInfo.isBackground = Boolean.parseBoolean(line.split(KV)[1]);
69 | } else if (line.startsWith(KEY_CPU_BUSY)) {
70 | blockInfo.cpuBusy = Boolean.parseBoolean(line.split(KV)[1]);
71 | } else if (line.startsWith(KEY_CPU_RATE)) {
72 | String[] split = line.split(KV);
73 | if (split.length > 1) {
74 | StringBuilder cpuRateSb = new StringBuilder(split[1]);
75 | cpuRateSb.append(line.split(KV)[1]).append(SEPARATOR);
76 | line = reader.readLine();
77 |
78 | // read until SEPARATOR appears
79 | while (line != null) {
80 | if (!line.equals("")) {
81 | cpuRateSb.append(line).append(SEPARATOR);
82 | } else {
83 | break;
84 | }
85 | line = reader.readLine();
86 | }
87 | blockInfo.cpuRateInfo = cpuRateSb.toString();
88 | }
89 | } else if (line.startsWith(KEY_STACK)) {
90 | StringBuilder stackSb = new StringBuilder(line.split(KV)[1]);
91 | line = reader.readLine();
92 |
93 | // read until file ends
94 | while (line != null) {
95 | if (!line.equals("")) {
96 | stackSb.append(line).append(SEPARATOR);
97 | } else if (stackSb.length() > 0) {
98 | // ignore continual blank lines
99 | blockInfo.threadStackEntries.add(stackSb.toString());
100 | stackSb = new StringBuilder();
101 | }
102 | line = reader.readLine();
103 | }
104 | }
105 | }
106 | reader.close();
107 | reader = null;
108 | } catch (Throwable t) {
109 | Log.e(TAG, NEW_INSTANCE_METHOD, t);
110 | } finally {
111 | try {
112 | if (reader != null) {
113 | reader.close();
114 | }
115 | } catch (Exception e) {
116 | Log.e(TAG, NEW_INSTANCE_METHOD, e);
117 | }
118 | }
119 | blockInfo.flushString();
120 | return blockInfo;
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/BlockCanaryInternals.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 MarkZhai (http://zhaiyifan.cn).
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.moduth.blockcanary;
17 |
18 | import android.os.Environment;
19 | import android.os.Looper;
20 |
21 | import com.github.moduth.blockcanary.internal.BackgroundUtil;
22 | import com.github.moduth.blockcanary.internal.BlockInfo;
23 |
24 | import java.io.File;
25 | import java.io.FilenameFilter;
26 | import java.util.ArrayList;
27 | import java.util.LinkedList;
28 | import java.util.List;
29 |
30 | public final class BlockCanaryInternals {
31 |
32 | LooperMonitor monitor;
33 | StackSampler stackSampler;
34 | CpuSampler cpuSampler;
35 |
36 | private static BlockCanaryInternals sInstance;
37 | private static BlockCanaryContext sContext;
38 |
39 | private List mInterceptorChain = new LinkedList<>();
40 |
41 | public BlockCanaryInternals() {
42 |
43 | stackSampler = new StackSampler(
44 | Looper.getMainLooper().getThread(),
45 | sContext.provideDumpInterval());
46 |
47 | cpuSampler = new CpuSampler(sContext.provideDumpInterval());
48 |
49 | setMonitor(new LooperMonitor(new LooperMonitor.BlockListener() {
50 |
51 | @Override
52 | public void onBlockEvent(long realTimeStart, long realTimeEnd,
53 | long threadTimeStart, long threadTimeEnd) {
54 | // Get recent thread-stack entries and cpu usage
55 | ArrayList threadStackEntries = stackSampler
56 | .getThreadStackEntries(realTimeStart, realTimeEnd);
57 | if (!threadStackEntries.isEmpty()) {
58 | BlockInfo blockInfo = BlockInfo.newInstance()
59 | .setMainThreadTimeCost(realTimeStart, realTimeEnd, threadTimeStart, threadTimeEnd)
60 | .setCpuBusyFlag(cpuSampler.isCpuBusy(realTimeStart, realTimeEnd))
61 | .setRecentCpuRate(cpuSampler.getCpuRateInfo())
62 | .setThreadStackEntries(threadStackEntries)
63 | .setAppBackground(BackgroundUtil.isBackground(sContext.provideContext()))
64 | .flushString();
65 | LogWriter.save(blockInfo.toString());
66 |
67 | if (mInterceptorChain.size() != 0) {
68 | for (BlockInterceptor interceptor : mInterceptorChain) {
69 | interceptor.onBlock(getContext().provideContext(), blockInfo);
70 | }
71 | }
72 | }
73 | }
74 | }, getContext().provideBlockThreshold(), getContext().stopWhenDebugging()));
75 |
76 | LogWriter.cleanObsolete();
77 | }
78 |
79 | /**
80 | * Get BlockCanaryInternals singleton
81 | *
82 | * @return BlockCanaryInternals instance
83 | */
84 | static BlockCanaryInternals getInstance() {
85 | if (sInstance == null) {
86 | synchronized (BlockCanaryInternals.class) {
87 | if (sInstance == null) {
88 | sInstance = new BlockCanaryInternals();
89 | }
90 | }
91 | }
92 | return sInstance;
93 | }
94 |
95 | /**
96 | * set {@link BlockCanaryContext} implementation
97 | *
98 | * @param context context
99 | */
100 | public static void setContext(BlockCanaryContext context) {
101 | sContext = context;
102 | }
103 |
104 | public static BlockCanaryContext getContext() {
105 | return sContext;
106 | }
107 |
108 | void addBlockInterceptor(BlockInterceptor blockInterceptor) {
109 | mInterceptorChain.add(blockInterceptor);
110 | }
111 |
112 | private void setMonitor(LooperMonitor looperPrinter) {
113 | monitor = looperPrinter;
114 | }
115 |
116 | long getSampleDelay() {
117 | return (long) (BlockCanaryInternals.getContext().provideBlockThreshold() * 0.8f);
118 | }
119 |
120 | static String getPath() {
121 | String state = Environment.getExternalStorageState();
122 | String logPath = BlockCanaryInternals.getContext()
123 | == null ? "" : BlockCanaryInternals.getContext().providePath();
124 |
125 | if (Environment.MEDIA_MOUNTED.equals(state)
126 | && Environment.getExternalStorageDirectory().canWrite()) {
127 | return Environment.getExternalStorageDirectory().getPath() + logPath;
128 | }
129 | return getContext().provideContext().getFilesDir() + BlockCanaryInternals.getContext().providePath();
130 | }
131 |
132 | static File detectedBlockDirectory() {
133 | File directory = new File(getPath());
134 | if (!directory.exists()) {
135 | directory.mkdirs();
136 | }
137 | return directory;
138 | }
139 |
140 | public static File[] getLogFiles() {
141 | File f = detectedBlockDirectory();
142 | if (f.exists() && f.isDirectory()) {
143 | return f.listFiles(new BlockLogFileFilter());
144 | }
145 | return null;
146 | }
147 |
148 | private static class BlockLogFileFilter implements FilenameFilter {
149 |
150 | private String TYPE = ".log";
151 |
152 | BlockLogFileFilter() {
153 |
154 | }
155 |
156 | @Override
157 | public boolean accept(File dir, String filename) {
158 | return filename.endsWith(TYPE);
159 | }
160 | }
161 | }
162 |
--------------------------------------------------------------------------------
/blockcanary-android/src/main/java/com/github/moduth/blockcanary/BlockCanary.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 MarkZhai (http://zhaiyifan.cn).
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.moduth.blockcanary;
17 |
18 | import android.content.ComponentName;
19 | import android.content.Context;
20 | import android.content.pm.PackageManager;
21 | import android.os.Looper;
22 | import android.preference.PreferenceManager;
23 |
24 | import com.github.moduth.blockcanary.ui.DisplayActivity;
25 |
26 | import java.util.concurrent.Executor;
27 | import java.util.concurrent.Executors;
28 |
29 | import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
30 | import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31 | import static android.content.pm.PackageManager.DONT_KILL_APP;
32 |
33 | public final class BlockCanary {
34 |
35 | private static final String TAG = "BlockCanary";
36 |
37 | private static BlockCanary sInstance;
38 | private BlockCanaryInternals mBlockCanaryCore;
39 | private boolean mMonitorStarted = false;
40 |
41 | private BlockCanary() {
42 | BlockCanaryInternals.setContext(BlockCanaryContext.get());
43 | mBlockCanaryCore = BlockCanaryInternals.getInstance();
44 | mBlockCanaryCore.addBlockInterceptor(BlockCanaryContext.get());
45 | if (!BlockCanaryContext.get().displayNotification()) {
46 | return;
47 | }
48 | mBlockCanaryCore.addBlockInterceptor(new DisplayService());
49 |
50 | }
51 |
52 | /**
53 | * Install {@link BlockCanary}
54 | *
55 | * @param context Application context
56 | * @param blockCanaryContext BlockCanary context
57 | * @return {@link BlockCanary}
58 | */
59 | public static BlockCanary install(Context context, BlockCanaryContext blockCanaryContext) {
60 | BlockCanaryContext.init(context, blockCanaryContext);
61 | setEnabled(context, DisplayActivity.class, BlockCanaryContext.get().displayNotification());
62 | return get();
63 | }
64 |
65 | /**
66 | * Get {@link BlockCanary} singleton.
67 | *
68 | * @return {@link BlockCanary} instance
69 | */
70 | public static BlockCanary get() {
71 | if (sInstance == null) {
72 | synchronized (BlockCanary.class) {
73 | if (sInstance == null) {
74 | sInstance = new BlockCanary();
75 | }
76 | }
77 | }
78 | return sInstance;
79 | }
80 |
81 | /**
82 | * Start monitoring.
83 | */
84 | public void start() {
85 | if (!mMonitorStarted) {
86 | mMonitorStarted = true;
87 | Looper.getMainLooper().setMessageLogging(mBlockCanaryCore.monitor);
88 | }
89 | }
90 |
91 | /**
92 | * Stop monitoring.
93 | */
94 | public void stop() {
95 | if (mMonitorStarted) {
96 | mMonitorStarted = false;
97 | Looper.getMainLooper().setMessageLogging(null);
98 | mBlockCanaryCore.stackSampler.stop();
99 | mBlockCanaryCore.cpuSampler.stop();
100 | }
101 | }
102 |
103 | /**
104 | * Zip and upload log files, will user context's zip and log implementation.
105 | */
106 | public void upload() {
107 | Uploader.zipAndUpload();
108 | }
109 |
110 | /**
111 | * Record monitor start time to preference, you may use it when after push which tells start
112 | * BlockCanary.
113 | */
114 | public void recordStartTime() {
115 | PreferenceManager.getDefaultSharedPreferences(BlockCanaryContext.get().provideContext())
116 | .edit()
117 | .putLong("BlockCanary_StartTime", System.currentTimeMillis())
118 | .commit();
119 | }
120 |
121 | /**
122 | * Is monitor duration end, compute from recordStartTime end provideMonitorDuration.
123 | *
124 | * @return true if ended
125 | */
126 | public boolean isMonitorDurationEnd() {
127 | long startTime =
128 | PreferenceManager.getDefaultSharedPreferences(BlockCanaryContext.get().provideContext())
129 | .getLong("BlockCanary_StartTime", 0);
130 | return startTime != 0 && System.currentTimeMillis() - startTime >
131 | BlockCanaryContext.get().provideMonitorDuration() * 3600 * 1000;
132 | }
133 |
134 | // these lines are originally copied from LeakCanary: Copyright (C) 2015 Square, Inc.
135 | private static final Executor fileIoExecutor = newSingleThreadExecutor("File-IO");
136 |
137 | private static void setEnabledBlocking(Context appContext,
138 | Class> componentClass,
139 | boolean enabled) {
140 | ComponentName component = new ComponentName(appContext, componentClass);
141 | PackageManager packageManager = appContext.getPackageManager();
142 | int newState = enabled ? COMPONENT_ENABLED_STATE_ENABLED : COMPONENT_ENABLED_STATE_DISABLED;
143 | // Blocks on IPC.
144 | packageManager.setComponentEnabledSetting(component, newState, DONT_KILL_APP);
145 | }
146 | // end of lines copied from LeakCanary
147 |
148 | private static void executeOnFileIoThread(Runnable runnable) {
149 | fileIoExecutor.execute(runnable);
150 | }
151 |
152 | private static Executor newSingleThreadExecutor(String threadName) {
153 | return Executors.newSingleThreadExecutor(new SingleThreadFactory(threadName));
154 | }
155 |
156 | private static void setEnabled(Context context,
157 | final Class> componentClass,
158 | final boolean enabled) {
159 | final Context appContext = context.getApplicationContext();
160 | executeOnFileIoThread(new Runnable() {
161 | @Override
162 | public void run() {
163 | setEnabledBlocking(appContext, componentClass, enabled);
164 | }
165 | });
166 | }
167 | }
168 |
--------------------------------------------------------------------------------
/blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/BlockCanaryContext.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 MarkZhai (http://zhaiyifan.cn).
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.moduth.blockcanary;
17 |
18 | import android.content.Context;
19 |
20 | import com.github.moduth.blockcanary.internal.BlockInfo;
21 |
22 | import java.io.File;
23 | import java.util.LinkedList;
24 | import java.util.List;
25 |
26 | /**
27 | * User should provide a real implementation of this class to use BlockCanary.
28 | */
29 | public class BlockCanaryContext implements BlockInterceptor {
30 |
31 | private static Context sApplicationContext;
32 | private static BlockCanaryContext sInstance = null;
33 |
34 | public BlockCanaryContext() {
35 | }
36 |
37 | static void init(Context context, BlockCanaryContext blockCanaryContext) {
38 | sApplicationContext = context;
39 | sInstance = blockCanaryContext;
40 | }
41 |
42 | public static BlockCanaryContext get() {
43 | if (sInstance == null) {
44 | throw new RuntimeException("BlockCanaryContext null");
45 | } else {
46 | return sInstance;
47 | }
48 | }
49 |
50 | /**
51 | * Provide application context.
52 | */
53 | public Context provideContext() {
54 | return sApplicationContext;
55 | }
56 |
57 | /**
58 | * Implement in your project.
59 | *
60 | * @return Qualifier which can specify this installation, like version + flavor.
61 | */
62 | public String provideQualifier() {
63 | return "unknown";
64 | }
65 |
66 | /**
67 | * Implement in your project.
68 | *
69 | * @return user id
70 | */
71 | public String provideUid() {
72 | return "uid";
73 | }
74 |
75 | /**
76 | * Network type
77 | *
78 | * @return {@link String} like 2G, 3G, 4G, wifi, etc.
79 | */
80 | public String provideNetworkType() {
81 | return "unknown";
82 | }
83 |
84 | /**
85 | * Config monitor duration, after this time BlockCanary will stop, use
86 | * with {@code BlockCanary}'s isMonitorDurationEnd
87 | *
88 | * @return monitor last duration (in hour)
89 | */
90 | public int provideMonitorDuration() {
91 | return -1;
92 | }
93 |
94 | /**
95 | * Config block threshold (in millis), dispatch over this duration is regarded as a BLOCK. You may set it
96 | * from performance of device.
97 | *
98 | * @return threshold in mills
99 | */
100 | public int provideBlockThreshold() {
101 | return 1000;
102 | }
103 |
104 | /**
105 | * Thread stack dump interval, use when block happens, BlockCanary will dump on main thread
106 | * stack according to current sample cycle.
107 | *
108 | * Because the implementation mechanism of Looper, real dump interval would be longer than
109 | * the period specified here (especially when cpu is busier).
110 | *
111 | *
112 | * @return dump interval (in millis)
113 | */
114 | public int provideDumpInterval() {
115 | return provideBlockThreshold();
116 | }
117 |
118 | /**
119 | * Path to save log, like "/blockcanary/", will save to sdcard if can.
120 | *
121 | * @return path of log files
122 | */
123 | public String providePath() {
124 | return "/blockcanary/";
125 | }
126 |
127 | /**
128 | * If need notification to notice block.
129 | *
130 | * @return true if need, else if not need.
131 | */
132 | public boolean displayNotification() {
133 | return true;
134 | }
135 |
136 | /**
137 | * Implement in your project, bundle files into a zip file.
138 | *
139 | * @param src files before compress
140 | * @param dest files compressed
141 | * @return true if compression is successful
142 | */
143 | public boolean zip(File[] src, File dest) {
144 | return false;
145 | }
146 |
147 | /**
148 | * Implement in your project, bundled log files.
149 | *
150 | * @param zippedFile zipped file
151 | */
152 | public void upload(File zippedFile) {
153 | throw new UnsupportedOperationException();
154 | }
155 |
156 | /**
157 | * Packages that developer concern, by default it uses process name,
158 | * put high priority one in pre-order.
159 | *
160 | * @return null if simply concern only package with process name.
161 | */
162 | public List concernPackages() {
163 | return null;
164 | }
165 |
166 | /**
167 | * Filter stack without any in concern package, used with @{code concernPackages}.
168 | *
169 | * @return true if filter, false it not.
170 | */
171 | public boolean filterNonConcernStack() {
172 | return false;
173 | }
174 |
175 | /**
176 | * Provide white list, entry in white list will not be shown in ui list.
177 | *
178 | * @return return null if you don't need white-list filter.
179 | */
180 | public List provideWhiteList() {
181 | LinkedList whiteList = new LinkedList<>();
182 | whiteList.add("org.chromium");
183 | return whiteList;
184 | }
185 |
186 | /**
187 | * Whether to delete files whose stack is in white list, used with white-list.
188 | *
189 | * @return true if delete, false it not.
190 | */
191 | public boolean deleteFilesInWhiteList() {
192 | return true;
193 | }
194 |
195 | /**
196 | * Block interceptor, developer may provide their own actions.
197 | */
198 | @Override
199 | public void onBlock(Context context, BlockInfo blockInfo) {
200 |
201 | }
202 |
203 | /**
204 | * Whether to stop monitoring when in debug mode.
205 | *
206 | * @return true if stop, false otherwise
207 | */
208 | public boolean stopWhenDebugging() {
209 | return true;
210 | }
211 |
212 |
213 | /**
214 | * Default method will collect several messages when detect block what we not need
215 | *
216 | * @return true if you only need one message, false otherwise
217 | */
218 | public boolean reportRecentOneMessage() {
219 | return false;
220 | }
221 | }
--------------------------------------------------------------------------------
/blockcanary-android/src/main/java/com/github/moduth/blockcanary/ui/DetailAdapter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.moduth.blockcanary.ui;
17 |
18 | import android.content.Context;
19 | import android.text.Html;
20 | import android.view.LayoutInflater;
21 | import android.view.View;
22 | import android.view.ViewGroup;
23 | import android.widget.BaseAdapter;
24 | import android.widget.TextView;
25 |
26 | import com.github.moduth.blockcanary.R;
27 | import com.github.moduth.blockcanary.internal.BlockInfo;
28 |
29 | import java.util.Arrays;
30 |
31 | final class DetailAdapter extends BaseAdapter {
32 |
33 | private static final int TOP_ROW = 0;
34 | private static final int NORMAL_ROW = 1;
35 |
36 | private boolean[] mFoldings = new boolean[0];
37 |
38 | private BlockInfo mBlockInfo;
39 |
40 | private static final int POSITION_BASIC = 1;
41 | private static final int POSITION_TIME = 2;
42 | private static final int POSITION_CPU = 3;
43 | private static final int POSITION_THREAD_STACK = 4;
44 |
45 | @Override
46 | public View getView(int position, View convertView, ViewGroup parent) {
47 | Context context = parent.getContext();
48 | if (getItemViewType(position) == TOP_ROW) {
49 | if (convertView == null) {
50 | convertView =
51 | LayoutInflater.from(context).inflate(R.layout.block_canary_ref_top_row, parent, false);
52 | }
53 | TextView textView = findById(convertView, R.id.__leak_canary_row_text);
54 | textView.setText(context.getPackageName());
55 | } else {
56 | if (convertView == null) {
57 | convertView =
58 | LayoutInflater.from(context).inflate(R.layout.block_canary_ref_row, parent, false);
59 | }
60 | TextView textView = findById(convertView, R.id.__leak_canary_row_text);
61 |
62 | boolean isThreadStackEntry = position == POSITION_THREAD_STACK + 1;
63 | String element = getItem(position);
64 | String htmlString = elementToHtmlString(element, position, mFoldings[position]);
65 | if (isThreadStackEntry && !mFoldings[position]) {
66 | htmlString += " " + "blocked" + "";
67 | }
68 | textView.setText(Html.fromHtml(htmlString));
69 |
70 | DisplayConnectorView connectorView = findById(convertView, R.id.__leak_canary_row_connector);
71 | connectorView.setType(connectorViewType(position));
72 |
73 | MoreDetailsView moreDetailsView = findById(convertView, R.id.__leak_canary_row_more);
74 | moreDetailsView.setFolding(mFoldings[position]);
75 | }
76 |
77 | return convertView;
78 | }
79 |
80 | private DisplayConnectorView.Type connectorViewType(int position) {
81 | return (position == 1) ? DisplayConnectorView.Type.START : (
82 | (position == getCount() - 1) ? DisplayConnectorView.Type.END :
83 | DisplayConnectorView.Type.NODE);
84 | }
85 |
86 | private String elementToHtmlString(String element, int position, boolean folding) {
87 | String htmlString = element.replaceAll(BlockInfo.SEPARATOR, " ");
88 |
89 | switch (position) {
90 | case POSITION_BASIC:
91 | if (folding) {
92 | htmlString = htmlString.substring(htmlString.indexOf(BlockInfo.KEY_CPU_CORE));
93 | }
94 | htmlString = String.format("%s ", htmlString);
95 | break;
96 | case POSITION_TIME:
97 | if (folding) {
98 | htmlString = htmlString.substring(0, htmlString.indexOf(BlockInfo.KEY_TIME_COST_START));
99 | }
100 | htmlString = String.format("%s ", htmlString);
101 | break;
102 | case POSITION_CPU:
103 | // FIXME Figure out why sometimes \r\n cannot replace completely
104 | htmlString = element;
105 | if (folding) {
106 | htmlString = htmlString.substring(0, htmlString.indexOf(BlockInfo.KEY_CPU_RATE));
107 | }
108 | htmlString = htmlString.replace("cpurate = ", " cpurate ");
109 | htmlString = String.format("%s ", htmlString);
110 | htmlString = htmlString.replaceAll("]", "] ");
111 | break;
112 | case POSITION_THREAD_STACK:
113 | default:
114 | if (folding) {
115 | for (String concernPackage : BlockCanaryUtils.getConcernPackages()) {
116 | int index = htmlString.indexOf(concernPackage);
117 | if (index > 0) {
118 | htmlString = htmlString.substring(index);
119 | break;
120 | }
121 | }
122 | }
123 | htmlString = String.format("%s ", htmlString);
124 | break;
125 | }
126 | return htmlString;
127 | }
128 |
129 | public void update(BlockInfo blockInfo) {
130 | if (mBlockInfo != null && blockInfo.timeStart.equals(mBlockInfo.timeStart)) {
131 | // Same data, nothing to change.
132 | return;
133 | }
134 | mBlockInfo = blockInfo;
135 | mFoldings = new boolean[POSITION_THREAD_STACK + mBlockInfo.threadStackEntries.size()];
136 | Arrays.fill(mFoldings, true);
137 | notifyDataSetChanged();
138 | }
139 |
140 | public void toggleRow(int position) {
141 | mFoldings[position] = !mFoldings[position];
142 | notifyDataSetChanged();
143 | }
144 |
145 | @Override
146 | public int getCount() {
147 | if (mBlockInfo == null) {
148 | return 0;
149 | }
150 | return POSITION_THREAD_STACK + mBlockInfo.threadStackEntries.size();
151 | }
152 |
153 | @Override
154 | public String getItem(int position) {
155 | if (getItemViewType(position) == TOP_ROW) {
156 | return null;
157 | }
158 | switch (position) {
159 | case POSITION_BASIC:
160 | return mBlockInfo.getBasicString();
161 | case POSITION_TIME:
162 | return mBlockInfo.getTimeString();
163 | case POSITION_CPU:
164 | return mBlockInfo.getCpuString();
165 | case POSITION_THREAD_STACK:
166 | default:
167 | return mBlockInfo.threadStackEntries.get(position - POSITION_THREAD_STACK);
168 | }
169 | }
170 |
171 | @Override
172 | public int getViewTypeCount() {
173 | return 2;
174 | }
175 |
176 | @Override
177 | public int getItemViewType(int position) {
178 | if (position == 0) {
179 | return TOP_ROW;
180 | }
181 | return NORMAL_ROW;
182 | }
183 |
184 | @Override
185 | public long getItemId(int position) {
186 | return position;
187 | }
188 |
189 | @SuppressWarnings("unchecked")
190 | private static T findById(View view, int id) {
191 | return (T) view.findViewById(id);
192 | }
193 | }
194 |
--------------------------------------------------------------------------------
/blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/internal/BlockInfo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 MarkZhai (http://zhaiyifan.cn).
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.moduth.blockcanary.internal;
17 |
18 | import android.content.Context;
19 | import android.content.pm.PackageInfo;
20 | import android.os.Build;
21 | import android.os.Build.VERSION;
22 | import android.provider.Settings;
23 | import android.telephony.TelephonyManager;
24 | import android.text.TextUtils;
25 | import android.util.Log;
26 |
27 | import com.github.moduth.blockcanary.BlockCanaryInternals;
28 |
29 | import java.text.SimpleDateFormat;
30 | import java.util.ArrayList;
31 | import java.util.Locale;
32 |
33 | /**
34 | * Information to trace a block.
35 | */
36 | public class BlockInfo {
37 |
38 | private static final String TAG = "BlockInfo";
39 |
40 | public static final SimpleDateFormat TIME_FORMATTER =
41 | new SimpleDateFormat("MM-dd HH:mm:ss.SSS", Locale.US);
42 |
43 | public static final String SEPARATOR = "\r\n";
44 | public static final String KV = " = ";
45 |
46 | public static final String NEW_INSTANCE_METHOD = "newInstance: ";
47 |
48 | public static final String KEY_QUA = "qua";
49 | public static final String KEY_MODEL = "model";
50 | public static final String KEY_API = "api-level";
51 | public static final String KEY_IMEI = "imei";
52 | public static final String KEY_UID = "uid";
53 | public static final String KEY_CPU_CORE = "cpu-core";
54 | public static final String KEY_CPU_BUSY = "cpu-busy";
55 | public static final String KEY_CPU_RATE = "cpu-rate";
56 | public static final String KEY_TIME_COST = "time";
57 | public static final String KEY_THREAD_TIME_COST = "thread-time";
58 | public static final String KEY_TIME_COST_START = "time-start";
59 | public static final String KEY_TIME_COST_END = "time-end";
60 | public static final String KEY_STACK = "stack";
61 | public static final String KEY_PROCESS = "process";
62 | public static final String KEY_VERSION_NAME = "versionName";
63 | public static final String KEY_VERSION_CODE = "versionCode";
64 | public static final String KEY_NETWORK = "network";
65 | public static final String KEY_TOTAL_MEMORY = "totalMemory";
66 | public static final String KEY_FREE_MEMORY = "freeMemory";
67 | public static final String KEY_IS_BACKGROUND = "background";
68 |
69 | public static String sQualifier;
70 | public static String sModel;
71 | public static String sApiLevel = "";
72 | /**
73 | * The International Mobile Equipment Identity or IMEI /aɪˈmiː/ is a number,
74 | * usually unique, to identify 3GPP and iDEN mobile phones
75 | */
76 | public static String sImei = "";
77 | public static int sCpuCoreNum = -1;
78 |
79 | public String qualifier;
80 | public String model;
81 | public String apiLevel = "";
82 | public String imei = "";
83 | public int cpuCoreNum = -1;
84 |
85 | // Per Block Info fields
86 | public String uid;
87 | public String processName;
88 | public String versionName = "";
89 | public int versionCode;
90 | public String network;
91 | public String freeMemory;
92 | public String totalMemory;
93 | public long timeCost;
94 | public long threadTimeCost;
95 | public String timeStart;
96 | public String timeEnd;
97 | public boolean cpuBusy;
98 | public String cpuRateInfo;
99 | public ArrayList threadStackEntries = new ArrayList<>();
100 | public boolean isBackground;
101 |
102 | private StringBuilder basicSb = new StringBuilder();
103 | private StringBuilder cpuSb = new StringBuilder();
104 | private StringBuilder timeSb = new StringBuilder();
105 | private StringBuilder stackSb = new StringBuilder();
106 | private static final String EMPTY_IMEI = "empty_imei";
107 |
108 | static {
109 | sCpuCoreNum = PerformanceUtils.getNumCores();
110 | sModel = Build.MODEL;
111 | sApiLevel = Build.VERSION.SDK_INT + " " + VERSION.RELEASE;
112 | sQualifier = BlockCanaryInternals.getContext().provideQualifier();
113 | try {
114 | sImei = getIMEI(BlockCanaryInternals.getContext().provideContext());
115 | } catch (Exception exception) {
116 | Log.e(TAG, NEW_INSTANCE_METHOD, exception);
117 | sImei = EMPTY_IMEI;
118 | }
119 | }
120 |
121 | public static String getIMEI(Context context) {
122 | TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
123 | String deviceId = telephonyManager.getDeviceId();
124 | //android 10以上已经获取不了imei了 用 android id代替
125 | if (TextUtils.isEmpty(deviceId)) {
126 | deviceId = Settings.System.getString(
127 | context.getContentResolver(), Settings.Secure.ANDROID_ID);
128 | }
129 | return deviceId;
130 | }
131 |
132 | public BlockInfo() {
133 | }
134 |
135 | public static BlockInfo newInstance() {
136 | BlockInfo blockInfo = new BlockInfo();
137 | Context context = BlockCanaryInternals.getContext().provideContext();
138 | if (blockInfo.versionName == null || blockInfo.versionName.length() == 0) {
139 | try {
140 | PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
141 | blockInfo.versionCode = info.versionCode;
142 | blockInfo.versionName = info.versionName;
143 | } catch (Throwable e) {
144 | Log.e(TAG, NEW_INSTANCE_METHOD, e);
145 | }
146 | }
147 |
148 | blockInfo.cpuCoreNum = sCpuCoreNum;
149 | blockInfo.model = sModel;
150 | blockInfo.apiLevel = sApiLevel;
151 | blockInfo.qualifier = sQualifier;
152 | blockInfo.imei = sImei;
153 | blockInfo.uid = BlockCanaryInternals.getContext().provideUid();
154 | blockInfo.processName = ProcessUtils.myProcessName();
155 | blockInfo.network = BlockCanaryInternals.getContext().provideNetworkType();
156 | blockInfo.freeMemory = String.valueOf(PerformanceUtils.getFreeMemory());
157 | blockInfo.totalMemory = String.valueOf(PerformanceUtils.getTotalMemory());
158 |
159 | return blockInfo;
160 | }
161 |
162 | public BlockInfo setCpuBusyFlag(boolean busy) {
163 | cpuBusy = busy;
164 | return this;
165 | }
166 |
167 | public BlockInfo setRecentCpuRate(String info) {
168 | cpuRateInfo = info;
169 | return this;
170 | }
171 |
172 | public BlockInfo setThreadStackEntries(ArrayList threadStackEntries) {
173 | this.threadStackEntries = threadStackEntries;
174 | return this;
175 | }
176 |
177 | public BlockInfo setMainThreadTimeCost(long realTimeStart, long realTimeEnd, long threadTimeStart, long threadTimeEnd) {
178 | timeCost = realTimeEnd - realTimeStart;
179 | threadTimeCost = threadTimeEnd - threadTimeStart;
180 | timeStart = TIME_FORMATTER.format(realTimeStart);
181 | timeEnd = TIME_FORMATTER.format(realTimeEnd);
182 | return this;
183 | }
184 |
185 | public BlockInfo setAppBackground(boolean background) {
186 | isBackground = background;
187 | return this;
188 | }
189 |
190 | public BlockInfo flushString() {
191 | String separator = SEPARATOR;
192 | basicSb.append(KEY_QUA).append(KV).append(qualifier).append(separator);
193 | basicSb.append(KEY_VERSION_NAME).append(KV).append(versionName).append(separator);
194 | basicSb.append(KEY_VERSION_CODE).append(KV).append(versionCode).append(separator);
195 | basicSb.append(KEY_IMEI).append(KV).append(imei).append(separator);
196 | basicSb.append(KEY_UID).append(KV).append(uid).append(separator);
197 | basicSb.append(KEY_NETWORK).append(KV).append(network).append(separator);
198 | basicSb.append(KEY_MODEL).append(KV).append(model).append(separator);
199 | basicSb.append(KEY_API).append(KV).append(apiLevel).append(separator);
200 | basicSb.append(KEY_CPU_CORE).append(KV).append(cpuCoreNum).append(separator);
201 | basicSb.append(KEY_PROCESS).append(KV).append(processName).append(separator);
202 | basicSb.append(KEY_FREE_MEMORY).append(KV).append(freeMemory).append(separator);
203 | basicSb.append(KEY_TOTAL_MEMORY).append(KV).append(totalMemory).append(separator);
204 | basicSb.append(KEY_IS_BACKGROUND).append(KV).append(isBackground).append(separator);
205 |
206 | timeSb.append(KEY_TIME_COST).append(KV).append(timeCost).append(separator);
207 | timeSb.append(KEY_THREAD_TIME_COST).append(KV).append(threadTimeCost).append(separator);
208 | timeSb.append(KEY_TIME_COST_START).append(KV).append(timeStart).append(separator);
209 | timeSb.append(KEY_TIME_COST_END).append(KV).append(timeEnd).append(separator);
210 |
211 | cpuSb.append(KEY_CPU_BUSY).append(KV).append(cpuBusy).append(separator);
212 | cpuSb.append(KEY_CPU_RATE).append(KV).append(cpuRateInfo).append(separator);
213 |
214 |
215 | if (threadStackEntries != null && !threadStackEntries.isEmpty()) {
216 | StringBuilder temp = new StringBuilder();
217 | for (String s : threadStackEntries) {
218 | temp.append(s);
219 | temp.append(separator);
220 | }
221 | stackSb.append(KEY_STACK).append(KV).append(temp.toString()).append(separator);
222 | }
223 | return this;
224 | }
225 |
226 | public String getBasicString() {
227 | return basicSb.toString();
228 | }
229 |
230 | public String getCpuString() {
231 | return cpuSb.toString();
232 | }
233 |
234 | public String getTimeString() {
235 | return timeSb.toString();
236 | }
237 |
238 | public String toString() {
239 | return String.valueOf(basicSb) + timeSb + cpuSb + stackSb;
240 | }
241 |
242 |
243 | }
244 |
--------------------------------------------------------------------------------
/blockcanary-analyzer/src/main/java/com/github/moduth/blockcanary/CpuSampler.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 MarkZhai (http://zhaiyifan.cn).
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.moduth.blockcanary;
17 |
18 | import android.os.Build;
19 | import android.os.Process;
20 | import android.text.TextUtils;
21 | import android.util.Log;
22 |
23 | import com.github.moduth.blockcanary.internal.BlockInfo;
24 |
25 | import java.io.BufferedReader;
26 | import java.io.FileInputStream;
27 | import java.io.IOException;
28 | import java.io.InputStreamReader;
29 | import java.util.LinkedHashMap;
30 | import java.util.Map;
31 |
32 | /**
33 | * Dumps cpu usage.
34 | */
35 | class CpuSampler extends AbstractSampler {
36 |
37 | private static final String TAG = "CpuSampler";
38 | private static final int BUFFER_SIZE = 1000;
39 |
40 | /**
41 | * TODO: Explain how we define cpu busy in README
42 | */
43 | private final int BUSY_TIME;
44 | private static final int MAX_ENTRY_COUNT = BlockCanaryInternals.getContext().reportRecentOneMessage() ? 1 : 10;
45 |
46 | private final LinkedHashMap mCpuInfoEntries = new LinkedHashMap<>();
47 | private int mPid = 0;
48 | private long mUserLast = 0;
49 | private long mSystemLast = 0;
50 | private long mIdleLast = 0;
51 | private long mIoWaitLast = 0;
52 | private long mTotalLast = 0;
53 | private long mAppCpuTimeLast = 0;
54 | private boolean mAboveAndroidO = false;
55 |
56 | public CpuSampler(long sampleInterval) {
57 | super(sampleInterval);
58 | BUSY_TIME = (int) (mSampleInterval * 1.2f);
59 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
60 | mAboveAndroidO = true;
61 | }
62 | }
63 |
64 | @Override
65 | public void start() {
66 | super.start();
67 | reset();
68 | }
69 |
70 | /**
71 | * Get cpu rate information
72 | *
73 | * @return string show cpu rate information
74 | */
75 | public String getCpuRateInfo() {
76 | StringBuilder sb = new StringBuilder();
77 | synchronized (mCpuInfoEntries) {
78 | for (Map.Entry entry : mCpuInfoEntries.entrySet()) {
79 | long time = entry.getKey();
80 | sb.append(BlockInfo.TIME_FORMATTER.format(time))
81 | .append(' ')
82 | .append(entry.getValue())
83 | .append(BlockInfo.SEPARATOR);
84 | }
85 | }
86 | return sb.toString();
87 | }
88 |
89 | public boolean isCpuBusy(long start, long end) {
90 | if (end - start > mSampleInterval) {
91 | long s = start - mSampleInterval;
92 | long e = start + mSampleInterval;
93 | long last = 0;
94 | synchronized (mCpuInfoEntries) {
95 | for (Map.Entry entry : mCpuInfoEntries.entrySet()) {
96 | long time = entry.getKey();
97 | if (s < time && time < e) {
98 | if (last != 0 && time - last > BUSY_TIME) {
99 | return true;
100 | }
101 | last = time;
102 | }
103 | }
104 | }
105 | }
106 | return false;
107 | }
108 |
109 | @Override
110 | protected void doSample() {
111 | if (mAboveAndroidO) {
112 | getCPUDataForO();
113 | } else {
114 | getCPUData();
115 | }
116 | }
117 |
118 | /**
119 | * Android above O(26) can only get app rate
120 | */
121 | private void getCPUDataForO() {
122 | java.lang.Process process = null;
123 | try {
124 | process = Runtime.getRuntime().exec("top -n 1");
125 | BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
126 | String line;
127 | int cpuIndex = -1;
128 | while ((line = reader.readLine()) != null) {
129 | line = line.trim();
130 | if (TextUtils.isEmpty(line)) {
131 | continue;
132 | }
133 |
134 | int tempIndex = getCPUIndex(line);
135 | if (tempIndex != -1) {
136 | cpuIndex = tempIndex;
137 | continue;
138 | }
139 | if (line.startsWith(String.valueOf(Process.myPid()))) {
140 | if (cpuIndex == -1) {
141 | continue;
142 | }
143 | String[] param = line.split("\\s+");
144 |
145 | if (param.length <= cpuIndex) {
146 | continue;
147 | }
148 | String cpu = param[cpuIndex];
149 | if (cpu.endsWith("%")) {
150 | cpu = cpu.substring(0, cpu.lastIndexOf("%"));
151 | }
152 | float rate = Float.parseFloat(cpu) / Runtime.getRuntime().availableProcessors();
153 |
154 | StringBuilder stringBuilder = new StringBuilder();
155 |
156 | stringBuilder.append(cpu).append("% ");
157 |
158 | synchronized (mCpuInfoEntries) {
159 | mCpuInfoEntries.put(System.currentTimeMillis(), stringBuilder.toString());
160 | if (mCpuInfoEntries.size() > MAX_ENTRY_COUNT) {
161 | for (Map.Entry entry : mCpuInfoEntries.entrySet()) {
162 | Long key = entry.getKey();
163 | mCpuInfoEntries.remove(key);
164 | break;
165 | }
166 | }
167 | }
168 | }
169 | }
170 | } catch (IOException e) {
171 | e.printStackTrace();
172 | } finally {
173 | if (process != null) {
174 | process.destroy();
175 | }
176 | }
177 | }
178 |
179 |
180 | private int getCPUIndex(String line) {
181 | if (line.contains("CPU")) {
182 | String[] titles = line.split("\\s+");
183 | for (int i = 0; i < titles.length; i++) {
184 | if (titles[i].contains("CPU")) {
185 | return i;
186 | }
187 | }
188 | }
189 | return -1;
190 | }
191 |
192 |
193 | private void getCPUData() {
194 | BufferedReader cpuReader = null;
195 | BufferedReader pidReader = null;
196 | try {
197 | cpuReader = new BufferedReader(new InputStreamReader(
198 | new FileInputStream("/proc/stat")), BUFFER_SIZE);
199 | String cpuRate = cpuReader.readLine();
200 | if (cpuRate == null) {
201 | cpuRate = "";
202 | }
203 |
204 | if (mPid == 0) {
205 | mPid = android.os.Process.myPid();
206 | }
207 | pidReader = new BufferedReader(new InputStreamReader(
208 | new FileInputStream("/proc/" + mPid + "/stat")), BUFFER_SIZE);
209 | String pidCpuRate = pidReader.readLine();
210 | if (pidCpuRate == null) {
211 | pidCpuRate = "";
212 | }
213 | parse(cpuRate, pidCpuRate);
214 | } catch (Throwable throwable) {
215 | Log.e(TAG, "doSample: ", throwable);
216 | } finally {
217 | try {
218 | if (cpuReader != null) {
219 | cpuReader.close();
220 | }
221 | if (pidReader != null) {
222 | pidReader.close();
223 | }
224 | } catch (IOException exception) {
225 | Log.e(TAG, "doSample: ", exception);
226 | }
227 | }
228 | }
229 |
230 | private void reset() {
231 | mUserLast = 0;
232 | mSystemLast = 0;
233 | mIdleLast = 0;
234 | mIoWaitLast = 0;
235 | mTotalLast = 0;
236 | mAppCpuTimeLast = 0;
237 | }
238 |
239 | private void parse(String cpuRate, String pidCpuRate) {
240 | String[] cpuInfoArray = cpuRate.split(" ");
241 | if (cpuInfoArray.length < 9) {
242 | return;
243 | }
244 | long user = Long.parseLong(cpuInfoArray[2]);
245 | long nice = Long.parseLong(cpuInfoArray[3]);
246 | long system = Long.parseLong(cpuInfoArray[4]);
247 | long idle = Long.parseLong(cpuInfoArray[5]);
248 | long ioWait = Long.parseLong(cpuInfoArray[6]);
249 | long total = user + nice + system + idle + ioWait
250 | + Long.parseLong(cpuInfoArray[7])
251 | + Long.parseLong(cpuInfoArray[8]);
252 |
253 | String[] pidCpuInfoList = pidCpuRate.split(" ");
254 | if (pidCpuInfoList.length < 17) {
255 | return;
256 | }
257 |
258 | long appCpuTime = Long.parseLong(pidCpuInfoList[13])
259 | + Long.parseLong(pidCpuInfoList[14])
260 | + Long.parseLong(pidCpuInfoList[15])
261 | + Long.parseLong(pidCpuInfoList[16]);
262 |
263 | if (mTotalLast != 0) {
264 | StringBuilder stringBuilder = new StringBuilder();
265 | long idleTime = idle - mIdleLast;
266 | long totalTime = total - mTotalLast;
267 |
268 | stringBuilder
269 | //.append("cpu: ")
270 | .append((totalTime - idleTime) * 100L / totalTime)
271 | .append("% ")
272 | //.append("app: ")
273 | .append((appCpuTime - mAppCpuTimeLast) * 100L / totalTime)
274 | .append("% ")
275 | //.append("user:")
276 | .append((user - mUserLast) * 100L / totalTime)
277 | .append("% ")
278 | //.append("system:")
279 | .append((system - mSystemLast) * 100L / totalTime)
280 | .append("% ")
281 | //.append("ioWait:")
282 | .append((ioWait - mIoWaitLast) * 100L / totalTime)
283 | .append("% ");
284 |
285 | synchronized (mCpuInfoEntries) {
286 | mCpuInfoEntries.put(System.currentTimeMillis(), stringBuilder.toString());
287 | if (mCpuInfoEntries.size() > MAX_ENTRY_COUNT) {
288 | for (Map.Entry entry : mCpuInfoEntries.entrySet()) {
289 | Long key = entry.getKey();
290 | mCpuInfoEntries.remove(key);
291 | break;
292 | }
293 | }
294 | }
295 | }
296 | mUserLast = user;
297 | mSystemLast = system;
298 | mIdleLast = idle;
299 | mIoWaitLast = ioWait;
300 | mTotalLast = total;
301 |
302 | mAppCpuTimeLast = appCpuTime;
303 | }
304 |
305 |
306 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/blockcanary-android/src/main/java/com/github/moduth/blockcanary/ui/DisplayActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.moduth.blockcanary.ui;
17 |
18 | import android.app.ActionBar;
19 | import android.app.Activity;
20 | import android.app.AlertDialog;
21 | import android.app.PendingIntent;
22 | import android.content.Context;
23 | import android.content.DialogInterface;
24 | import android.content.Intent;
25 | import android.net.Uri;
26 | import android.os.Build;
27 | import android.os.Bundle;
28 | import android.os.Handler;
29 | import android.os.Looper;
30 | import android.text.TextUtils;
31 | import android.text.format.DateUtils;
32 | import android.util.Log;
33 | import android.view.LayoutInflater;
34 | import android.view.Menu;
35 | import android.view.MenuItem;
36 | import android.view.View;
37 | import android.view.ViewGroup;
38 | import android.widget.AdapterView;
39 | import android.widget.BaseAdapter;
40 | import android.widget.Button;
41 | import android.widget.ListAdapter;
42 | import android.widget.ListView;
43 | import android.widget.TextView;
44 |
45 | import com.github.moduth.blockcanary.BlockCanaryContext;
46 | import com.github.moduth.blockcanary.BlockCanaryInternals;
47 | import com.github.moduth.blockcanary.LogWriter;
48 | import com.github.moduth.blockcanary.R;
49 |
50 | import java.io.File;
51 | import java.util.ArrayList;
52 | import java.util.Collections;
53 | import java.util.Comparator;
54 | import java.util.List;
55 | import java.util.concurrent.Executor;
56 | import java.util.concurrent.Executors;
57 |
58 | import static android.app.PendingIntent.FLAG_UPDATE_CURRENT;
59 | import static android.text.format.DateUtils.FORMAT_SHOW_DATE;
60 | import static android.text.format.DateUtils.FORMAT_SHOW_TIME;
61 | import static android.view.View.GONE;
62 | import static android.view.View.VISIBLE;
63 |
64 | /**
65 | * Display blocks.
66 | */
67 | public class DisplayActivity extends Activity {
68 |
69 | private static final String TAG = "DisplayActivity";
70 | private static final String SHOW_BLOCK_EXTRA = "show_latest";
71 | public static final String SHOW_BLOCK_EXTRA_KEY = "BlockStartTime";
72 |
73 | // empty until it's been first loaded.
74 | private List mBlockInfoEntries = new ArrayList<>();
75 | private String mBlockStartTime;
76 |
77 | private ListView mListView;
78 | private TextView mFailureView;
79 | private Button mActionButton;
80 | private int mMaxStoredBlockCount;
81 |
82 | public static PendingIntent createPendingIntent(Context context, String blockStartTime) {
83 | Intent intent = new Intent(context, DisplayActivity.class);
84 | intent.putExtra(SHOW_BLOCK_EXTRA, blockStartTime);
85 | intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
86 | return PendingIntent.getActivity(context, 1, intent, FLAG_UPDATE_CURRENT);
87 | }
88 |
89 | @Override
90 | protected void onCreate(Bundle savedInstanceState) {
91 | super.onCreate(savedInstanceState);
92 |
93 | if (savedInstanceState != null) {
94 | mBlockStartTime = savedInstanceState.getString(SHOW_BLOCK_EXTRA_KEY);
95 | } else {
96 | Intent intent = getIntent();
97 | if (intent.hasExtra(SHOW_BLOCK_EXTRA)) {
98 | mBlockStartTime = intent.getStringExtra(SHOW_BLOCK_EXTRA);
99 | }
100 | }
101 |
102 | setContentView(R.layout.block_canary_display_leak);
103 |
104 | mListView = (ListView) findViewById(R.id.__leak_canary_display_leak_list);
105 | mFailureView = (TextView) findViewById(R.id.__leak_canary_display_leak_failure);
106 | mActionButton = (Button) findViewById(R.id.__leak_canary_action);
107 |
108 | mMaxStoredBlockCount = getResources().getInteger(R.integer.block_canary_max_stored_count);
109 |
110 | updateUi();
111 | }
112 |
113 | // No, it's not deprecated. Android lies.
114 | @Override
115 | public Object onRetainNonConfigurationInstance() {
116 | return mBlockInfoEntries;
117 | }
118 |
119 | @Override
120 | protected void onSaveInstanceState(Bundle outState) {
121 | super.onSaveInstanceState(outState);
122 | outState.putString(SHOW_BLOCK_EXTRA_KEY, mBlockStartTime);
123 | }
124 |
125 | @Override
126 | protected void onResume() {
127 | super.onResume();
128 | LoadBlocks.load(this);
129 | }
130 |
131 | @Override
132 | public void setTheme(int resid) {
133 | // We don't want this to be called with an incompatible theme.
134 | // This could happen if you implement runtime switching of themes
135 | // using ActivityLifecycleCallbacks.
136 | if (resid != R.style.block_canary_BlockCanary_Base) {
137 | return;
138 | }
139 | super.setTheme(resid);
140 | }
141 |
142 | @Override
143 | protected void onDestroy() {
144 | super.onDestroy();
145 | LoadBlocks.forgetActivity();
146 | }
147 |
148 | @Override
149 | public boolean onCreateOptionsMenu(Menu menu) {
150 | final BlockInfoEx blockInfo = getBlock(mBlockStartTime);
151 | if (blockInfo != null) {
152 | menu.add(R.string.block_canary_share_leak)
153 | .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
154 | @Override
155 | public boolean onMenuItemClick(MenuItem item) {
156 | shareBlock(blockInfo);
157 | return true;
158 | }
159 | });
160 | menu.add(R.string.block_canary_share_stack_dump)
161 | .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
162 | @Override
163 | public boolean onMenuItemClick(MenuItem item) {
164 | shareHeapDump(blockInfo);
165 | return true;
166 | }
167 | });
168 | return true;
169 | }
170 | return false;
171 | }
172 |
173 | @Override
174 | public boolean onOptionsItemSelected(MenuItem item) {
175 | if (item.getItemId() == android.R.id.home) {
176 | mBlockStartTime = null;
177 | updateUi();
178 | }
179 | return true;
180 | }
181 |
182 | @Override
183 | public void onBackPressed() {
184 | if (mBlockStartTime != null) {
185 | mBlockStartTime = null;
186 | updateUi();
187 | } else {
188 | super.onBackPressed();
189 | }
190 | }
191 |
192 | private void shareBlock(BlockInfoEx blockInfo) {
193 | String leakInfo = blockInfo.toString();
194 | Intent intent = new Intent(Intent.ACTION_SEND);
195 | intent.setType("text/plain");
196 | intent.putExtra(Intent.EXTRA_TEXT, leakInfo);
197 | startActivity(Intent.createChooser(intent, getString(R.string.block_canary_share_with)));
198 | }
199 |
200 | private void shareHeapDump(BlockInfoEx blockInfo) {
201 | File heapDumpFile = blockInfo.logFile;
202 |
203 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
204 | heapDumpFile.setReadable(true, false);
205 | }
206 | Intent intent = new Intent(Intent.ACTION_SEND);
207 | intent.setType("application/octet-stream");
208 | intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(heapDumpFile));
209 | startActivity(Intent.createChooser(intent, getString(R.string.block_canary_share_with)));
210 | }
211 |
212 | private void updateUi() {
213 | final BlockInfoEx blockInfo = getBlock(mBlockStartTime);
214 | if (blockInfo == null) {
215 | mBlockStartTime = null;
216 | }
217 |
218 | // Reset to defaults
219 | mListView.setVisibility(VISIBLE);
220 | mFailureView.setVisibility(GONE);
221 |
222 | if (blockInfo != null) {
223 | renderBlockDetail(blockInfo);
224 | } else {
225 | renderBlockList();
226 | }
227 | }
228 |
229 | private void renderBlockList() {
230 | ListAdapter listAdapter = mListView.getAdapter();
231 | if (listAdapter instanceof BlockListAdapter) {
232 | ((BlockListAdapter) listAdapter).notifyDataSetChanged();
233 | } else {
234 | BlockListAdapter adapter = new BlockListAdapter();
235 | mListView.setAdapter(adapter);
236 | mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
237 | @Override
238 | public void onItemClick(AdapterView> parent, View view, int position, long id) {
239 | mBlockStartTime = mBlockInfoEntries.get(position).timeStart;
240 | updateUi();
241 | }
242 | });
243 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
244 | invalidateOptionsMenu();
245 | ActionBar actionBar = getActionBar();
246 | if (actionBar != null) {
247 | actionBar.setDisplayHomeAsUpEnabled(false);
248 | }
249 | }
250 | setTitle(getString(R.string.block_canary_block_list_title, getPackageName()));
251 | mActionButton.setText(R.string.block_canary_delete_all);
252 | mActionButton.setOnClickListener(new View.OnClickListener() {
253 | @Override
254 | public void onClick(View v) {
255 | DialogInterface.OnClickListener okListener = new DialogInterface.OnClickListener() {
256 | @Override
257 | public void onClick(DialogInterface dialogInterface, int i) {
258 | LogWriter.deleteAll();
259 | mBlockInfoEntries = Collections.emptyList();
260 | updateUi();
261 | }
262 | };
263 | new AlertDialog.Builder(DisplayActivity.this)
264 | .setTitle(getString(R.string.block_canary_delete))
265 | .setMessage(getString(R.string.block_canary_delete_all_dialog_content))
266 | .setPositiveButton(getString(R.string.block_canary_yes), okListener)
267 | .setNegativeButton(getString(R.string.block_canary_no), null)
268 | .show();
269 |
270 | }
271 | });
272 | }
273 | mActionButton.setVisibility(mBlockInfoEntries.isEmpty() ? GONE : VISIBLE);
274 | }
275 |
276 | private void renderBlockDetail(final BlockInfoEx blockInfo) {
277 | ListAdapter listAdapter = mListView.getAdapter();
278 | final DetailAdapter adapter;
279 | if (listAdapter instanceof DetailAdapter) {
280 | adapter = (DetailAdapter) listAdapter;
281 | } else {
282 | adapter = new DetailAdapter();
283 | mListView.setAdapter(adapter);
284 | mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
285 | @Override
286 | public void onItemClick(AdapterView> parent, View view, int position, long id) {
287 | adapter.toggleRow(position);
288 | }
289 | });
290 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
291 | invalidateOptionsMenu();
292 | ActionBar actionBar = getActionBar();
293 | if (actionBar != null) {
294 | actionBar.setDisplayHomeAsUpEnabled(true);
295 | }
296 | }
297 | mActionButton.setVisibility(VISIBLE);
298 | mActionButton.setText(R.string.block_canary_delete);
299 | }
300 | mActionButton.setOnClickListener(new View.OnClickListener() {
301 | @Override
302 | public void onClick(View v) {
303 | if (blockInfo != null) {
304 | blockInfo.logFile.delete();
305 | mBlockStartTime = null;
306 | mBlockInfoEntries.remove(blockInfo);
307 | updateUi();
308 | }
309 | }
310 | });
311 | adapter.update(blockInfo);
312 | setTitle(getString(R.string.block_canary_class_has_blocked, blockInfo.timeCost));
313 | }
314 |
315 | private BlockInfoEx getBlock(String startTime) {
316 | if (mBlockInfoEntries == null || TextUtils.isEmpty(startTime)) {
317 | return null;
318 | }
319 | for (BlockInfoEx blockInfo : mBlockInfoEntries) {
320 | if (blockInfo.timeStart != null && startTime.equals(blockInfo.timeStart)) {
321 | return blockInfo;
322 | }
323 | }
324 | return null;
325 | }
326 |
327 | class BlockListAdapter extends BaseAdapter {
328 |
329 | @Override
330 | public int getCount() {
331 | return mBlockInfoEntries.size();
332 | }
333 |
334 | @Override
335 | public BlockInfoEx getItem(int position) {
336 | return mBlockInfoEntries.get(position);
337 | }
338 |
339 | @Override
340 | public long getItemId(int position) {
341 | return position;
342 | }
343 |
344 | @Override
345 | public View getView(int position, View convertView, ViewGroup parent) {
346 | if (convertView == null) {
347 | convertView = LayoutInflater.from(DisplayActivity.this)
348 | .inflate(R.layout.block_canary_block_row, parent, false);
349 | }
350 | TextView titleView = (TextView) convertView.findViewById(R.id.__leak_canary_row_text);
351 | TextView timeView = (TextView) convertView.findViewById(R.id.__leak_canary_row_time);
352 | BlockInfoEx blockInfo = getItem(position);
353 |
354 | String index;
355 | if (position == 0 && mBlockInfoEntries.size() == mMaxStoredBlockCount) {
356 | index = "MAX. ";
357 | } else {
358 | index = (mBlockInfoEntries.size() - position) + ". ";
359 | }
360 |
361 | String keyStackString = BlockCanaryUtils.concernStackString(blockInfo);
362 | String title = index + keyStackString + " " +
363 | getString(R.string.block_canary_class_has_blocked, blockInfo.timeCost);
364 | titleView.setText(title);
365 | String time = DateUtils.formatDateTime(DisplayActivity.this,
366 | blockInfo.logFile.lastModified(), FORMAT_SHOW_TIME | FORMAT_SHOW_DATE);
367 | timeView.setText(time);
368 | return convertView;
369 | }
370 | }
371 |
372 | static class LoadBlocks implements Runnable {
373 |
374 | static final List inFlight = new ArrayList<>();
375 | static final Executor backgroundExecutor = Executors.newSingleThreadExecutor();
376 | private DisplayActivity activityOrNull;
377 | private final Handler mainHandler;
378 |
379 | LoadBlocks(DisplayActivity activity) {
380 | this.activityOrNull = activity;
381 | mainHandler = new Handler(Looper.getMainLooper());
382 | }
383 |
384 | static void load(DisplayActivity activity) {
385 | LoadBlocks loadBlocks = new LoadBlocks(activity);
386 | inFlight.add(loadBlocks);
387 | backgroundExecutor.execute(loadBlocks);
388 | }
389 |
390 | static void forgetActivity() {
391 | for (LoadBlocks loadBlocks : inFlight) {
392 | loadBlocks.activityOrNull = null;
393 | }
394 | inFlight.clear();
395 | }
396 |
397 | @Override
398 | public void run() {
399 | final List blockInfoList = new ArrayList<>();
400 | File[] files = BlockCanaryInternals.getLogFiles();
401 | if (files != null) {
402 | for (File blockFile : files) {
403 | try {
404 | BlockInfoEx blockInfo = BlockInfoEx.newInstance(blockFile);
405 | if (!BlockCanaryUtils.isBlockInfoValid(blockInfo)) {
406 | throw new BlockInfoCorruptException(blockInfo);
407 | }
408 |
409 | boolean needAddToList = true;
410 |
411 | if (BlockCanaryUtils.isInWhiteList(blockInfo)) {
412 | if (BlockCanaryContext.get().deleteFilesInWhiteList()) {
413 | blockFile.delete();
414 | blockFile = null;
415 | }
416 | needAddToList = false;
417 | }
418 |
419 | blockInfo.concernStackString = BlockCanaryUtils.concernStackString(blockInfo);
420 | if (BlockCanaryContext.get().filterNonConcernStack() &&
421 | TextUtils.isEmpty(blockInfo.concernStackString)) {
422 | needAddToList = false;
423 | }
424 |
425 | if (needAddToList && blockFile != null) {
426 | blockInfoList.add(blockInfo);
427 | }
428 | } catch (Exception e) {
429 | // Probably blockFile corrupts or format changes, just delete it.
430 | blockFile.delete();
431 | Log.e(TAG, "Could not read block log file, deleted :" + blockFile, e);
432 | }
433 | }
434 | Collections.sort(blockInfoList, new Comparator() {
435 | @Override
436 | public int compare(BlockInfoEx lhs, BlockInfoEx rhs) {
437 | return Long.valueOf(rhs.logFile.lastModified())
438 | .compareTo(lhs.logFile.lastModified());
439 | }
440 | });
441 | }
442 | mainHandler.post(new Runnable() {
443 | @Override
444 | public void run() {
445 | inFlight.remove(LoadBlocks.this);
446 | if (activityOrNull != null) {
447 | activityOrNull.mBlockInfoEntries = blockInfoList;
448 | Log.d(TAG, "load block entries: " + blockInfoList.size());
449 | activityOrNull.updateUi();
450 | }
451 | }
452 | });
453 | }
454 | }
455 | }
--------------------------------------------------------------------------------