├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ ├── dimens.xml
│ │ │ │ └── styles.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
│ │ │ └── layout
│ │ │ │ └── activity_main.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── newsdog
│ │ │ └── crashcanary
│ │ │ └── MainActivity.java
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── newsdog
│ │ │ └── crashcanary
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── newsdog
│ │ └── crashcanary
│ │ └── ApplicationTest.java
├── proguard-rules.pro
└── build.gradle
├── crashcanary
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── drawable
│ │ │ │ └── crash_icon.png
│ │ │ ├── values
│ │ │ │ ├── colors.xml
│ │ │ │ └── strings.xml
│ │ │ └── layout
│ │ │ │ └── crash_log_layout.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── simple
│ │ │ ├── SharePref.java
│ │ │ ├── IOUtils.java
│ │ │ ├── LogReader.java
│ │ │ ├── LogWriter.java
│ │ │ ├── StorageUtils.java
│ │ │ ├── ui
│ │ │ └── LogDetailActivity.java
│ │ │ └── CrashCanary.java
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── newsdog
│ │ │ └── crashcanary
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── newsdog
│ │ └── crashcanary
│ │ └── ApplicationTest.java
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── log.png
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── .gitignore
├── README.md
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/crashcanary/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':crashcanary'
2 |
--------------------------------------------------------------------------------
/log.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hehonghui/CrashCanary/HEAD/log.png
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | CrashCanary
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hehonghui/CrashCanary/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hehonghui/CrashCanary/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hehonghui/CrashCanary/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hehonghui/CrashCanary/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hehonghui/CrashCanary/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hehonghui/CrashCanary/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/crashcanary/src/main/res/drawable/crash_icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hehonghui/CrashCanary/HEAD/crashcanary/src/main/res/drawable/crash_icon.png
--------------------------------------------------------------------------------
/crashcanary/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FF4081
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sat May 28 09:09:00 CST 2016
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.4-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/test/java/com/newsdog/crashcanary/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.newsdog.crashcanary;
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
12 | public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------
/crashcanary/src/test/java/com/newsdog/crashcanary/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.newsdog.crashcanary;
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
12 | public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/newsdog/crashcanary/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package com.newsdog.crashcanary;
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 | }
--------------------------------------------------------------------------------
/crashcanary/src/androidTest/java/com/newsdog/crashcanary/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package com.newsdog.crashcanary;
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 | }
--------------------------------------------------------------------------------
/crashcanary/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/crashcanary/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | CrashCanary
3 |
4 | 查看日志
5 | 清空日志
6 | 复制日志
7 | crash日志已经复制~
8 | 关闭
9 | 日志为空
10 | 详细日志
11 | Crash!!!
12 |
13 |
14 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Applications/dev/adt-bundle-mac-x86_64-20131030/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 |
--------------------------------------------------------------------------------
/crashcanary/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 /Applications/dev/adt-bundle-mac-x86_64-20131030/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 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.2"
6 |
7 | defaultConfig {
8 | applicationId "com.newsdog.crashcanary"
9 | minSdkVersion 10
10 | targetSdkVersion 23
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(dir: 'libs', include: ['*.jar'])
24 | testCompile 'junit:junit:4.12'
25 | compile 'com.android.support:appcompat-v7:23.4.0'
26 |
27 | compile project(':crashcanary')
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/crashcanary/src/main/java/com/simple/SharePref.java:
--------------------------------------------------------------------------------
1 | package com.simple;
2 |
3 | import android.content.Context;
4 |
5 | /**
6 | * Created by mrsimple on 1/6/16.
7 | */
8 | public final class SharePref {
9 |
10 | private SharePref() {
11 | }
12 |
13 | static final String LOG_PREF = "crash.log";
14 |
15 | /**
16 | * @param context
17 | * @param fileName
18 | */
19 | public static void saveLastCrashLog(Context context, String fileName) {
20 | context.getSharedPreferences(LOG_PREF, Context.MODE_PRIVATE).edit()
21 | .putString("last_crash", fileName).commit();
22 | }
23 |
24 | public static String getLastCrashLog(Context context) {
25 | return context.getSharedPreferences(LOG_PREF, Context.MODE_PRIVATE).getString("last_crash", "");
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/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
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # built application files
2 | *.apk
3 | *.ap_
4 |
5 | release_apks/
6 |
7 | build/
8 | .gradle/
9 | *.DS_Store
10 | .idea/vcs.xml
11 |
12 | # files for the dex VM
13 | *.dex
14 |
15 | # Java class files
16 | *.class
17 |
18 | # generated files
19 | bin/
20 | gen/
21 |
22 | # build file
23 | */**/build/
24 | */release_apks/
25 |
26 | # Local configuration file (sdk path, etc)
27 | local.properties
28 |
29 | # Eclipse project files
30 | .classpath
31 | .project
32 |
33 | # Proguard folder generated by Eclipse
34 | proguard/
35 |
36 | # Intellij project files
37 | *.iml
38 | *.ipr
39 | *.iws
40 | .idea/
41 |
42 | # */**/*.gradle
43 | # */**/*.iml
44 |
45 | .idea/gradle.xml
46 | .idea/misc.xml
47 | .idea/modules.xml
48 | .idea/vcs.xml
49 | BreakingNews-AS.iml
50 | android_imageviewer/android_imageviewer.iml
51 | colorful/colorful.iml
52 | facebook/facebook.iml
53 | local.properties
54 | newsDog/newsDog.iml
55 | newsDog/newsDog-release.zip
56 | newsDog/newsDog-release/
57 | local.properties
58 | newsDog/src/main/.DS_Store
59 | .idea/misc.xml
60 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
13 |
14 |
19 |
20 |
27 |
28 |
--------------------------------------------------------------------------------
/crashcanary/src/main/res/layout/crash_log_layout.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
14 |
15 |
20 |
25 |
26 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/crashcanary/src/main/java/com/simple/IOUtils.java:
--------------------------------------------------------------------------------
1 | package com.simple;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.Closeable;
5 | import java.io.IOException;
6 | import java.io.InputStream;
7 | import java.io.InputStreamReader;
8 |
9 | /**
10 | * 将stream 转换 String的工具类
11 | */
12 | public final class IOUtils {
13 |
14 | private IOUtils() {
15 | }
16 |
17 | /**
18 | * stream to string
19 | * @param inputStream
20 | * @return
21 | * @throws IOException
22 | */
23 | public static String streamToString(InputStream inputStream)
24 | throws IOException {
25 | if ( inputStream == null ) {
26 | return "";
27 | }
28 | StringBuilder sBuilder = new StringBuilder();
29 | String line ;
30 | BufferedReader bufferedReader = new BufferedReader(
31 | new InputStreamReader(inputStream));
32 | while ((line = bufferedReader.readLine()) != null) {
33 | sBuilder.append(line).append("\n");
34 | }
35 | return sBuilder.toString();
36 | }
37 |
38 | /**
39 | * 关闭Closeable对象
40 | * @param closeable
41 | */
42 | public static void closeSilently(Closeable closeable) {
43 | if (closeable != null) {
44 | try {
45 | closeable.close();
46 | } catch (IOException e) {
47 | e.printStackTrace();
48 | }
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/app/src/main/java/com/newsdog/crashcanary/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.newsdog.crashcanary;
2 |
3 | import android.os.Bundle;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.view.View;
6 | import android.widget.Button;
7 |
8 | import com.simple.CrashCanary;
9 |
10 | public class MainActivity extends AppCompatActivity {
11 |
12 | @Override
13 | protected void onCreate(Bundle savedInstanceState) {
14 | super.onCreate(savedInstanceState);
15 | setContentView(R.layout.activity_main);
16 |
17 | final CrashCanary crashCanary = new CrashCanary.Builder(this)
18 | .setExceptionHandler(new Thread.UncaughtExceptionHandler() { // 设置自己的异常处理 Handler
19 | @Override
20 | public void uncaughtException(Thread thread, Throwable ex) {
21 |
22 | }
23 | })
24 | .setKillProcessWhenCrash(true) // 发生crash之后关闭应用,再次进入应用时会有crash通知
25 | .build();
26 |
27 | Button btn = (Button) findViewById(R.id.submit_btn);
28 | btn.setOnClickListener(new View.OnClickListener() {
29 | @Override
30 | public void onClick(View v) {
31 | throw new NullPointerException("Crash Canary Test");
32 | }
33 | });
34 |
35 | findViewById(R.id.show_btn).setOnClickListener(new View.OnClickListener() {
36 | @Override
37 | public void onClick(View v) {
38 | crashCanary.showLogListDialog(MainActivity.this);
39 | }
40 | });
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/crashcanary/src/main/java/com/simple/LogReader.java:
--------------------------------------------------------------------------------
1 | package com.simple;
2 |
3 | import java.io.File;
4 | import java.io.FileInputStream;
5 |
6 | /**
7 | * Created by mrsimple on 28/5/16.
8 | */
9 | public class LogReader {
10 | String mLogDir = "";
11 |
12 | /**
13 | * 获取log根目录下的所有log文件路径
14 | */
15 | public String[] getCrashLogFileNames() {
16 | File[] files = new File(mLogDir).listFiles();
17 | if (files == null || files.length <= 0) {
18 | return new String[]{};
19 | }
20 |
21 | int size = files.length - 1;
22 | String[] logFiles = new String[files.length];
23 | for (int i = size; i >= 0; i--) {
24 | // 将文件逆序排
25 | logFiles[size - i] = files[i].getName();
26 | }
27 | return logFiles;
28 | }
29 |
30 | /**
31 | * 通过txt文件的路径获取其内容
32 | *
33 | * @param filepath
34 | * @return
35 | */
36 | public String readLog(String filepath) {
37 | FileInputStream fileInputStream = null;
38 | String log = "";
39 | try {
40 | File file = new File(filepath);
41 | fileInputStream = new FileInputStream(file);
42 | log = IOUtils.streamToString(fileInputStream);
43 | } catch (Exception e) {
44 | e.printStackTrace();
45 | } finally {
46 | IOUtils.closeSilently(fileInputStream);
47 | }
48 | return log;
49 | }
50 |
51 | void setLogDir(String dir) {
52 | this.mLogDir = dir;
53 | }
54 |
55 | public String getLogDir() {
56 | return mLogDir;
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # CrashCanary
2 |
3 | 
4 |
5 | CrashCanary 是一个记录Android 应用程序 Crash的库,当程序发生Crash时CrashCanary会将Crash 日志存储到本地,并且在下次进入应用时通过通知栏提示开发人员,开发人员点击通知栏即可进入到Log详情页面。开发人员也可以手动查看Crash日志列表以及每个Log的详细信息. [下载示例apk](http://pan.baidu.com/s/1eS0kHY6)
6 |
7 | 示例代码如下:
8 |
9 | ```java
10 | public class MainActivity extends AppCompatActivity {
11 |
12 | @Override
13 | protected void onCreate(Bundle savedInstanceState) {
14 | super.onCreate(savedInstanceState);
15 | setContentView(R.layout.activity_main);
16 |
17 | final CrashCanary crashCanary = new CrashCanary.Builder(this)
18 | // 设置自己的异常处理 Handler
19 | .setExceptionHandler(new Thread.UncaughtExceptionHandler() {
20 | @Override
21 | public void uncaughtException(Thread thread, Throwable ex) {
22 |
23 | }
24 | })
25 | .setKillProcessWhenCrash(true) // 发生crash之后关闭应用,再次进入应用时会有crash通知
26 | .build();
27 |
28 | Button btn = (Button) findViewById(R.id.submit_btn);
29 | btn.setOnClickListener(new View.OnClickListener() {
30 | @Override
31 | public void onClick(View v) {
32 | // 模拟一个Crash
33 | throw new NullPointerException("Crash Canary Test");
34 | }
35 | });
36 |
37 | findViewById(R.id.show_btn).setOnClickListener(new View.OnClickListener() {
38 | @Override
39 | public void onClick(View v) {
40 | crashCanary.showLogListDialog(MainActivity.this);
41 | }
42 | });
43 | }
44 | }
45 | ```
46 |
47 | ## 效果
48 |
49 | 
50 |
51 |
--------------------------------------------------------------------------------
/crashcanary/src/main/java/com/simple/LogWriter.java:
--------------------------------------------------------------------------------
1 | package com.simple;
2 |
3 | import java.io.BufferedWriter;
4 | import java.io.FileWriter;
5 | import java.io.PrintWriter;
6 | import java.io.StringWriter;
7 | import java.io.Writer;
8 | import java.text.DateFormat;
9 | import java.text.SimpleDateFormat;
10 | import java.util.Date;
11 |
12 | /**
13 | * Created by mrsimple on 28/5/16.
14 | */
15 | public class LogWriter {
16 | /**
17 | * 用于格式化日期,作为日志文件名的一部分
18 | */
19 | private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
20 |
21 | String mLogDir = "";
22 |
23 | /**
24 | * 写入crash 日志, 并且返回log文件的文件名 [ 将日志写入到文件 ]
25 | *
26 | * @param t
27 | * @param e
28 | * @return log完整的文件名,如果没有写入到本地文件,直接返回""即可
29 | */
30 | public String write(Thread t, final Throwable e) {
31 | final Writer stringWriter = new StringWriter();
32 | final PrintWriter printWriter = new PrintWriter(stringWriter);
33 | e.printStackTrace(printWriter);
34 | // 存储log
35 | String fileName = writeToFile(stringWriter.toString());
36 | IOUtils.closeSilently(printWriter);
37 | return fileName;
38 | }
39 |
40 | /**
41 | * 将crash log写入到文件,并且返回该文件的完整路径
42 | *
43 | * @param stacktrace
44 | * @return log的完整路径
45 | */
46 | private String writeToFile(String stacktrace) {
47 | String fileName = generateLogFileName(mLogDir);
48 | BufferedWriter bos = null;
49 | try {
50 | bos = new BufferedWriter(new FileWriter(fileName));
51 | bos.write(stacktrace);
52 | bos.flush();
53 | } catch (Exception e) {
54 | e.printStackTrace();
55 | } finally {
56 | IOUtils.closeSilently(bos);
57 | }
58 | return fileName;
59 | }
60 |
61 | void setLogDir(String dir) {
62 | this.mLogDir = dir;
63 | }
64 |
65 | /**
66 | * @param dir
67 | * @return
68 | */
69 | private static String generateLogFileName(String dir) {
70 | String time = DATE_FORMAT.format(new Date());
71 | return dir + "log_" + time + ".txt";
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/crashcanary/src/main/java/com/simple/StorageUtils.java:
--------------------------------------------------------------------------------
1 | package com.simple;
2 |
3 | import android.content.Context;
4 | import android.os.Environment;
5 |
6 | import java.io.File;
7 |
8 | /**
9 | * Created by mrsimple on 28/5/16.
10 | */
11 | public final class StorageUtils {
12 |
13 | private StorageUtils() {
14 | }
15 |
16 | /**
17 | * 有sd卡的路径
18 | */
19 | public static String CRASH_DIR = "/crashcanary/log/";
20 |
21 | public static boolean isSDCardMounted() {
22 | return Environment.getExternalStorageState()
23 | .equals(android.os.Environment.MEDIA_MOUNTED);
24 | }
25 |
26 | public static String getCrashDir(Context context) {
27 | initLogDir(context);
28 | String dir;
29 | if (isSDCardMounted()) {
30 | dir = Environment.getExternalStorageDirectory().toString() + CRASH_DIR;
31 | } else {
32 | dir = context.getCacheDir() + CRASH_DIR;
33 | }
34 | checkCrashLogDir(dir);
35 | return dir;
36 | }
37 |
38 | private static void initLogDir(Context context) {
39 | CRASH_DIR = "/crashcanary/" + context.getPackageName() + "/log/";
40 | }
41 |
42 | private static void checkCrashLogDir(String crashFileDirs) {
43 | File file = new File(crashFileDirs);
44 | if (!file.exists()) {
45 | try {
46 | // 按照指定的路径创建文件夹
47 | file.mkdirs();
48 | } catch (Exception e) {
49 | return;
50 | }
51 | }
52 | }
53 |
54 | /**
55 | * 递归删除文件和文件夹
56 | *
57 | * @param file 要删除的根目录
58 | */
59 | public static void deleteFile(File file) {
60 | if (file.isFile()) {
61 | file.delete();
62 | return;
63 | }
64 | if (file.isDirectory()) {
65 | File[] childFile = file.listFiles();
66 | if (childFile == null || childFile.length == 0) {
67 | file.delete();
68 | return;
69 | }
70 | for (File f : childFile) {
71 | deleteFile(f);
72 | }
73 | file.delete();
74 | }
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/crashcanary/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.github.dcendents.android-maven'
3 | apply plugin: 'com.jfrog.bintray'
4 |
5 | version = "1.0"
6 | android {
7 | compileSdkVersion 23
8 | buildToolsVersion "23.0.2"
9 | resourcePrefix "crashcanary__" //这个随便填
10 |
11 | defaultConfig {
12 | minSdkVersion 10
13 | targetSdkVersion 23
14 | versionCode 1
15 | versionName version
16 | }
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 | }
24 |
25 | dependencies {
26 | compile fileTree(dir: 'libs', include: ['*.jar'])
27 | testCompile 'junit:junit:4.12'
28 | compile "com.android.support:support-v4:23.0.1"
29 | }
30 |
31 | // This is the library version used when deploying the artifact
32 | def siteUrl = 'https://github.com/hehonghui/CrashCanary' // 项目的主页
33 | def gitUrl = 'https://github.com/hehonghui/CrashCanary.git' // Git仓库的url
34 | group = "com.simple" // Maven Group ID for the artifact,一般填你唯一的包名
35 | install {
36 | repositories.mavenInstaller {
37 | // This generates POM.xml with proper parameters
38 | pom {
39 | project {
40 | packaging 'aar'
41 | // Add your description here
42 | name 'Android Crash Canary' //项目描述
43 | url siteUrl
44 | // Set your license
45 | licenses {
46 | license {
47 | name 'The Apache Software License, Version 2.0'
48 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
49 | }
50 | }
51 | developers {
52 | developer {
53 | id 'bboyfeiyu' //填写的一些基本信息
54 | name 'MrSimple'
55 | email 'simplecoder.h@gmail.com'
56 | }
57 | }
58 | scm {
59 | connection gitUrl
60 | developerConnection gitUrl
61 | url siteUrl
62 | }
63 | }
64 | }
65 | }
66 | }
67 | task sourcesJar(type: Jar) {
68 | from android.sourceSets.main.java.srcDirs
69 | classifier = 'sources'
70 | }
71 |
72 | //task javadoc(type: Javadoc) {
73 | // source = android.sourceSets.main.java.srcDirs
74 | // classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
75 | //}
76 | //task javadocJar(type: Jar, dependsOn: javadoc) {
77 | // classifier = 'javadoc'
78 | // from javadoc.destinationDir
79 | //}
80 |
81 | artifacts {
82 | // archives javadocJar
83 | archives sourcesJar
84 | }
85 | Properties properties = new Properties()
86 | properties.load(project.rootProject.file('local.properties').newDataInputStream())
87 | bintray {
88 | user = properties.getProperty("bintray.user")
89 | key = properties.getProperty("bintray.apikey")
90 | configurations = ['archives']
91 | pkg {
92 | repo = "maven"
93 | name = "CrashCanary" //发布到JCenter上的项目名字
94 | websiteUrl = siteUrl
95 | vcsUrl = gitUrl
96 | licenses = ["Apache-2.0"]
97 | publish = true
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/crashcanary/src/main/java/com/simple/ui/LogDetailActivity.java:
--------------------------------------------------------------------------------
1 | package com.simple.ui;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.os.AsyncTask;
6 | import android.os.Bundle;
7 | import android.text.ClipboardManager;
8 | import android.text.TextUtils;
9 | import android.view.View;
10 | import android.widget.TextView;
11 | import android.widget.Toast;
12 |
13 | import com.simple.CrashCanary;
14 | import com.simple.LogReader;
15 | import com.simple.R;
16 |
17 | /**
18 | * 日志详情页面
19 | * Created by mrsimple on 28/5/16.
20 | */
21 | public class LogDetailActivity extends Activity {
22 |
23 | TextView mReasonTv;
24 | TextView mLogTextView;
25 | String mLogFile = "";
26 |
27 | @Override
28 | protected void onCreate(Bundle savedInstanceState) {
29 | super.onCreate(savedInstanceState);
30 | setContentView(R.layout.crash_log_layout);
31 | mLogFile = getIntent().getExtras().getString("log");
32 | if (TextUtils.isEmpty(mLogFile)) {
33 | Toast.makeText(this, "no log file", Toast.LENGTH_SHORT).show();
34 | finish();
35 | return;
36 | }
37 | mReasonTv = (TextView) findViewById(R.id.crash_reason_tv);
38 | mLogTextView = (TextView) findViewById(R.id.crash_log_tv);
39 | }
40 |
41 | private void setupCopy(final String logContent) {
42 | findViewById(R.id.copy_btn).setOnClickListener(new View.OnClickListener() {
43 | @Override
44 | public void onClick(View v) {
45 | copy(logContent);
46 | }
47 | });
48 | }
49 |
50 | @Override
51 | protected void onResume() {
52 | super.onResume();
53 | submitReadLogDetailTask(mLogFile, getApplicationContext(), CrashCanary.getInstance().getReader());
54 | }
55 |
56 | /**
57 | * @param selectedFile
58 | * @param context
59 | * @param reader
60 | */
61 | private void submitReadLogDetailTask(final String selectedFile,
62 | final Context context,
63 | final LogReader reader) {
64 | new AsyncTask() {
65 |
66 | @Override
67 | protected String doInBackground(Void... params) {
68 | if (!TextUtils.isEmpty(selectedFile)) {
69 | return reader.readLog(selectedFile);
70 | }
71 | return "";
72 | }
73 |
74 | @Override
75 | protected void onPostExecute(String logContent) {
76 | if (!TextUtils.isEmpty(logContent)) {
77 | mReasonTv.setText(parseReason(logContent));
78 | mLogTextView.setText(logContent);
79 | setupCopy(logContent);
80 | } else {
81 | Toast.makeText(context, R.string.empty_log, Toast.LENGTH_SHORT).show();
82 | }
83 | }
84 |
85 | private String parseReason(String logContent) {
86 | int firstIndex = logContent.indexOf(")");
87 | if (firstIndex < 0) {
88 | return "Not Found.";
89 | }
90 | return logContent.substring(0, firstIndex + 1);
91 | }
92 | }.execute();
93 | }
94 |
95 | private void copy(String logContent) {
96 | ClipboardManager cmb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
97 | cmb.setText(logContent);
98 | Toast.makeText(this, R.string.copy_success, Toast.LENGTH_SHORT).show();
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/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 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/crashcanary/src/main/java/com/simple/CrashCanary.java:
--------------------------------------------------------------------------------
1 | package com.simple;
2 |
3 | import android.app.AlertDialog;
4 | import android.app.NotificationManager;
5 | import android.app.PendingIntent;
6 | import android.content.Context;
7 | import android.content.DialogInterface;
8 | import android.content.Intent;
9 | import android.graphics.BitmapFactory;
10 | import android.support.v4.app.NotificationCompat;
11 | import android.text.TextUtils;
12 |
13 | import com.simple.ui.LogDetailActivity;
14 |
15 | import java.io.File;
16 |
17 | /**
18 | * 崩溃日志收集、显示处理类,在 内部设置了 UncaughtExceptionHandler,
19 | * 因此如果在应用中使用了其他 crash 收集sdk,需要注意 CrashCanary 与这些sdk的兼容。
20 | *
21 | * crash 日志会在下次进入应用时自动提示到通知栏,或者用户可以手动调用
22 | * {@link #showLogListDialog(Context)} 函数显示crash 日志列表
23 | *
24 | * Created by ly on 16/5/10.
25 | */
26 | public final class CrashCanary {
27 | private static CrashCanary sInstance;
28 | /**
29 | * 是否正在写crash log, 避免同一个crash log 写入多个文件
30 | */
31 | private boolean isWriting = false;
32 | private LogWriter mWriter;
33 | private LogReader mReader;
34 | private Context mContext;
35 | /**
36 | * 用户打开crash 日志列表时选中的log 项
37 | */
38 | private String mSelectedItem = "";
39 |
40 | private CrashCanary() {
41 | }
42 |
43 | public static CrashCanary getInstance() {
44 | if (sInstance == null) {
45 | synchronized (CrashCanary.class) {
46 | if (sInstance == null) {
47 | }
48 | sInstance = new CrashCanary();
49 | }
50 | }
51 | return sInstance;
52 | }
53 |
54 | /**
55 | * dump the crash log
56 | *
57 | * @param thread
58 | * @param exception
59 | */
60 | private void dump(final Thread thread, final Throwable exception) {
61 | if (isWriting) {
62 | return;
63 | }
64 | isWriting = true;
65 | // 存储这次的crash 文件名,下次进入应用时弹出通知
66 | SharePref.saveLastCrashLog(mContext, mWriter.write(thread, exception));
67 | isWriting = false;
68 | }
69 |
70 | private void showNotification(String fileName) {
71 | Intent intent = new Intent(mContext, LogDetailActivity.class);
72 | intent.putExtra("log", fileName);
73 |
74 | PendingIntent pendingintent =
75 | PendingIntent.getActivity(mContext, 0, intent, 0);
76 | //设置各项参数
77 | NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext);
78 | mBuilder.setContentTitle(mContext.getString(R.string.crash_occur))
79 | .setContentText(fileName)
80 | .setSmallIcon(R.drawable.crash_icon)
81 | .setWhen(System.currentTimeMillis())
82 | .setAutoCancel(true)
83 | .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.drawable.crash_icon))
84 | .setContentIntent(pendingintent);
85 |
86 | NotificationManager notifyMgr =
87 | (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
88 | notifyMgr.notify(intent.hashCode(), mBuilder.build());
89 | }
90 |
91 | /**
92 | * 展示崩溃日志列表
93 | */
94 | public void showLogListDialog(final Context context) {
95 | // 获取日志列表
96 | final String[] allList = mReader.getCrashLogFileNames();
97 | if (allList.length > 0) {
98 | mSelectedItem = allList[0];
99 | }
100 |
101 | AlertDialog.Builder builder = new AlertDialog.Builder(context);
102 | builder.setTitle(R.string.log_detail);
103 | builder.setSingleChoiceItems(allList, 0, new DialogInterface.OnClickListener() {
104 | @Override
105 | public void onClick(DialogInterface dialog, int which) {
106 | mSelectedItem = allList[which];
107 | }
108 | });
109 | builder.setPositiveButton(R.string.show_log, new DialogInterface.OnClickListener() {
110 |
111 | @Override
112 | public void onClick(DialogInterface dialog, int which) {
113 | Intent intent = new Intent(context, LogDetailActivity.class);
114 | intent.putExtra("log", mReader.getLogDir() + mSelectedItem);
115 | context.startActivity(intent);
116 | dialog.dismiss();
117 | }
118 | });
119 | builder.setNeutralButton(R.string.clear_all, new DialogInterface.OnClickListener() {
120 | @Override
121 | public void onClick(DialogInterface dialog, int which) {
122 | StorageUtils.deleteFile(new File(mReader.getLogDir()));
123 | }
124 | });
125 | AlertDialog alertDialog = builder.create();
126 | alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
127 | @Override
128 | public void onDismiss(DialogInterface dialog) {
129 | mSelectedItem = "";
130 | }
131 | });
132 | alertDialog.show();
133 | }
134 |
135 | private void checkLastCrash() {
136 | String lastLog = SharePref.getLastCrashLog(mContext);
137 | if (!TextUtils.isEmpty(lastLog)) {
138 | showNotification(lastLog);
139 | SharePref.saveLastCrashLog(mContext, "");
140 | }
141 | }
142 |
143 | public LogReader getReader() {
144 | return mReader;
145 | }
146 |
147 | public LogWriter getWriter() {
148 | return mWriter;
149 | }
150 |
151 | /**
152 | * CrashCanary的Builder,用于配置 CrashCanaey
153 | */
154 | public static class Builder {
155 | private Context mContext;
156 | private String mLogDir;
157 | private Thread.UncaughtExceptionHandler mExpHandler;
158 | private LogReader mLogReader;
159 | private LogWriter mLogWriter;
160 | private boolean killProcessWhenCrash = true;
161 |
162 | public Builder(Context context) {
163 | this.mContext = context.getApplicationContext();
164 | }
165 |
166 | public Builder setLogDir(String dir) {
167 | this.mLogDir = dir;
168 | return this;
169 | }
170 |
171 | public Builder setLogReader(LogReader mLogReader) {
172 | this.mLogReader = mLogReader;
173 | return this;
174 | }
175 |
176 | public Builder setLogWriter(LogWriter mLogWriter) {
177 | this.mLogWriter = mLogWriter;
178 | return this;
179 | }
180 |
181 | public Builder setExceptionHandler(Thread.UncaughtExceptionHandler handler) {
182 | this.mExpHandler = handler;
183 | return this;
184 | }
185 |
186 | public Builder setKillProcessWhenCrash(boolean isKill) {
187 | this.killProcessWhenCrash = isKill;
188 | return this;
189 | }
190 |
191 | private void killTheProcess() {
192 | android.os.Process.killProcess(android.os.Process.myPid());
193 | System.exit(1);
194 | }
195 |
196 | private void handleCrash(CrashCanary crashCanary, Thread thread, Throwable ex) {
197 | if (mExpHandler != null) {
198 | mExpHandler.uncaughtException(thread, ex);
199 | }
200 | crashCanary.dump(thread, ex);
201 | ex.printStackTrace();
202 | if (killProcessWhenCrash) {
203 | killTheProcess();
204 | }
205 | }
206 |
207 | public CrashCanary build() {
208 | final CrashCanary crashCanary = CrashCanary.getInstance();
209 | if (TextUtils.isEmpty(mLogDir)) {
210 | mLogDir = StorageUtils.getCrashDir(mContext);
211 | }
212 | crashCanary.mContext = mContext;
213 | crashCanary.mReader = mLogReader == null ? new LogReader() : mLogReader;
214 | crashCanary.mWriter = mLogWriter == null ? new LogWriter() : mLogWriter;
215 | crashCanary.mReader.setLogDir(mLogDir);
216 | crashCanary.mWriter.setLogDir(mLogDir);
217 | // 设置异常处理
218 | Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
219 | @Override
220 | public void uncaughtException(Thread thread, Throwable ex) {
221 | handleCrash(crashCanary, thread, ex);
222 | }
223 | });
224 | crashCanary.checkLastCrash();
225 | return crashCanary;
226 | }
227 | }
228 | }
229 |
--------------------------------------------------------------------------------