├── .gitignore
├── README.md
├── assets
├── detail.png
├── list.png
├── notification.png
└── video.gif
├── build.gradle
├── demo
├── .gitignore
├── build.gradle
├── debug.keystore
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── nshmura
│ │ └── strictmodenotifier
│ │ └── demo
│ │ └── ApplicationTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── nshmura
│ │ │ └── strictmodenotifier
│ │ │ └── demo
│ │ │ ├── MainActivity.java
│ │ │ └── MainApplication.java
│ └── res
│ │ ├── layout
│ │ └── activity_main.xml
│ │ ├── mipmap-hdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ └── ic_launcher.png
│ │ ├── values-w820dp
│ │ └── dimens.xml
│ │ └── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── nshmura
│ └── strictmodenotifier
│ └── demo
│ └── ExampleUnitTest.java
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── library-common
├── .gitignore
├── build.gradle
└── src
│ └── main
│ ├── AndroidManifest.xml
│ └── java
│ └── com
│ └── nshmura
│ └── strictmodenotifier
│ ├── CustomAction.java
│ ├── IgnoreAction.java
│ ├── NotifierConfig.java
│ ├── StrictModeViolation.java
│ └── ViolationType.java
├── library-no-op
├── .gitignore
├── build.gradle
└── src
│ └── main
│ ├── AndroidManifest.xml
│ └── java
│ └── com
│ └── nshmura
│ └── strictmodenotifier
│ └── StrictModeNotifier.java
├── library
├── .gitignore
├── build.gradle
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── nshmura
│ │ └── strictmodenotifier
│ │ ├── LogWatchService.java
│ │ ├── ReportActivityUtils.java
│ │ ├── ReportAdapter.java
│ │ ├── StrictModeLog.java
│ │ ├── StrictModeNotifier.java
│ │ ├── StrictModeNotifierInternals.java
│ │ ├── StrictModeNotifierSingleThreadFactory.java
│ │ ├── StrictModeReportActivity.java
│ │ ├── StrictModeReportDetailActivity.java
│ │ ├── StringModeConfig.java
│ │ ├── ViolationStore.java
│ │ ├── ViolationTypeInfo.java
│ │ └── detector
│ │ ├── ClassInstanceLimitDetector.java
│ │ ├── CleartextNetworkDetector.java
│ │ ├── CustomSlowCallDetector.java
│ │ ├── Detector.java
│ │ ├── FileUriExposureDetector.java
│ │ ├── LeakedClosableObjectsDetector.java
│ │ ├── NetworkDetector.java
│ │ └── ResourceMismatchDetector.java
│ └── res
│ ├── drawable-hdpi
│ ├── strictmode_notifier_ic_launcher.png
│ └── strictmode_notifier_ic_notification.png
│ ├── drawable-mdpi
│ ├── strictmode_notifier_ic_launcher.png
│ └── strictmode_notifier_ic_notification.png
│ ├── drawable-xhdpi
│ ├── strictmode_notifier_ic_launcher.png
│ └── strictmode_notifier_ic_notification.png
│ ├── drawable-xxhdpi
│ ├── strictmode_notifier_ic_launcher.png
│ └── strictmode_notifier_ic_notification.png
│ ├── drawable-xxxhdpi
│ ├── strictmode_notifier_ic_launcher.png
│ └── strictmode_notifier_ic_notification.png
│ ├── layout
│ ├── strictmode_notifier_activity_report.xml
│ ├── strictmode_notifier_activity_report_detail.xml
│ └── strictmode_notifier_row.xml
│ ├── menu
│ └── strictmode_notifier_menu.xml
│ ├── values-v14
│ └── strictmode_notifier_styles.xml
│ ├── values-v21
│ └── strictmode_notifier_styles.xml
│ └── values
│ ├── strictmode_notifer_strings.xml
│ ├── strictmode_notifier_colors.xml
│ └── strictmode_notifier_styles.xml
├── settings.gradle
└── testapp
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
├── androidTest
└── java
│ └── com
│ └── nshmura
│ └── strictmodenotifier
│ └── testapp
│ └── ApplicationTest.java
├── main
├── AndroidManifest.xml
├── java
│ └── com
│ │ └── nshmura
│ │ └── strictmodenotifier
│ │ └── testapp
│ │ ├── ClassInstanceLimitActivity.java
│ │ ├── CustomLogWatchService.java
│ │ ├── LeakedBroadcastReceiver.java
│ │ ├── LeakedClosableObjectsActivity.java
│ │ ├── LeakedSQLiteOpenHelper.java
│ │ ├── MainActivity.java
│ │ └── MainApplication.java
└── res
│ ├── layout
│ ├── activity_main.xml
│ └── row_actions.xml
│ ├── menu
│ └── main.xml
│ ├── mipmap-hdpi
│ └── ic_launcher.png
│ ├── mipmap-mdpi
│ └── ic_launcher.png
│ ├── mipmap-xhdpi
│ └── ic_launcher.png
│ ├── mipmap-xxhdpi
│ └── ic_launcher.png
│ ├── mipmap-xxxhdpi
│ └── ic_launcher.png
│ ├── values-w820dp
│ └── dimens.xml
│ └── values
│ ├── colors.xml
│ ├── dimens.xml
│ ├── strings.xml
│ └── styles.xml
└── test
└── java
└── com
└── nshmura
└── strictmodenotificator
└── ExampleUnitTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | Thumbs.db
3 |
4 | # Files for the Dalvik VM
5 | *.dex
6 |
7 | # Java class files
8 | *.class
9 |
10 | # Generated files
11 | bin/
12 | gen/
13 | obj/
14 | apk/
15 | target/
16 | build/
17 |
18 | # Gradle files
19 | .gradle/
20 | .idea
21 | *.iml
22 |
23 | # Local configuration file (sdk path, etc)
24 | local.properties
25 |
26 | # Proguard folder generated by Eclipse
27 | proguard/
28 |
29 | # Crashlytics
30 | res/values/com_crashlytics_export_strings.xml
31 | assets/crashlytics-build.properties
32 |
33 | # docs
34 | docs/
35 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # strictmode-notifier
2 | [](http://androidweekly.net/issues/issue-200)
3 | [](https://android-arsenal.com/details/1/3405)
4 |
5 | An Android library that improves the StrictMode reporting.
6 |
7 | - *Head-up Notification* of StrictMode violations.
8 | - *Ignoring Specific Violations*
9 | - *Custom Actions* that called when StrictMode violations is happened.
10 | - *Violation History Viewer* that automatically installed.
11 |
12 | ## Screenshots
13 |
14 |
15 |
16 |
17 | ## Sample App
18 | [strictmode-notifier/testapp](https://github.com/nshmura/strictmode-notifier/tree/master/testapp)
19 |
20 | 
21 |
22 | ## About StrictMode
23 | - [StrictMode for Runtime Analysis on Android](https://medium.com/google-developers/strictmode-for-runtime-analysis-on-android-f8d0a2c5667e#.elffd4gi1)
24 | - [StrictMode for enforcing best practices at runtime](https://www.youtube.com/watch?v=BxTfwT7mkB4)
25 |
26 | ## Getting started
27 |
28 | In your `build.gradle`:
29 |
30 | ```gradle
31 | repositories {
32 | jcenter()
33 | }
34 |
35 | dependencies {
36 | debugCompile 'com.nshmura:strictmode-notifier:0.9.3'
37 | releaseCompile 'com.nshmura:strictmode-notifier-no-op:0.9.3'
38 | }
39 | ```
40 |
41 | In your `Application` class:
42 |
43 | ```java
44 | public class ExampleApplication extends Application {
45 |
46 | @Override public void onCreate() {
47 | super.onCreate();
48 |
49 | if (BuildConfig.DEBUG) {
50 | //setup this library
51 | StrictModeNotifier.install(this);
52 |
53 | //setup StrictMode.
54 | //
55 | // penaltyLog() should be called for strictmode-notifier
56 | //
57 | new Handler().post(new Runnable() {
58 | @Override public void run() {
59 | StrictMode.ThreadPolicy threadPolicy = new StrictMode.ThreadPolicy.Builder()
60 | .detectAll()
61 | .permitDiskReads()
62 | .permitDiskWrites()
63 | .penaltyLog() // Must!
64 | .build();
65 | StrictMode.setThreadPolicy(threadPolicy);
66 |
67 | StrictMode.VmPolicy vmPolicy = new StrictMode.VmPolicy.Builder()
68 | .detectAll()
69 | .penaltyLog() // Must!
70 | .build();
71 | StrictMode.setVmPolicy(vmPolicy);
72 | }
73 | });
74 | }
75 | }
76 | }
77 | ```
78 |
79 | ## How does it work?
80 | 1. `strictmode-notifier` starts `logcat` command in backgound thread, and infinitely reads the log from `logcat`.
81 | 2. If StrictMode violation is happened, error logs is outputed.
82 | 3. `strictmode-notifier` reads that log via `logcat`, and shows a notification of the violation.
83 |
84 | ## Customizing
85 |
86 | ### How to ignore specific violations
87 |
88 | ```java
89 | StrictModeNotifier
90 | .install(context)
91 | .setIgnoreAction(new IgnoreAction() {
92 | @Override public boolean ignore(StrictModeViolation violation) {
93 | // ex) ignore LEAKED_CLOSABLE_OBJECTS that contains android.foo.bar in stacktrace.
94 | return violation.violationType == ViolationType.LEAKED_CLOSABLE_OBJECTS
95 | && violation.getStacktraceText().contains("android.foo.bar");
96 | }
97 | });
98 | ```
99 |
100 | ### How to add custom actions
101 |
102 | ```java
103 | StrictModeNotifier
104 | .install(context)
105 | .addCustomAction(new CustomAction() {
106 | @Override public void onViolation(StrictModeViolation violation) {
107 | //ex) Send messages into Slack
108 | }
109 | });
110 | ```
111 |
112 | ### How to disable Headup Notification
113 |
114 | ```java
115 | StrictModeNotifier
116 | .install(context)
117 | .setHeadupEnabled(false);
118 | ```
119 |
120 | ### How to enable debug mode of strictmode-notifier
121 |
122 | ```java
123 | StrictModeNotifier
124 | .install(context)
125 | .setDebugMode(true);
126 | ```
127 |
128 | ## Todo
129 | Parsing following violations
130 | - ActivityLeaks
131 | - LeakedRegistrationObjects
132 | - LeakedSqlLiteObjects
133 |
134 | ## Thanks
135 | Inspired by [square/leakcanary](https://github.com/square/leakcanary)
136 |
137 | ## License
138 | ```
139 | Copyright (C) 2016 nshmura
140 |
141 | Licensed under the Apache License, Version 2.0 (the "License");
142 | you may not use this file except in compliance with the License.
143 | You may obtain a copy of the License at
144 |
145 | http://www.apache.org/licenses/LICENSE-2.0
146 |
147 | Unless required by applicable law or agreed to in writing, software
148 | distributed under the License is distributed on an "AS IS" BASIS,
149 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
150 | See the License for the specific language governing permissions and
151 | limitations under the License.
152 | ```
153 |
--------------------------------------------------------------------------------
/assets/detail.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/assets/detail.png
--------------------------------------------------------------------------------
/assets/list.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/assets/list.png
--------------------------------------------------------------------------------
/assets/notification.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/assets/notification.png
--------------------------------------------------------------------------------
/assets/video.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/assets/video.gif
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.1.2'
9 | classpath 'com.novoda:bintray-release:0.3.4'
10 |
11 | // NOTE: Do not place your application dependencies here; they belong
12 | // in the individual module build.gradle files
13 | }
14 | }
15 |
16 | allprojects {
17 | repositories {
18 | jcenter()
19 | }
20 | }
21 |
22 | task clean(type: Delete) {
23 | delete rootProject.buildDir
24 | }
25 |
26 | ext {
27 | minSdkVersion = 9
28 | compileSdkVersion = 23
29 | targetSdkVersion = compileSdkVersion
30 | buildToolsVersion = '23.0.2'
31 | javaVersion = JavaVersion.VERSION_1_7
32 | supportLibraryVersion = '23.2.1'
33 | versionCode = 4
34 | versionName = "0.9.3"
35 |
36 | POM_DEVELOPER_ID = "nshmura"
37 | POM_GROUP = "com.nshmura"
38 | POM_VERSION_NAME = versionName
39 | POM_URL = "https://github.com/nshmura/strictmode-notifier"
40 |
41 | POM_ARTIFACT_ID = "strictmode-notifier"
42 | POM_ARTIFACT_NAME = "strictmode-notifier"
43 | POM_DESCRIPTION = "An Android library that report notification of StrictMode violation."
44 |
45 | POM_ARTIFACT_ID_NO_OP = "strictmode-notifier-no-op"
46 | POM_ARTIFACT_NAME_NO_OP = "strictmode-notifier-no-op"
47 | POM_DESCRIPTION_NO_OP = "No op strictmode-notifier"
48 | }
--------------------------------------------------------------------------------
/demo/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/demo/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion rootProject.ext.compileSdkVersion
5 | buildToolsVersion rootProject.ext.buildToolsVersion
6 |
7 | defaultConfig {
8 | applicationId "com.nshmura.strictmodenotifier.demo"
9 | minSdkVersion 11
10 | targetSdkVersion rootProject.ext.targetSdkVersion
11 | versionCode rootProject.ext.versionCode
12 | versionName rootProject.ext.versionName
13 | }
14 |
15 | signingConfigs {
16 | product {
17 | storeFile file("debug.keystore")
18 | storePassword "android"
19 | keyAlias "androiddebugkey"
20 | keyPassword "android"
21 | }
22 | }
23 |
24 | buildTypes {
25 | release {
26 | signingConfig signingConfigs.product
27 | minifyEnabled false
28 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
29 | }
30 | }
31 | }
32 |
33 | dependencies {
34 | compile fileTree(dir: 'libs', include: ['*.jar'])
35 | testCompile 'junit:junit:4.12'
36 | compile "com.android.support:appcompat-v7:$rootProject.ext.supportLibraryVersion"
37 |
38 | debugCompile project(":library")
39 | releaseCompile project(":library-no-op")
40 | //debugCompile "com.nshmura:strictmode-notifier:$rootProject.ext.versionName"
41 | //releaseCompile "com.nshmura:strictmode-notifier-no-op:$rootProject.ext.versionName"
42 | }
43 |
--------------------------------------------------------------------------------
/demo/debug.keystore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/demo/debug.keystore
--------------------------------------------------------------------------------
/demo/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/a13088/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/demo/src/androidTest/java/com/nshmura/strictmodenotifier/demo/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier.demo;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/demo/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/demo/src/main/java/com/nshmura/strictmodenotifier/demo/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier.demo;
2 |
3 | import android.os.Bundle;
4 | import android.os.StrictMode;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.view.View;
7 |
8 | public class MainActivity extends AppCompatActivity {
9 |
10 | @Override protected void onCreate(Bundle savedInstanceState) {
11 | super.onCreate(savedInstanceState);
12 | setContentView(R.layout.activity_main);
13 |
14 | //noinspection ConstantConditions
15 | findViewById(R.id.fire_error).setOnClickListener(new View.OnClickListener() {
16 | @Override public void onClick(View v) {
17 | StrictMode.noteSlowCall("fireSlowCall");
18 | }
19 | });
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/demo/src/main/java/com/nshmura/strictmodenotifier/demo/MainApplication.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier.demo;
2 |
3 | import android.app.Application;
4 | import android.os.Handler;
5 | import android.os.StrictMode;
6 | import com.nshmura.strictmodenotifier.CustomAction;
7 | import com.nshmura.strictmodenotifier.IgnoreAction;
8 | import com.nshmura.strictmodenotifier.StrictModeNotifier;
9 | import com.nshmura.strictmodenotifier.StrictModeViolation;
10 | import com.nshmura.strictmodenotifier.ViolationType;
11 |
12 | public class MainApplication extends Application {
13 |
14 | @Override public void onCreate() {
15 | super.onCreate();
16 |
17 | if (BuildConfig.DEBUG) {
18 | StrictModeNotifier
19 | .install(this)
20 | .setDebugMode(true)
21 | .setHeadupEnabled(true)
22 | .setIgnoreAction(new IgnoreAction() {
23 | @Override public boolean ignore(StrictModeViolation violation) {
24 | return violation.violationType == ViolationType.LEAKED_CLOSABLE_OBJECTS
25 | && violation.getStacktraceText().contains("android.foo.barr");
26 | }
27 | })
28 | .addCustomAction(new CustomAction() {
29 | @Override public void onViolation(StrictModeViolation violation) {
30 | //ex) Send messages into Slack
31 | }
32 | });
33 |
34 | //https://code.google.com/p/android/issues/detail?id=35298
35 | new Handler().post(new Runnable() {
36 | @Override public void run() {
37 | StrictMode.setThreadPolicy(
38 | new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
39 | }
40 | });
41 | }
42 | }
43 | }
--------------------------------------------------------------------------------
/demo/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/demo/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/demo/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/demo/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/demo/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/demo/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/demo/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/demo/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/demo/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/demo/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/demo/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | demo
3 |
4 |
--------------------------------------------------------------------------------
/demo/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/demo/src/test/java/com/nshmura/strictmodenotifier/demo/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier.demo;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class ExampleUnitTest {
11 | @Test public void addition_isCorrect() throws Exception {
12 | assertEquals(4, 2 + 2);
13 | }
14 | }
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 28 10:00:20 PST 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/library-common/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/library-common/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion rootProject.ext.compileSdkVersion
5 | buildToolsVersion rootProject.ext.buildToolsVersion
6 |
7 | defaultConfig {
8 | minSdkVersion rootProject.ext.minSdkVersion
9 | targetSdkVersion rootProject.ext.targetSdkVersion
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/library-common/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/library-common/src/main/java/com/nshmura/strictmodenotifier/CustomAction.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier;
2 |
3 | public interface CustomAction {
4 | void onViolation(StrictModeViolation violation);
5 | }
--------------------------------------------------------------------------------
/library-common/src/main/java/com/nshmura/strictmodenotifier/IgnoreAction.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier;
2 |
3 | public interface IgnoreAction {
4 | boolean ignore(StrictModeViolation violation);
5 | }
--------------------------------------------------------------------------------
/library-common/src/main/java/com/nshmura/strictmodenotifier/NotifierConfig.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | public class NotifierConfig {
7 |
8 | private static NotifierConfig instance;
9 |
10 | private List customActions = new ArrayList<>();
11 | private IgnoreAction ignoreAction;
12 | private boolean debugMode;
13 | private boolean headupEnabled = true;
14 |
15 | private NotifierConfig() {
16 |
17 | }
18 |
19 | public static NotifierConfig getInstance() {
20 | if (instance == null) {
21 | instance = new NotifierConfig();
22 | }
23 | return instance;
24 | }
25 |
26 | public NotifierConfig addCustomAction(CustomAction customAction) {
27 | customActions.add(customAction);
28 | return this;
29 | }
30 |
31 | public List getCustomActions() {
32 | return customActions;
33 | }
34 |
35 | public NotifierConfig setIgnoreAction(IgnoreAction ignoreAction) {
36 | this.ignoreAction = ignoreAction;
37 | return this;
38 | }
39 |
40 | public IgnoreAction getIgnoreAction() {
41 | return ignoreAction;
42 | }
43 |
44 | public boolean isDebugMode() {
45 | return debugMode;
46 | }
47 |
48 | public NotifierConfig setDebugMode(boolean debugMode) {
49 | this.debugMode = debugMode;
50 | return this;
51 | }
52 |
53 | public boolean isHeadupEnabled() {
54 | return headupEnabled;
55 | }
56 |
57 | public NotifierConfig setHeadupEnabled(boolean headupEnabled) {
58 | this.headupEnabled = headupEnabled;
59 | return this;
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/library-common/src/main/java/com/nshmura/strictmodenotifier/StrictModeViolation.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier;
2 |
3 | import android.content.Context;
4 | import android.text.format.DateUtils;
5 | import java.io.Serializable;
6 | import java.util.ArrayList;
7 |
8 | import static android.text.format.DateUtils.FORMAT_SHOW_DATE;
9 | import static android.text.format.DateUtils.FORMAT_SHOW_TIME;
10 |
11 | public class StrictModeViolation implements Serializable {
12 |
13 | public final ViolationType violationType;
14 | public final String message;
15 | public final String logKey;
16 | public final ArrayList stacktreace;
17 | public final long time;
18 |
19 | public StrictModeViolation(ViolationType violationType, String message, String logKey,
20 | ArrayList stacktreace, long time) {
21 | this.violationType = violationType;
22 | this.message = message;
23 | this.logKey = logKey;
24 | this.stacktreace = stacktreace;
25 | this.time = time;
26 | }
27 |
28 | public String getDateText(Context context) {
29 | return DateUtils.formatDateTime(context, time, FORMAT_SHOW_TIME | FORMAT_SHOW_DATE);
30 | }
31 |
32 | public String getStacktraceText() {
33 | StringBuilder builder = new StringBuilder();
34 | for (String line : stacktreace) {
35 | if (builder.length() > 0) {
36 | builder.append("\n");
37 | }
38 | builder.append(line);
39 | }
40 | return builder.toString();
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/library-common/src/main/java/com/nshmura/strictmodenotifier/ViolationType.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier;
2 |
3 | public enum ViolationType {
4 |
5 | // ThreadPolicy
6 | CUSTOM_SLOW_CALL,
7 | NETWORK,
8 | RESOURCE_MISMATCHES,
9 |
10 | // VmPolicy
11 | CLASS_INSTANCE_LIMIT,
12 | CLEARTEXT_NETWORK,
13 | FILE_URI_EXPOSURE,
14 | LEAKED_CLOSABLE_OBJECTS,
15 | ACTIVITY_LEAKS,
16 | LEAKED_REGISTRATION_OBJECTS,
17 | LEAKED_SQL_LITE_OBJECTS,
18 |
19 | //UNKNOWN
20 | UNKNOWN
21 | }
22 |
--------------------------------------------------------------------------------
/library-no-op/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/library-no-op/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.novoda.bintray-release'
3 |
4 | android {
5 | compileSdkVersion rootProject.ext.compileSdkVersion
6 | buildToolsVersion rootProject.ext.buildToolsVersion
7 |
8 | defaultConfig {
9 | minSdkVersion rootProject.ext.minSdkVersion
10 | targetSdkVersion rootProject.ext.targetSdkVersion
11 | }
12 |
13 | sourceSets {
14 | main.java.srcDirs += ['../library-common/src/main/java/']
15 | }
16 | }
17 |
18 | publish {
19 | userOrg = rootProject.ext.POM_DEVELOPER_ID
20 | groupId = rootProject.ext.POM_GROUP
21 | artifactId = rootProject.ext.POM_ARTIFACT_ID_NO_OP
22 | uploadName = rootProject.ext.POM_ARTIFACT_NAME_NO_OP
23 | publishVersion = rootProject.ext.POM_VERSION_NAME
24 | desc = rootProject.ext.POM_DESCRIPTION_NO_OP
25 | website = rootProject.ext.POM_URL
26 | }
--------------------------------------------------------------------------------
/library-no-op/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/library-no-op/src/main/java/com/nshmura/strictmodenotifier/StrictModeNotifier.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier;
2 |
3 | import android.content.Context;
4 |
5 | public class StrictModeNotifier {
6 |
7 | public static NotifierConfig install(Context context) {
8 | //no-op
9 | return NotifierConfig.getInstance();
10 | }
11 | }
--------------------------------------------------------------------------------
/library/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/library/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.novoda.bintray-release'
3 |
4 | android {
5 | compileSdkVersion rootProject.ext.compileSdkVersion
6 | buildToolsVersion rootProject.ext.buildToolsVersion
7 |
8 | defaultConfig {
9 | minSdkVersion rootProject.ext.minSdkVersion
10 | targetSdkVersion rootProject.ext.targetSdkVersion
11 | }
12 |
13 | sourceSets {
14 | main.java.srcDirs += ['../library-common/src/main/java/']
15 | }
16 | }
17 |
18 | publish {
19 | userOrg = rootProject.ext.POM_DEVELOPER_ID
20 | groupId = rootProject.ext.POM_GROUP
21 | artifactId = rootProject.ext.POM_ARTIFACT_ID
22 | uploadName = rootProject.ext.POM_ARTIFACT_NAME
23 | publishVersion = rootProject.ext.POM_VERSION_NAME
24 | desc = rootProject.ext.POM_DESCRIPTION
25 | website = rootProject.ext.POM_URL
26 | }
--------------------------------------------------------------------------------
/library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
9 |
10 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/library/src/main/java/com/nshmura/strictmodenotifier/LogWatchService.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier;
2 |
3 | import android.app.IntentService;
4 | import android.content.Intent;
5 | import android.text.TextUtils;
6 | import android.util.Log;
7 | import java.io.BufferedReader;
8 | import java.io.IOException;
9 | import java.io.InputStreamReader;
10 | import java.util.ArrayList;
11 | import java.util.List;
12 | import java.util.Timer;
13 | import java.util.TimerTask;
14 |
15 | public class LogWatchService extends IntentService {
16 |
17 | private static final String THREAD_NAME = LogWatchService.class.getSimpleName();
18 | private static final String TAG = THREAD_NAME;
19 |
20 | private static final String LOGCAT_COMMAND = "logcat -v time -s StrictMode:* System.err:*";
21 | private static final java.lang.String PARSE_REGEXP = "(StrictMode|System.err)(\\([ 0-9]+\\))?:";
22 | private static final CharSequence EXCEPTION_KEY = "System.err";
23 |
24 | private static final long NOTIFICATION_DELAY = 2000; //ms
25 | private static final long LOG_DELAY = 1000; //ms
26 | private static final long EXIT_SPAN = 1000 * 60; //ms
27 |
28 | private NotifierConfig notifierConfig = NotifierConfig.getInstance();
29 | private Process proc;
30 | private final ViolationStore violationStore;
31 | private List logs = new ArrayList<>();
32 | private Timer timer = null;
33 | private ViolationType[] violationTypes = ViolationType.values();
34 |
35 | public LogWatchService() {
36 | this(TAG);
37 | }
38 |
39 | public LogWatchService(String name) {
40 | super(name);
41 | violationStore = new ViolationStore(this);
42 | }
43 |
44 | @Override public int onStartCommand(Intent intent, int flags, int startId) {
45 | super.onStartCommand(intent, flags, startId);
46 | return START_STICKY;
47 | }
48 |
49 | @Override protected void onHandleIntent(Intent intent) {
50 | startReadLoop();
51 | }
52 |
53 | @Override public void onDestroy() {
54 | super.onDestroy();
55 | log("onDestroy");
56 |
57 | if (proc != null) {
58 | proc.destroy();
59 | proc = null;
60 | }
61 | }
62 |
63 | /**
64 | * notify the StrictModeViolation.
65 | *
66 | * @param violation StrictModeViolation
67 | */
68 | protected void notifyViolation(StrictModeViolation violation) {
69 | //Custom Actions
70 | List customActions = notifierConfig.getCustomActions();
71 | for (CustomAction customAction : customActions) {
72 | customAction.onViolation(violation);
73 | }
74 |
75 | //Default Action
76 | String notificationTitle;
77 | if (violation.violationType != null) {
78 | notificationTitle = ViolationTypeInfo.convert(violation.violationType).violationName();
79 | } else {
80 | notificationTitle = getString(R.string.strictmode_notifier_title, getPackageName());
81 | }
82 | StrictModeNotifierInternals.showNotification(this, notificationTitle,
83 | getString(R.string.strictmode_notifier_more_detail), notifierConfig.isHeadupEnabled(),
84 | StrictModeReportActivity.createPendingIntent(this, violation));
85 | }
86 |
87 | private void startReadLoop() {
88 | while (true) {
89 | long startTime = System.currentTimeMillis();
90 |
91 | log("start readLoop");
92 |
93 | readLoop();
94 |
95 | log("end readLoop");
96 |
97 | if (System.currentTimeMillis() - startTime <= EXIT_SPAN) {
98 | log("exit readLoop");
99 | break;
100 | }
101 | }
102 | }
103 |
104 | private void readLoop() {
105 | BufferedReader reader = null;
106 | try {
107 | //clear log
108 | Runtime.getRuntime().exec("logcat -c");
109 |
110 | //read only StrictMode error
111 | proc = Runtime.getRuntime().exec(LOGCAT_COMMAND);
112 | reader = new BufferedReader(new InputStreamReader(proc.getInputStream()), 1024);
113 |
114 | while (true) {
115 | String line = reader.readLine();
116 | if (line != null && line.length() != 0) {
117 | log(line);
118 |
119 | StrictModeLog log = parseLine(line);
120 | if (log != null) {
121 | storeLog(log);
122 | startReportTimer();
123 | }
124 | } else {
125 | error("error readLoop");
126 | break;
127 | }
128 | }
129 | } catch (IOException e) {
130 | error(e.getMessage());
131 | } finally {
132 | if (reader != null) {
133 | try {
134 | reader.close();
135 | } catch (IOException e) {
136 | //ignore
137 | }
138 | }
139 | }
140 | }
141 |
142 | private StrictModeLog parseLine(String line) {
143 | String[] split = line.split(PARSE_REGEXP);
144 | if (split.length < 2) {
145 | return null;
146 | }
147 | if (split[1].equals("null")) {
148 | return null;
149 | }
150 | return new StrictModeLog(split[0], split[1], System.currentTimeMillis());
151 | }
152 |
153 | private void storeLog(StrictModeLog log) {
154 | synchronized (this) {
155 | logs.add(log);
156 | }
157 | }
158 |
159 | private void startReportTimer() {
160 | synchronized (this) {
161 | if (timer != null) {
162 | return;
163 | }
164 | timer = new Timer(true);
165 | }
166 |
167 | timer.schedule(new TimerTask() {
168 | @Override public void run() {
169 | synchronized (LogWatchService.this) {
170 |
171 | int count = logs.size();
172 | boolean prevIsAt = false;
173 | long lastReadTime = 0;
174 | List targets = new ArrayList<>();
175 |
176 | for (int i = 0; i < count; i++) {
177 | StrictModeLog log = logs.get(i);
178 |
179 | boolean isAt = log.isAt();
180 | if (!isAt && prevIsAt && targets.size() > 0) {
181 | StrictModeViolation report = createViolation(targets);
182 | if (report != null && StringModeConfig.from(LogWatchService.this).isEnabled()) {
183 | storeViolation(report);
184 | notifyViolation(report);
185 | }
186 | targets.clear();
187 | }
188 | prevIsAt = isAt;
189 | targets.add(log);
190 | lastReadTime = log.time;
191 | }
192 |
193 | if (targets.size() > 0 && System.currentTimeMillis() - lastReadTime >= LOG_DELAY) {
194 | StrictModeViolation report = createViolation(targets);
195 | if (report != null && StringModeConfig.from(LogWatchService.this).isEnabled()) {
196 | storeViolation(report);
197 | notifyViolation(report);
198 | }
199 | targets.clear();
200 | }
201 | timer = null;
202 |
203 | if (targets.size() > 0) {
204 | logs = targets;
205 | startReportTimer();
206 | } else {
207 | logs.clear();
208 | }
209 | }
210 | }
211 | }, NOTIFICATION_DELAY);
212 | }
213 |
214 | private StrictModeViolation createViolation(List logs) {
215 | ArrayList stacktreace = new ArrayList<>(logs.size());
216 | String title = "";
217 | String logKey = "";
218 | long time = 0;
219 | for (StrictModeLog log : logs) {
220 | if (TextUtils.isEmpty(title)) {
221 | title = log.message;
222 | logKey = log.tag;
223 | time = log.time;
224 | }
225 | stacktreace.add(log.message);
226 | }
227 |
228 | ViolationType violationType = getViolationType(logs);
229 | if (violationType == ViolationType.UNKNOWN && logKey.contains(EXCEPTION_KEY)) {
230 | return null;
231 | }
232 |
233 | StrictModeViolation violation =
234 | new StrictModeViolation(violationType, title, logKey, stacktreace, time);
235 |
236 | //Ignore Action
237 | if (notifierConfig.getIgnoreAction() != null) {
238 | if (notifierConfig.getIgnoreAction().ignore(violation)) {
239 | return null;
240 | }
241 | }
242 |
243 | return violation;
244 | }
245 |
246 | private void storeViolation(StrictModeViolation violation) {
247 | try {
248 | violationStore.append(violation);
249 | } catch (IOException e) {
250 | e.printStackTrace();
251 | }
252 | }
253 |
254 | private ViolationType getViolationType(List logs) {
255 | for (StrictModeLog log : logs) {
256 | for (ViolationType type : violationTypes) {
257 | ViolationTypeInfo info = ViolationTypeInfo.convert(type);
258 | if (info != null && info.detector.detect(log)) {
259 | return type;
260 | }
261 | }
262 | }
263 | return ViolationType.UNKNOWN;
264 | }
265 |
266 | private void log(String message) {
267 | if (notifierConfig.isDebugMode()) {
268 | Log.d(TAG, message);
269 | }
270 | }
271 |
272 | private void error(String message) {
273 | if (notifierConfig.isDebugMode()) {
274 | Log.e(TAG, message);
275 | }
276 | }
277 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/nshmura/strictmodenotifier/ReportActivityUtils.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier;
2 |
3 | import android.app.ActionBar;
4 | import android.app.Activity;
5 | import android.os.Build;
6 |
7 | /**
8 | * @author nishimura_shinichi
9 | */
10 | class ReportActivityUtils {
11 | public static void setTitle(Activity activity, String title) {
12 | if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
13 | ActionBar actionBar = activity.getActionBar();
14 | //noinspection ConstantConditions
15 | actionBar.setTitle(title);
16 | }
17 | }
18 |
19 | public static void setDisplayHomeAsUpEnabled(Activity activity, boolean enabled) {
20 | if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
21 | ActionBar actionBar = activity.getActionBar();
22 | //noinspection ConstantConditions
23 | actionBar.setDisplayHomeAsUpEnabled(enabled);
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/library/src/main/java/com/nshmura/strictmodenotifier/ReportAdapter.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier;
2 |
3 | import android.view.LayoutInflater;
4 | import android.view.View;
5 | import android.view.ViewGroup;
6 | import android.widget.BaseAdapter;
7 | import android.widget.TextView;
8 | import java.util.ArrayList;
9 | import java.util.List;
10 |
11 | class ReportAdapter extends BaseAdapter {
12 | List reports = new ArrayList<>();
13 | private StrictModeReportActivity reportActivity;
14 |
15 | public ReportAdapter(StrictModeReportActivity reportActivity) {
16 | this.reportActivity = reportActivity;
17 | }
18 |
19 | @Override public int getCount() {
20 | return reports.size();
21 | }
22 |
23 | @Override public StrictModeViolation getItem(int position) {
24 | return reports.get(position);
25 | }
26 |
27 | @Override public long getItemId(int position) {
28 | return position;
29 | }
30 |
31 | @Override public View getView(int position, View convertView, ViewGroup parent) {
32 | StrictModeViolation report = getItem(position);
33 |
34 | if (convertView == null) {
35 | convertView = LayoutInflater.from(reportActivity)
36 | .inflate(R.layout.strictmode_notifier_row, parent, false);
37 | convertView.setTag(new ViewHolder(convertView));
38 | }
39 |
40 | ViewHolder holder = (ViewHolder) convertView.getTag();
41 | holder.numberText.setText(
42 | parent.getContext().getString(R.string.strictmode_notifier_count, getCount() - position));
43 | holder.dateText.setText(report.getDateText(reportActivity));
44 |
45 | if (report.violationType != null) {
46 | holder.violationTypeText.setText(
47 | ViolationTypeInfo.convert(report.violationType).violationName());
48 | } else {
49 | holder.violationTypeText.setText(report.message);
50 | }
51 |
52 | return convertView;
53 | }
54 |
55 | public void addAll(List reports) {
56 | this.reports.addAll(reports);
57 | }
58 |
59 | public void clear() {
60 | this.reports.clear();
61 | }
62 |
63 | private class ViewHolder {
64 | final TextView numberText;
65 | final TextView violationTypeText;
66 | final TextView dateText;
67 |
68 | public ViewHolder(View convertView) {
69 | numberText = (TextView) convertView.findViewById(R.id.__number);
70 | violationTypeText = (TextView) convertView.findViewById(R.id.__violation_type);
71 | dateText = (TextView) convertView.findViewById(R.id.__date);
72 | }
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/library/src/main/java/com/nshmura/strictmodenotifier/StrictModeLog.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier;
2 |
3 | public class StrictModeLog {
4 | public final String tag;
5 | public final String message;
6 | public final long time;
7 |
8 | public StrictModeLog(String tag, String message, long time) {
9 | this.tag = tag;
10 | this.message = message;
11 | this.time = time;
12 | }
13 |
14 | public boolean isAt() {
15 | return message.matches("^\\s+at.*");
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/library/src/main/java/com/nshmura/strictmodenotifier/StrictModeNotifier.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier;
2 |
3 | import android.content.Context;
4 |
5 | public class StrictModeNotifier {
6 |
7 | public static NotifierConfig install(Context context) {
8 | return install(context, LogWatchService.class);
9 | }
10 |
11 | public static NotifierConfig install(Context context,
12 | Class extends LogWatchService> serviceClass) {
13 | StrictModeNotifierInternals.enableReportActivity(context);
14 | StrictModeNotifierInternals.startLogWatchService(context, serviceClass);
15 | return NotifierConfig.getInstance();
16 | }
17 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/nshmura/strictmodenotifier/StrictModeNotifierInternals.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier;
2 |
3 | import android.annotation.TargetApi;
4 | import android.app.Notification;
5 | import android.app.NotificationManager;
6 | import android.app.PendingIntent;
7 | import android.content.ComponentName;
8 | import android.content.Context;
9 | import android.content.Intent;
10 | import android.content.pm.PackageManager;
11 | import android.os.Build;
12 | import java.lang.reflect.Method;
13 | import java.util.concurrent.Executor;
14 | import java.util.concurrent.Executors;
15 |
16 | import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
17 | import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
18 | import static android.content.pm.PackageManager.DONT_KILL_APP;
19 | import static android.os.Build.VERSION.SDK_INT;
20 | import static android.os.Build.VERSION_CODES.HONEYCOMB;
21 | import static android.os.Build.VERSION_CODES.JELLY_BEAN;
22 | import static android.os.Build.VERSION_CODES.LOLLIPOP;
23 |
24 | final class StrictModeNotifierInternals {
25 |
26 | private static final Executor fileIoExecutor = newSingleThreadExecutor("File-IO");
27 | private static final int NOTIFICATION_ID = 1;
28 |
29 | public static void enableReportActivity(Context context) {
30 | StrictModeNotifierInternals.setEnabled(context, StrictModeReportActivity.class, true);
31 | }
32 |
33 | public static void startLogWatchService(Context context,
34 | Class extends LogWatchService> serviceClass) {
35 | Intent intent = new Intent(context, serviceClass);
36 | context.startService(intent);
37 | }
38 |
39 | public static void setEnabled(Context context, final Class> componentClass,
40 | final boolean enabled) {
41 | final Context appContext = context.getApplicationContext();
42 | executeOnFileIoThread(new Runnable() {
43 | @Override public void run() {
44 | setEnabledBlocking(appContext, componentClass, enabled);
45 | }
46 | });
47 | }
48 |
49 | public static void setEnabledBlocking(Context appContext, Class> componentClass,
50 | boolean enabled) {
51 | ComponentName component = new ComponentName(appContext, componentClass);
52 | PackageManager packageManager = appContext.getPackageManager();
53 | int newState = enabled ? COMPONENT_ENABLED_STATE_ENABLED : COMPONENT_ENABLED_STATE_DISABLED;
54 | // Blocks on IPC.
55 | packageManager.setComponentEnabledSetting(component, newState, DONT_KILL_APP);
56 | }
57 |
58 | public static void executeOnFileIoThread(Runnable runnable) {
59 | fileIoExecutor.execute(runnable);
60 | }
61 |
62 | public static Executor newSingleThreadExecutor(String threadName) {
63 | return Executors.newSingleThreadExecutor(new StrictModeNotifierSingleThreadFactory(threadName));
64 | }
65 |
66 | public static void showNotification(Context context, CharSequence contentTitle,
67 | CharSequence contentText, boolean headupEnabled, PendingIntent pendingIntent) {
68 |
69 | if (SDK_INT < HONEYCOMB) {
70 | showNotificationFor9(context, contentTitle, contentText, pendingIntent);
71 | } else {
72 | Notification.Builder builder = new Notification.Builder(context).setSmallIcon(
73 | R.drawable.strictmode_notifier_ic_notification)
74 | .setWhen(System.currentTimeMillis())
75 | .setContentTitle(contentTitle)
76 | .setContentText(contentText)
77 | .setAutoCancel(true)
78 | .setContentIntent(pendingIntent);
79 |
80 | if (SDK_INT < JELLY_BEAN) {
81 | showNotificationFor11(context, builder);
82 | } else {
83 | showNotificationFor16(context, headupEnabled, pendingIntent, builder);
84 | }
85 | }
86 | }
87 |
88 | private static void showNotificationFor9(Context context, CharSequence contentTitle,
89 | CharSequence contentText, PendingIntent pendingIntent) {
90 |
91 | Notification notification = new Notification();
92 | //noinspection deprecation
93 | notification.icon = R.drawable.strictmode_notifier_ic_notification;
94 | notification.when = System.currentTimeMillis();
95 | notification.flags |= Notification.FLAG_AUTO_CANCEL;
96 | try {
97 | Method method =
98 | Notification.class.getMethod("setLatestEventInfo", Context.class, CharSequence.class,
99 | CharSequence.class, PendingIntent.class);
100 | method.invoke(notification, context, contentTitle, contentText, pendingIntent);
101 | } catch (Exception e) {
102 | throw new RuntimeException(e);
103 | }
104 |
105 | getNotificationManager(context).notify(NOTIFICATION_ID, notification);
106 | }
107 |
108 | @TargetApi(Build.VERSION_CODES.HONEYCOMB)
109 | private static void showNotificationFor11(Context context, Notification.Builder builder) {
110 | //noinspection deprecation
111 | getNotificationManager(context).notify(NOTIFICATION_ID, builder.getNotification());
112 | }
113 |
114 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
115 | private static void showNotificationFor16(Context context, boolean headupEnabled,
116 | PendingIntent pendingIntent, Notification.Builder builder) {
117 |
118 | if (SDK_INT >= LOLLIPOP && headupEnabled) {
119 | builder.setFullScreenIntent(pendingIntent, true);
120 | }
121 |
122 | getNotificationManager(context).notify(NOTIFICATION_ID, builder.build());
123 | }
124 |
125 | private static NotificationManager getNotificationManager(Context context) {
126 | return (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
127 | }
128 | }
129 |
--------------------------------------------------------------------------------
/library/src/main/java/com/nshmura/strictmodenotifier/StrictModeNotifierSingleThreadFactory.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier;
2 |
3 | import java.util.concurrent.ThreadFactory;
4 |
5 | /**
6 | * This is intended to only be used with a single thread executor.
7 | */
8 | final class StrictModeNotifierSingleThreadFactory implements ThreadFactory {
9 |
10 | private final String threadName;
11 |
12 | StrictModeNotifierSingleThreadFactory(String threadName) {
13 | this.threadName = "StrictModeNotifier-" + threadName;
14 | }
15 |
16 | @Override public Thread newThread(Runnable runnable) {
17 | return new Thread(runnable, threadName);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/library/src/main/java/com/nshmura/strictmodenotifier/StrictModeReportActivity.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier;
2 |
3 | import android.app.Activity;
4 | import android.app.PendingIntent;
5 | import android.content.Context;
6 | import android.content.Intent;
7 | import android.os.Bundle;
8 | import android.view.View;
9 | import android.widget.AdapterView;
10 | import android.widget.CompoundButton;
11 | import android.widget.ListView;
12 | import android.widget.ToggleButton;
13 | import java.util.List;
14 |
15 | import static android.app.PendingIntent.FLAG_UPDATE_CURRENT;
16 |
17 | public class StrictModeReportActivity extends Activity {
18 |
19 | private static final String EXTRA_REPORT = "EXTRA_REPORT";
20 |
21 | private ReportAdapter adapter;
22 | private ViolationStore violationStore;
23 |
24 | @Override protected void onCreate(Bundle savedInstanceState) {
25 | super.onCreate(savedInstanceState);
26 | setContentView(R.layout.strictmode_notifier_activity_report);
27 |
28 | ReportActivityUtils.setTitle(this,
29 | getString(R.string.strictmode_notifier_title, getPackageName()));
30 |
31 | adapter = new ReportAdapter(this);
32 | ListView listView = (ListView) findViewById(R.id.__list_view);
33 | //noinspection ConstantConditions
34 | listView.setAdapter(adapter);
35 |
36 | violationStore = new ViolationStore(this);
37 | listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
38 | @Override public void onItemClick(AdapterView> parent, View view, int position, long id) {
39 | StrictModeViolation report = adapter.getItem(position);
40 | StrictModeReportDetailActivity.start(StrictModeReportActivity.this, report);
41 | }
42 | });
43 |
44 | ToggleButton toggleButton = (ToggleButton) findViewById(R.id.__enable_button);
45 | toggleButton.setChecked(StringModeConfig.from(this).isEnabled());
46 | toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
47 | @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
48 | StringModeConfig.from(StrictModeReportActivity.this).toggle();
49 | }
50 | });
51 |
52 | //noinspection ConstantConditions
53 | findViewById(R.id.__delete_button).setOnClickListener(new View.OnClickListener() {
54 | @Override public void onClick(View v) {
55 | violationStore.clear();
56 | adapter.clear();
57 | adapter.notifyDataSetChanged();
58 | }
59 | });
60 |
61 | if (savedInstanceState == null) {
62 | StrictModeViolation report = (StrictModeViolation) getIntent().getSerializableExtra(EXTRA_REPORT);
63 | if (report != null) {
64 | StrictModeReportDetailActivity.start(this, report);
65 | }
66 | }
67 | }
68 |
69 | @Override protected void onResume() {
70 | super.onResume();
71 |
72 | List reports = violationStore.getAll();
73 | adapter.clear();
74 | adapter.addAll(reports);
75 | adapter.notifyDataSetChanged();
76 | }
77 |
78 | public static Intent createIntent(Context context, StrictModeViolation report) {
79 | Intent intent = new Intent(context, StrictModeReportActivity.class);
80 | intent.putExtra(EXTRA_REPORT, report);
81 | return intent;
82 | }
83 |
84 | public static PendingIntent createPendingIntent(Context context, StrictModeViolation report) {
85 | Intent intent = StrictModeReportActivity.createIntent(context, report);
86 | intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
87 | return PendingIntent.getActivity(context, 1, intent, FLAG_UPDATE_CURRENT);
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/library/src/main/java/com/nshmura/strictmodenotifier/StrictModeReportDetailActivity.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier;
2 |
3 | import android.annotation.TargetApi;
4 | import android.app.Activity;
5 | import android.content.ClipData;
6 | import android.content.ClipboardManager;
7 | import android.content.Context;
8 | import android.content.Intent;
9 | import android.graphics.Color;
10 | import android.os.Build;
11 | import android.os.Bundle;
12 | import android.text.Spannable;
13 | import android.text.SpannableString;
14 | import android.text.style.ForegroundColorSpan;
15 | import android.text.style.StyleSpan;
16 | import android.view.Menu;
17 | import android.view.MenuInflater;
18 | import android.view.MenuItem;
19 | import android.view.View;
20 | import android.widget.TextView;
21 | import android.widget.Toast;
22 |
23 | public class StrictModeReportDetailActivity extends Activity {
24 |
25 | private static final String EXTRA_REPORT = "EXTRA_REPORT";
26 |
27 | private ViolationStore violationStore;
28 | private StrictModeViolation report;
29 |
30 | @Override protected void onCreate(Bundle savedInstanceState) {
31 | super.onCreate(savedInstanceState);
32 | setContentView(R.layout.strictmode_notifier_activity_report_detail);
33 |
34 | violationStore = new ViolationStore(StrictModeReportDetailActivity.this);
35 |
36 | report = (StrictModeViolation) getIntent().getSerializableExtra(EXTRA_REPORT);
37 |
38 | TextView stackTreace = (TextView) findViewById(R.id.__stacktrace_text);
39 |
40 | final String stacktraceText = report.getStacktraceText();
41 | final Spannable span = new SpannableString(stacktraceText);
42 |
43 | setColor(span, stacktraceText, getPackageName(), Color.WHITE);
44 |
45 | stackTreace.setText(span);
46 |
47 | if (report.violationType != null) {
48 | ReportActivityUtils.setTitle(this,
49 | ViolationTypeInfo.convert(report.violationType).violationName());
50 | ReportActivityUtils.setDisplayHomeAsUpEnabled(this, true);
51 | }
52 |
53 | findViewById(R.id.__delete_button).setOnClickListener(new View.OnClickListener() {
54 | @Override public void onClick(View v) {
55 | violationStore.remove(report);
56 | finish();
57 | }
58 | });
59 | }
60 |
61 | @Override public boolean onMenuItemSelected(int featureId, MenuItem item) {
62 | switch (item.getItemId()) {
63 | case android.R.id.home:
64 | finish();
65 | break;
66 | }
67 | return super.onMenuItemSelected(featureId, item);
68 | }
69 |
70 | @Override public boolean onCreateOptionsMenu(Menu menu) {
71 | MenuInflater inflater = getMenuInflater();
72 | inflater.inflate(R.menu.strictmode_notifier_menu, menu);
73 |
74 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
75 | menu.removeItem(R.id.__menu_copy);
76 | }
77 |
78 | return true;
79 | }
80 |
81 | @Override public boolean onOptionsItemSelected(MenuItem item) {
82 | int itemId = item.getItemId();
83 | if (itemId == R.id.__menu_copy) {
84 | copy();
85 | return true;
86 | } else if (itemId == R.id.__menu_share) {
87 | share();
88 | return true;
89 | } else {
90 | return super.onOptionsItemSelected(item);
91 | }
92 | }
93 |
94 | @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void copy() {
95 | ClipData clip = ClipData.newPlainText("info", shareText());
96 | ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
97 | clipboard.setPrimaryClip(clip);
98 | Toast.makeText(this, R.string.strictmode_notifier_copyped, Toast.LENGTH_LONG).show();
99 | }
100 |
101 | private void share() {
102 | Intent sendIntent = new Intent();
103 | sendIntent.setAction(Intent.ACTION_SEND);
104 | sendIntent.putExtra(Intent.EXTRA_TEXT, shareText());
105 | sendIntent.setType("text/plain");
106 |
107 | try {
108 | startActivity(Intent.createChooser(sendIntent,
109 | getResources().getText(R.string.strictmode_notifier_menu_share)));
110 | } catch (Exception e) {
111 | e.printStackTrace();
112 | }
113 | }
114 |
115 | private String shareText() {
116 | String shareText;
117 | if (report.violationType != null) {
118 | shareText = ViolationTypeInfo.convert(report.violationType).violationName();
119 | shareText += "\n\n" + report.getStacktraceText();
120 | } else {
121 | shareText = report.getStacktraceText();
122 | }
123 | return shareText;
124 | }
125 |
126 | public static void start(Context context, StrictModeViolation report) {
127 | context.startActivity(createIntent(context, report));
128 | }
129 |
130 | public static Intent createIntent(Context context, StrictModeViolation report) {
131 | Intent intent = new Intent(context, StrictModeReportDetailActivity.class);
132 | intent.putExtra(EXTRA_REPORT, report);
133 | return intent;
134 | }
135 |
136 | public void setColor(Spannable span, String stacktraceText, String hilight, int color) {
137 | final int length = hilight.length();
138 |
139 | int start = 0;
140 | while (true) {
141 | int index = stacktraceText.indexOf(hilight, start);
142 | if (index < 0) {
143 | break;
144 | }
145 |
146 | span.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), index, index + length,
147 | Spannable.SPAN_INCLUSIVE_INCLUSIVE);
148 |
149 | span.setSpan(new ForegroundColorSpan(color), index, index + length,
150 | Spannable.SPAN_INCLUSIVE_INCLUSIVE);
151 |
152 | start = index + length;
153 | }
154 | }
155 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/nshmura/strictmodenotifier/StringModeConfig.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier;
2 |
3 | import android.content.Context;
4 | import android.content.SharedPreferences;
5 |
6 | class StringModeConfig {
7 | private static final String NAME = "strictmode";
8 | private static final String KEY = "config";
9 |
10 | private final Context context;
11 |
12 | public static StringModeConfig from(Context context) {
13 | return new StringModeConfig(context);
14 | }
15 |
16 | StringModeConfig(Context context) {
17 | this.context = context;
18 | }
19 |
20 | public boolean isEnabled() {
21 | return getPrefs().getBoolean(KEY, true);
22 | }
23 |
24 | public void enable(boolean enabled) {
25 | getPrefs().edit().putBoolean(KEY, enabled).apply();
26 | }
27 |
28 | public void toggle() {
29 | enable(!isEnabled());
30 | }
31 |
32 | private SharedPreferences getPrefs() {
33 | return context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/library/src/main/java/com/nshmura/strictmodenotifier/ViolationStore.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier;
2 |
3 | import android.content.Context;
4 | import android.content.SharedPreferences;
5 | import android.util.Base64;
6 | import java.io.ByteArrayInputStream;
7 | import java.io.ByteArrayOutputStream;
8 | import java.io.IOException;
9 | import java.io.ObjectInputStream;
10 | import java.io.ObjectOutputStream;
11 | import java.io.Serializable;
12 | import java.util.ArrayList;
13 |
14 | class ViolationStore {
15 | private static final String NAME = "strictmode";
16 | private static final String KEY = "reports";
17 | private static final int MAX_REPORTS = 50;
18 |
19 | private final Context context;
20 |
21 | ViolationStore(Context context) {
22 | this.context = context;
23 | }
24 |
25 | /**
26 | * Read the object from Base64 string.
27 | *
28 | * @see {http://stackoverflow.com/questions/134492/how-to-serialize-an-object-into-a-string}
29 | */
30 | private static Object fromString(String s) throws IOException, ClassNotFoundException {
31 | byte[] data = Base64.decode(s, Base64.DEFAULT);
32 | ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
33 | Object o = ois.readObject();
34 | ois.close();
35 | return o;
36 | }
37 |
38 | /**
39 | * Write the object to a Base64 string.
40 | *
41 | * @see {http://stackoverflow.com/questions/134492/how-to-serialize-an-object-into-a-string}
42 | */
43 | private static String toString(Serializable o) throws IOException {
44 | ByteArrayOutputStream baos = new ByteArrayOutputStream();
45 | ObjectOutputStream oos = new ObjectOutputStream(baos);
46 | oos.writeObject(o);
47 | oos.close();
48 | return Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
49 | }
50 |
51 | public ArrayList getAll() {
52 | try {
53 | String serialized = getPrefs().getString(KEY, null);
54 | if (serialized != null) {
55 | //noinspection unchecked
56 | return (ArrayList) fromString(serialized);
57 | }
58 | } catch (Exception e) {
59 | //ignore
60 | }
61 | return new ArrayList<>();
62 | }
63 |
64 | public void append(StrictModeViolation report) throws IOException {
65 | ArrayList reports = getAll();
66 |
67 | if (reports.size() > MAX_REPORTS) {
68 | reports.subList(0, MAX_REPORTS);
69 | }
70 |
71 | reports.add(0, report);
72 | getPrefs().edit().putString(KEY, toString(reports)).apply();
73 | }
74 |
75 | public void remove(StrictModeViolation target) {
76 | ArrayList reports = getAll();
77 | Integer targetIndex = null;
78 | for(int i = 0; i < reports.size(); i++) {
79 | StrictModeViolation report = reports.get(i);
80 | if (report.logKey.equals(target.logKey) && report.time == target.time) {
81 | targetIndex = i;
82 | break;
83 | }
84 | }
85 | if (targetIndex != null) {
86 | reports.remove(targetIndex.intValue());
87 | try {
88 | getPrefs().edit().putString(KEY, toString(reports)).apply();
89 | } catch (IOException e) {
90 | e.printStackTrace();
91 | }
92 | }
93 | }
94 |
95 | public void clear() {
96 | getPrefs().edit().clear().apply();
97 | }
98 |
99 | private SharedPreferences getPrefs() {
100 | return context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
101 | }
102 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/nshmura/strictmodenotifier/ViolationTypeInfo.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier;
2 |
3 | import android.os.Build;
4 | import com.nshmura.strictmodenotifier.detector.ClassInstanceLimitDetector;
5 | import com.nshmura.strictmodenotifier.detector.CleartextNetworkDetector;
6 | import com.nshmura.strictmodenotifier.detector.CustomSlowCallDetector;
7 | import com.nshmura.strictmodenotifier.detector.Detector;
8 | import com.nshmura.strictmodenotifier.detector.FileUriExposureDetector;
9 | import com.nshmura.strictmodenotifier.detector.LeakedClosableObjectsDetector;
10 | import com.nshmura.strictmodenotifier.detector.NetworkDetector;
11 | import com.nshmura.strictmodenotifier.detector.ResourceMismatchDetector;
12 |
13 | public enum ViolationTypeInfo {
14 |
15 | // ThreadPolicy
16 | CUSTOM_SLOW_CALL(
17 | "Custom Slow Call",
18 | ViolationType.CUSTOM_SLOW_CALL,
19 | Build.VERSION_CODES.HONEYCOMB,
20 | new CustomSlowCallDetector()),
21 |
22 | NETWORK(
23 | "Network",
24 | ViolationType.NETWORK,
25 | Build.VERSION_CODES.GINGERBREAD,
26 | new NetworkDetector()),
27 |
28 | RESOURCE_MISMATCHES(
29 | "Resource Mismatches",
30 | ViolationType.RESOURCE_MISMATCHES,
31 | Build.VERSION_CODES.M,
32 | new ResourceMismatchDetector()),
33 |
34 | // VmPolicy
35 | CLASS_INSTANCE_LIMIT(
36 | "Class Instance Limit",
37 | ViolationType.CLASS_INSTANCE_LIMIT,
38 | Build.VERSION_CODES.HONEYCOMB,
39 | new ClassInstanceLimitDetector()),
40 |
41 | CLEARTEXT_NETWORK(
42 | "Cleartext Network",
43 | ViolationType.CLEARTEXT_NETWORK,
44 | Build.VERSION_CODES.M,
45 | new CleartextNetworkDetector()),
46 |
47 | FILE_URI_EXPOSURE(
48 | "File Uri Exposure",
49 | ViolationType.FILE_URI_EXPOSURE,
50 | Build.VERSION_CODES.JELLY_BEAN_MR2,
51 | new FileUriExposureDetector()),
52 |
53 | LEAKED_CLOSABLE_OBJECTS(
54 | "Leaked Closable Objects",
55 | ViolationType.LEAKED_CLOSABLE_OBJECTS,
56 | Build.VERSION_CODES.HONEYCOMB,
57 | new LeakedClosableObjectsDetector()),
58 |
59 | ACTIVITY_LEAKS(
60 | "Activity Leaks",
61 | ViolationType.ACTIVITY_LEAKS,
62 | Build.VERSION_CODES.HONEYCOMB,
63 | null),
64 |
65 | LEAKED_REGISTRATION_OBJECTS(
66 | "Leaked Registration_Objects",
67 | ViolationType.LEAKED_REGISTRATION_OBJECTS,
68 | Build.VERSION_CODES.JELLY_BEAN,
69 | null),
70 |
71 | LEAKED_SQL_LITE_OBJECTS(
72 | "Leaked Sql Lite Objects",
73 | ViolationType.LEAKED_SQL_LITE_OBJECTS,
74 | Build.VERSION_CODES.GINGERBREAD,
75 | null),
76 |
77 | UNKNOWN("UNKNOWN", ViolationType.UNKNOWN, 0, null);
78 |
79 | private String name;
80 | public final ViolationType violationType;
81 | public final int minSdkVersion;
82 | public final Detector detector;
83 |
84 | ViolationTypeInfo(String name, ViolationType violationType, int minSdkVersion,
85 | Detector detector) {
86 | this.name = name;
87 | this.violationType = violationType;
88 | this.minSdkVersion = minSdkVersion;
89 |
90 | if (detector != null) {
91 | this.detector = detector;
92 | } else {
93 | this.detector = new Detector() {
94 | @Override public boolean detect(StrictModeLog log) {
95 | return false;
96 | }
97 | };
98 | }
99 | }
100 |
101 | public static ViolationTypeInfo convert(ViolationType type) {
102 | for (ViolationTypeInfo info : values()) {
103 | if (info.violationType == type) {
104 | return info;
105 | }
106 | }
107 | return ViolationTypeInfo.UNKNOWN;
108 | }
109 |
110 | public String violationName() {
111 | return name + " Violation";
112 | }
113 | }
114 |
--------------------------------------------------------------------------------
/library/src/main/java/com/nshmura/strictmodenotifier/detector/ClassInstanceLimitDetector.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier.detector;
2 |
3 | import com.nshmura.strictmodenotifier.StrictModeLog;
4 |
5 | public class ClassInstanceLimitDetector implements Detector {
6 |
7 | @Override public boolean detect(StrictModeLog log) {
8 | return log.message.contains("StrictMode.setClassInstanceLimit");
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/library/src/main/java/com/nshmura/strictmodenotifier/detector/CleartextNetworkDetector.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier.detector;
2 |
3 | import com.nshmura.strictmodenotifier.StrictModeLog;
4 |
5 | public class CleartextNetworkDetector implements Detector {
6 |
7 | @Override public boolean detect(StrictModeLog log) {
8 | return log.message.contains("CLEARTEXT communication not supported:");
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/library/src/main/java/com/nshmura/strictmodenotifier/detector/CustomSlowCallDetector.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier.detector;
2 |
3 | import com.nshmura.strictmodenotifier.StrictModeLog;
4 |
5 | public class CustomSlowCallDetector implements Detector {
6 |
7 | @Override public boolean detect(StrictModeLog log) {
8 | return log.message.contains("StrictMode$StrictModeCustomViolation");
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/library/src/main/java/com/nshmura/strictmodenotifier/detector/Detector.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier.detector;
2 |
3 | import com.nshmura.strictmodenotifier.StrictModeLog;
4 |
5 | public interface Detector {
6 | boolean detect(StrictModeLog log);
7 | }
8 |
--------------------------------------------------------------------------------
/library/src/main/java/com/nshmura/strictmodenotifier/detector/FileUriExposureDetector.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier.detector;
2 |
3 | import com.nshmura.strictmodenotifier.StrictModeLog;
4 |
5 | public class FileUriExposureDetector implements Detector {
6 |
7 | @Override public boolean detect(StrictModeLog log) {
8 | return log.message.contains("StrictMode.onFileUriExposed");
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/library/src/main/java/com/nshmura/strictmodenotifier/detector/LeakedClosableObjectsDetector.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier.detector;
2 |
3 | import com.nshmura.strictmodenotifier.StrictModeLog;
4 |
5 | public class LeakedClosableObjectsDetector implements Detector {
6 |
7 | @Override public boolean detect(StrictModeLog log) {
8 | return log.message.contains("A resource was acquired at attached stack trace but never released.");
9 | }
10 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/nshmura/strictmodenotifier/detector/NetworkDetector.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier.detector;
2 |
3 | import com.nshmura.strictmodenotifier.StrictModeLog;
4 |
5 | public class NetworkDetector implements Detector {
6 |
7 | @Override public boolean detect(StrictModeLog log) {
8 | return log.message.contains("StrictMode$StrictModeNetworkViolation");
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/library/src/main/java/com/nshmura/strictmodenotifier/detector/ResourceMismatchDetector.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier.detector;
2 |
3 | import com.nshmura.strictmodenotifier.StrictModeLog;
4 |
5 | public class ResourceMismatchDetector implements Detector {
6 |
7 | @Override public boolean detect(StrictModeLog log) {
8 | return log.message.contains("StrictMode$StrictModeResourceMismatchViolation");
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/library/src/main/res/drawable-hdpi/strictmode_notifier_ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/library/src/main/res/drawable-hdpi/strictmode_notifier_ic_launcher.png
--------------------------------------------------------------------------------
/library/src/main/res/drawable-hdpi/strictmode_notifier_ic_notification.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/library/src/main/res/drawable-hdpi/strictmode_notifier_ic_notification.png
--------------------------------------------------------------------------------
/library/src/main/res/drawable-mdpi/strictmode_notifier_ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/library/src/main/res/drawable-mdpi/strictmode_notifier_ic_launcher.png
--------------------------------------------------------------------------------
/library/src/main/res/drawable-mdpi/strictmode_notifier_ic_notification.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/library/src/main/res/drawable-mdpi/strictmode_notifier_ic_notification.png
--------------------------------------------------------------------------------
/library/src/main/res/drawable-xhdpi/strictmode_notifier_ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/library/src/main/res/drawable-xhdpi/strictmode_notifier_ic_launcher.png
--------------------------------------------------------------------------------
/library/src/main/res/drawable-xhdpi/strictmode_notifier_ic_notification.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/library/src/main/res/drawable-xhdpi/strictmode_notifier_ic_notification.png
--------------------------------------------------------------------------------
/library/src/main/res/drawable-xxhdpi/strictmode_notifier_ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/library/src/main/res/drawable-xxhdpi/strictmode_notifier_ic_launcher.png
--------------------------------------------------------------------------------
/library/src/main/res/drawable-xxhdpi/strictmode_notifier_ic_notification.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/library/src/main/res/drawable-xxhdpi/strictmode_notifier_ic_notification.png
--------------------------------------------------------------------------------
/library/src/main/res/drawable-xxxhdpi/strictmode_notifier_ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/library/src/main/res/drawable-xxxhdpi/strictmode_notifier_ic_launcher.png
--------------------------------------------------------------------------------
/library/src/main/res/drawable-xxxhdpi/strictmode_notifier_ic_notification.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/library/src/main/res/drawable-xxxhdpi/strictmode_notifier_ic_notification.png
--------------------------------------------------------------------------------
/library/src/main/res/layout/strictmode_notifier_activity_report.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
14 |
15 |
20 |
21 |
29 |
30 |
37 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/library/src/main/res/layout/strictmode_notifier_activity_report_detail.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
10 |
14 |
15 |
19 |
20 |
27 |
28 |
29 |
30 |
31 |
32 |
37 |
38 |
--------------------------------------------------------------------------------
/library/src/main/res/layout/strictmode_notifier_row.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
19 |
20 |
26 |
27 |
32 |
33 |
--------------------------------------------------------------------------------
/library/src/main/res/menu/strictmode_notifier_menu.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/library/src/main/res/values-v14/strictmode_notifier_styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/library/src/main/res/values-v21/strictmode_notifier_styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/library/src/main/res/values/strictmode_notifer_strings.xml:
--------------------------------------------------------------------------------
1 |
2 | StrictMode
3 | Violation in %s
4 | Click for more detail
5 | DELETE ALL
6 | %02d.
7 | copyed
8 | Copy
9 | Share
10 | DELETE
11 | Notification\nEnabled
12 | Notification\nDisabled
13 |
14 |
--------------------------------------------------------------------------------
/library/src/main/res/values/strictmode_notifier_colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3c3c3c
4 |
--------------------------------------------------------------------------------
/library/src/main/res/values/strictmode_notifier_styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':library-common', ':library', ':library-no-op', ':demo', ':testapp'
--------------------------------------------------------------------------------
/testapp/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/testapp/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion rootProject.ext.compileSdkVersion
5 | buildToolsVersion rootProject.ext.buildToolsVersion
6 |
7 | defaultConfig {
8 | applicationId "com.nshmura.strictmodenotifier.testapp"
9 | minSdkVersion rootProject.ext.minSdkVersion
10 | targetSdkVersion rootProject.ext.targetSdkVersion
11 | versionCode rootProject.ext.versionCode
12 | versionName rootProject.ext.versionName
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | testCompile 'junit:junit:4.12'
24 | compile "com.android.support:appcompat-v7:$rootProject.ext.supportLibraryVersion"
25 |
26 | compile project(":library")
27 | //compile "com.nshmura:strictmode-notifer:$rootProject.ext.versionName"
28 | }
--------------------------------------------------------------------------------
/testapp/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/a13088/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/testapp/src/androidTest/java/com/nshmura/strictmodenotifier/testapp/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier.testapp;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 |
11 | public ApplicationTest() {
12 | super(Application.class);
13 | }
14 | }
--------------------------------------------------------------------------------
/testapp/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/testapp/src/main/java/com/nshmura/strictmodenotifier/testapp/ClassInstanceLimitActivity.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier.testapp;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 | import android.os.Bundle;
6 | import android.os.Handler;
7 | import android.support.v7.app.AppCompatActivity;
8 |
9 | public class ClassInstanceLimitActivity extends AppCompatActivity {
10 |
11 | private static final String EXTRA_COUNT = "EXTRA_COUNT";
12 |
13 | public static void start(Context context, int count) {
14 | Intent starter = new Intent(context, ClassInstanceLimitActivity.class);
15 | starter.putExtra(EXTRA_COUNT, count);
16 | context.startActivity(starter);
17 | }
18 |
19 | @Override protected void onCreate(Bundle savedInstanceState) {
20 | super.onCreate(savedInstanceState);
21 |
22 | // Post a message and delay its execution for 10 minutes.
23 | new Handler().postDelayed(new Runnable() {
24 | @Override public void run() {
25 | }
26 | }, 1000 * 60 * 10);
27 |
28 | int count = getIntent().getIntExtra(EXTRA_COUNT, 0);
29 | if (count > 0) {
30 | start(this, --count);
31 | }
32 |
33 | finish();
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/testapp/src/main/java/com/nshmura/strictmodenotifier/testapp/CustomLogWatchService.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier.testapp;
2 |
3 | import android.util.Log;
4 | import com.nshmura.strictmodenotifier.LogWatchService;
5 | import com.nshmura.strictmodenotifier.StrictModeViolation;
6 |
7 | public class CustomLogWatchService extends LogWatchService {
8 |
9 | @Override
10 | protected void notifyViolation(StrictModeViolation violation) {
11 | super.notifyViolation(violation);
12 |
13 | //Custom Actions.
14 | // ex) Send logs to Slack.
15 | Log.d("CustomLogWatchService", "custom action");
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/testapp/src/main/java/com/nshmura/strictmodenotifier/testapp/LeakedBroadcastReceiver.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier.testapp;
2 |
3 | import android.content.BroadcastReceiver;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.os.Handler;
7 |
8 | public class LeakedBroadcastReceiver extends BroadcastReceiver {
9 |
10 | public LeakedBroadcastReceiver() {
11 | }
12 |
13 | @Override public void onReceive(Context context, Intent intent) {
14 | // Post a message and delay its execution for 10 minutes.
15 | new Handler().postDelayed(new Runnable() {
16 | @Override public void run() {
17 | }
18 | }, 1000 * 60 * 10);
19 | }
20 | }
--------------------------------------------------------------------------------
/testapp/src/main/java/com/nshmura/strictmodenotifier/testapp/LeakedClosableObjectsActivity.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier.testapp;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 | import android.os.Bundle;
6 | import android.support.v7.app.AppCompatActivity;
7 | import java.io.BufferedWriter;
8 | import java.io.OutputStreamWriter;
9 |
10 | public class LeakedClosableObjectsActivity extends AppCompatActivity {
11 |
12 | public static void start(Context context) {
13 | Intent starter = new Intent(context, LeakedClosableObjectsActivity.class);
14 | context.startActivity(starter);
15 | }
16 |
17 | @Override protected void onCreate(Bundle savedInstanceState) {
18 | super.onCreate(savedInstanceState);
19 |
20 | try {
21 | OutputStreamWriter output_writer =
22 | new OutputStreamWriter(openFileOutput("FILETEST", MODE_PRIVATE));
23 | BufferedWriter writer = new BufferedWriter(output_writer);
24 | writer.write("Hi This is my File to test StrictMode");
25 | //writer.close();
26 | } catch (Exception e) {
27 | e.printStackTrace();
28 | }
29 |
30 | finish();
31 | }
32 |
33 | private void fireLeakedClosableObjects() {
34 |
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/testapp/src/main/java/com/nshmura/strictmodenotifier/testapp/LeakedSQLiteOpenHelper.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier.testapp;
2 |
3 | import android.content.Context;
4 | import android.database.sqlite.SQLiteDatabase;
5 | import android.database.sqlite.SQLiteOpenHelper;
6 |
7 | public class LeakedSQLiteOpenHelper extends SQLiteOpenHelper {
8 |
9 | static final String DB = "sqlite_sample.db";
10 | static final int DB_VERSION = 1;
11 | static final String CREATE_TABLE =
12 | "create table sample ( _id integer primary key autoincrement, data integer not null );";
13 | static final String DROP_TABLE = "drop table sample;";
14 |
15 | public LeakedSQLiteOpenHelper(Context context) {
16 | super(context, DB, null, DB_VERSION);
17 | }
18 |
19 | public void onCreate(SQLiteDatabase db) {
20 | db.execSQL(CREATE_TABLE);
21 | }
22 |
23 | public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
24 | db.execSQL(DROP_TABLE);
25 | onCreate(db);
26 | }
27 | }
--------------------------------------------------------------------------------
/testapp/src/main/java/com/nshmura/strictmodenotifier/testapp/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier.testapp;
2 |
3 | import android.annotation.TargetApi;
4 | import android.content.ContentValues;
5 | import android.content.Intent;
6 | import android.content.res.TypedArray;
7 | import android.database.Cursor;
8 | import android.database.sqlite.SQLiteDatabase;
9 | import android.net.Uri;
10 | import android.os.Build;
11 | import android.os.Bundle;
12 | import android.os.Environment;
13 | import android.os.StrictMode;
14 | import android.security.NetworkSecurityPolicy;
15 | import android.support.v7.app.AppCompatActivity;
16 | import android.view.LayoutInflater;
17 | import android.view.Menu;
18 | import android.view.MenuInflater;
19 | import android.view.MenuItem;
20 | import android.view.View;
21 | import android.view.ViewGroup;
22 | import android.widget.BaseAdapter;
23 | import android.widget.Button;
24 | import android.widget.ListView;
25 | import android.widget.Toast;
26 | import com.nshmura.strictmodenotifier.LogWatchService;
27 | import com.nshmura.strictmodenotifier.ViolationType;
28 | import com.nshmura.strictmodenotifier.ViolationTypeInfo;
29 | import java.io.File;
30 | import java.io.IOException;
31 | import java.lang.reflect.Method;
32 | import java.net.HttpURLConnection;
33 | import java.net.URL;
34 | import java.util.ArrayList;
35 | import java.util.Arrays;
36 |
37 | public class MainActivity extends AppCompatActivity {
38 |
39 | @Override protected void onCreate(Bundle savedInstanceState) {
40 | super.onCreate(savedInstanceState);
41 | setContentView(R.layout.activity_main);
42 |
43 | ListView listView = (ListView) findViewById(R.id.list_view);
44 | //noinspection ConstantConditions
45 | listView.setAdapter(new Adapter());
46 | }
47 |
48 | @Override public boolean onCreateOptionsMenu(Menu menu) {
49 | MenuInflater inflater = getMenuInflater();
50 | inflater.inflate(R.menu.main, menu);
51 | return true;
52 | }
53 |
54 | @Override public boolean onOptionsItemSelected(MenuItem item) {
55 | // Handle item selection
56 | switch (item.getItemId()) {
57 | case R.id.menu_stop_service:
58 | stopService(new Intent(this, LogWatchService.class));
59 | return true;
60 |
61 | default:
62 | return super.onOptionsItemSelected(item);
63 | }
64 | }
65 |
66 | private void fireStrictModeError(ViolationTypeInfo info) {
67 | if (Build.VERSION.SDK_INT < info.minSdkVersion) {
68 | Toast.makeText(this, "min sdk version " + info.minSdkVersion, Toast.LENGTH_LONG).show();
69 | return;
70 | }
71 |
72 | switch (info) {
73 | case CUSTOM_SLOW_CALL:
74 | fireSlowCall();
75 | break;
76 | case NETWORK:
77 | fireNetwork();
78 | break;
79 | case RESOURCE_MISMATCHES:
80 | fireResourceMismatches();
81 | break;
82 | case CLASS_INSTANCE_LIMIT:
83 | fireClassInstanceLimit();
84 | break;
85 | case CLEARTEXT_NETWORK:
86 | fireCleartextNetwork();
87 | break;
88 | case FILE_URI_EXPOSURE:
89 | fireFileUriExposure();
90 | break;
91 | case LEAKED_CLOSABLE_OBJECTS:
92 | fireLeakedClosableObjects();
93 | break;
94 | case ACTIVITY_LEAKS:
95 | fireActivityLeaks();
96 | break;
97 | case LEAKED_REGISTRATION_OBJECTS:
98 | fireLeakedRegistrationObjects();
99 | break;
100 | case LEAKED_SQL_LITE_OBJECTS:
101 | fireLeakedSqlLiteObjects();
102 | break;
103 | }
104 | }
105 |
106 | @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void fireSlowCall() {
107 | StrictMode.noteSlowCall("fireSlowCall");
108 | }
109 |
110 | private void fireNetwork() {
111 | try {
112 | URL url = new URL("http://google.com/");
113 | HttpURLConnection con = (HttpURLConnection) url.openConnection();
114 | con.setRequestMethod("GET");
115 | con.connect();
116 | } catch (IOException e) {
117 | e.printStackTrace();
118 | }
119 | }
120 |
121 | private void fireResourceMismatches() {
122 | TypedArray names = getResources().obtainTypedArray(R.array.sample_names);
123 | names.getInt(0, 0);
124 | names.recycle();
125 | }
126 |
127 | private void fireClassInstanceLimit() {
128 | ClassInstanceLimitActivity.start(this, 2);
129 | }
130 |
131 | // https://koz.io/android-m-and-the-war-on-cleartext-traffic/
132 | @TargetApi(Build.VERSION_CODES.M) private void fireCleartextNetwork() {
133 | Runnable runnable = new Runnable() {
134 | @Override public void run() {
135 | try {
136 | Method method = NetworkSecurityPolicy.getInstance()
137 | .getClass()
138 | .getMethod("setCleartextTrafficPermitted", boolean.class);
139 | method.invoke(NetworkSecurityPolicy.getInstance(), false);
140 |
141 | URL url = new URL("http://google.com/");
142 | HttpURLConnection con = (HttpURLConnection) url.openConnection();
143 | con.setRequestMethod("GET");
144 | con.connect();
145 |
146 | method.invoke(NetworkSecurityPolicy.getInstance(), true);
147 | } catch (Exception e) {
148 | e.printStackTrace();
149 | }
150 | }
151 | };
152 | new Thread(runnable).start();
153 | }
154 |
155 | private void fireFileUriExposure() {
156 | File file = Environment.getExternalStorageDirectory();
157 | Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("file://" + file.toString()));
158 | startActivity(intent);
159 | }
160 |
161 | private void fireLeakedClosableObjects() {
162 | LeakedClosableObjectsActivity.start(this);
163 | }
164 |
165 | //FIXME not working
166 | private void fireActivityLeaks() {
167 |
168 | }
169 |
170 | //FIXME not working
171 | private void fireLeakedRegistrationObjects() {
172 | Intent i = new Intent("LeakAction");
173 | sendBroadcast(i);
174 | }
175 |
176 | //FIXME not working
177 | private void fireLeakedSqlLiteObjects() {
178 | LeakedSQLiteOpenHelper helper = new LeakedSQLiteOpenHelper(getApplicationContext());
179 | SQLiteDatabase db = helper.getWritableDatabase();
180 |
181 | ContentValues values = new ContentValues();
182 | values.put("data", "data");
183 | db.insert("sample", null, values);
184 |
185 | Cursor cursor =
186 | db.query("sample", new String[] { "_id", "data" }, null, null, null, null, "_id DESC");
187 | cursor.moveToNext();
188 | cursor.close();
189 | //db.close();
190 | }
191 |
192 | class Adapter extends BaseAdapter {
193 |
194 | private final ViolationType[] values;
195 |
196 | public Adapter() {
197 | ArrayList list = new ArrayList<>(Arrays.asList(ViolationType.values()));
198 | list.remove(ViolationType.ACTIVITY_LEAKS);
199 | list.remove(ViolationType.LEAKED_REGISTRATION_OBJECTS);
200 | list.remove(ViolationType.LEAKED_SQL_LITE_OBJECTS);
201 | list.remove(ViolationType.UNKNOWN);
202 | values = list.toArray(new ViolationType[list.size()]);
203 | }
204 |
205 | @Override public int getCount() {
206 | return values.length;
207 | }
208 |
209 | @Override public ViolationType getItem(int position) {
210 | return values[position];
211 | }
212 |
213 | @Override public long getItemId(int position) {
214 | return position;
215 | }
216 |
217 | @Override public View getView(int position, View convertView, ViewGroup parent) {
218 |
219 | if (convertView == null) {
220 | convertView =
221 | LayoutInflater.from(MainActivity.this).inflate(R.layout.row_actions, parent, false);
222 | }
223 | final ViolationTypeInfo info = ViolationTypeInfo.convert(getItem(position));
224 |
225 | String text = String.format("%s error (minSdk %s)",
226 | ViolationTypeInfo.convert(info.violationType).violationName(),
227 | info.minSdkVersion);
228 |
229 | Button button = (Button) convertView.findViewById(R.id.button);
230 | button.setText(text);
231 | button.setEnabled(Build.VERSION.SDK_INT >= info.minSdkVersion);
232 |
233 | button.setOnClickListener(new View.OnClickListener() {
234 | @Override public void onClick(View v) {
235 | fireStrictModeError(info);
236 | }
237 | });
238 |
239 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
240 | button.setAllCaps(false);
241 | }
242 |
243 | return convertView;
244 | }
245 | }
246 | }
--------------------------------------------------------------------------------
/testapp/src/main/java/com/nshmura/strictmodenotifier/testapp/MainApplication.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier.testapp;
2 |
3 | import android.app.Application;
4 | import android.os.Handler;
5 | import android.os.StrictMode;
6 | import com.nshmura.strictmodenotifier.StrictModeNotifier;
7 |
8 | public class MainApplication extends Application {
9 |
10 | @Override public void onCreate() {
11 | super.onCreate();
12 |
13 | StrictModeNotifier
14 | .install(this)
15 | .setDebugMode(true);
16 |
17 | //https://code.google.com/p/android/issues/detail?id=35298
18 | new Handler().post(new Runnable() {
19 | @Override public void run() {
20 | StrictMode.ThreadPolicy threadPolicy = new StrictMode.ThreadPolicy.Builder().detectAll()
21 | .permitDiskReads()
22 | .permitDiskWrites()
23 | .penaltyLog()
24 | .build();
25 | StrictMode.setThreadPolicy(threadPolicy);
26 |
27 | StrictMode.VmPolicy vmPolicy =
28 | new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build();
29 | StrictMode.setVmPolicy(vmPolicy);
30 | }
31 | });
32 | }
33 | }
--------------------------------------------------------------------------------
/testapp/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/testapp/src/main/res/layout/row_actions.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
14 |
15 |
--------------------------------------------------------------------------------
/testapp/src/main/res/menu/main.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/testapp/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/testapp/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/testapp/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/testapp/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/testapp/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/testapp/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/testapp/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/testapp/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/testapp/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nshmura/strictmode-notifier/c2f91aab6462ecbe0c5ca14f858040e99dea0f01/testapp/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/testapp/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/testapp/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
8 | - 1
9 | - 2
10 | - 3
11 |
12 |
13 |
--------------------------------------------------------------------------------
/testapp/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/testapp/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | strictmode-notifier TestApp
3 | Stop LogWatchService
4 |
5 |
--------------------------------------------------------------------------------
/testapp/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/testapp/src/test/java/com/nshmura/strictmodenotificator/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.nshmura.strictmodenotifier;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.assertEquals;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class ExampleUnitTest {
11 |
12 | @Test public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------