Skip to content

Commit

Permalink
add: 信号量crash catch
Browse files Browse the repository at this point in the history
  • Loading branch information
zjw committed Jul 1, 2022
1 parent 6aad7e2 commit e8a698f
Show file tree
Hide file tree
Showing 33 changed files with 575 additions and 48 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@
/build
/captures
.externalNativeBuild
.cxx
3 changes: 2 additions & 1 deletion .idea/gradle.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 17 additions & 3 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 0 additions & 11 deletions .idea/modules.xml

This file was deleted.

12 changes: 0 additions & 12 deletions .idea/runConfigurations.xml

This file was deleted.

1 change: 1 addition & 0 deletions app/.gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
/build
.idea
.cxx
25 changes: 19 additions & 6 deletions app/build.gradle
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

configurations.all {
resolutionStrategy {
force 'androidx.core:core:1.6.0'
force 'androidx.core:core-ktx:1.6.0'
force 'androidx.appcompat:appcompat:1.3.1'
}
}
android {
compileSdkVersion 28
compileSdkVersion 28
defaultConfig {
applicationId "com.example.ndk.ndkdemo"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
externalNativeBuild {
cmake {
cppFlags ""
Expand All @@ -31,11 +39,16 @@ android {

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
//kotlin
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.core:core:1.6.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation project(path: ':lib_signal')
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0'
implementation "com.google.guava:guava:18.0"

}
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package com.example.ndk.ndkdemo;

import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;

import org.junit.Test;
import org.junit.runner.RunWith;
Expand Down
1 change: 1 addition & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
package="com.example.ndk.ndkdemo">

<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
Expand Down
16 changes: 16 additions & 0 deletions app/src/main/cpp/native-lib.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
#include <jni.h>
#include <string>
#include<android/log.h>
#include"valid.cpp"

extern "C"
Expand Down Expand Up @@ -49,4 +51,18 @@ Java_com_example_ndk_ndkdemo_SignHelper_getSignToken(
} else {
return env->NewStringUTF("获取失败,请检查valid.cpp文件配置的sha1值");
}
}


// 测试crash
extern "C"
JNIEXPORT void JNICALL
Java_com_example_ndk_ndkdemo_SignHelper_throwNativeCrash(JNIEnv *env, jobject thiz) {
// int i = 0 / 0;
// jstring j = (jstring) "132" + i;
// char *name = const_cast<char *>(env->GetStringUTFChars(j, NULL));
// __android_log_print(ANDROID_LOG_INFO, "hello", "%s", &"jni will crash"[(*name)]);
// 向自身发送一个信号
raise(SIGQUIT);

}
9 changes: 8 additions & 1 deletion app/src/main/java/com/example/ndk/ndkdemo/MainActivity.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package com.example.ndk.ndkdemo;

import android.support.v7.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

Expand All @@ -19,6 +20,12 @@ protected void onCreate(Bundle savedInstanceState) {

TextView tv_show = (TextView) findViewById(R.id.tv_show);
tv_show.setText(SignHelper.getSign(this));
tv_show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SignHelper.throwNativeCrash();
}
});

//是否二次打包
if (SignHelper.checkSha1(this)) {
Expand Down
12 changes: 12 additions & 0 deletions app/src/main/java/com/example/ndk/ndkdemo/MyApplication.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.example.ndk.ndkdemo

import android.app.Application
import com.example.lib_signal.SignalConst
import com.example.lib_signal.SignalController

class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
SignalController(this).initWithSignals(intArrayOf(SignalConst.SIGQUIT,SignalConst.SIGABRT))
}
}
72 changes: 72 additions & 0 deletions app/src/main/java/com/example/ndk/ndkdemo/MyHandler.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package com.example.ndk.ndkdemo

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Looper
import android.os.Message
import android.os.Process
import android.os.SystemClock
import android.util.Log
import android.widget.Toast
import androidx.annotation.RequiresApi
import com.example.lib_signal.CallOnCatchSignal

class MyHandler : CallOnCatchSignal {
@RequiresApi(Build.VERSION_CODES.M)
override fun onCatchSignal(signal: Int, context: Context) {
// 自定义处理,比如弹出一个toast,或者更友好的交互
Log.i("hello", "custom onCatchSignal ")
if (checkIsANR(signal, context)) {
Toast.makeText(context, "自定义anr 处理", Toast.LENGTH_LONG).show()
}else {
Toast.makeText(context, "自定义native crash 处理", Toast.LENGTH_LONG).show()
}
val restart: Intent? =
context.packageManager.getLaunchIntentForPackage(context.packageName)
restart?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK)
restart?.action = "restart"
context.startActivity(restart)
Process.killProcess(Process.myPid())
System.exit(0)
}

// 判断是否是anr
@SuppressLint("DiscouragedPrivateApi")
@RequiresApi(Build.VERSION_CODES.M)
private fun checkIsANR(signal: Int, context: Context): Boolean {
// val systemService = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
// val currentPid = Process.myPid()
// Log.i("hello", "systemService ${systemService}")

try {
val queue = Looper.getMainLooper().queue
val field = queue.javaClass.getDeclaredField("mMessages")
field.isAccessible = true
val message = field.get(queue) as Message
// 这里应该根据实际逻辑判断,比如在前台的话就相应的判断,比如超出5s,这里简单比较演示
return message.`when` < SystemClock.uptimeMillis()

// 可以dump这些消息
// val processesInErrorStates = systemService.processesInErrorState
// Log.i("hello", "processesInErrorStates ${processesInErrorStates}")
// Log.i("hello", "checkIsANR")
// Log.i("hello", "currentPid $currentPid")
//
// processesInErrorStates?.let {
// it.forEach { info ->
// Log.i("hello", "pid is ${info.pid} ========${info.condition}")
// if (info.pid == currentPid && info.condition == ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING) {
// Log.i("hello", "发生了anr")
// return true
// }
// }
// }
} catch (e: Exception) {
e.printStackTrace()
}

return false
}
}
1 change: 1 addition & 0 deletions app/src/main/java/com/example/ndk/ndkdemo/SignHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public class SignHelper {
public static native String getSignToken(Context context,String userId);
public static native String getSignaturesSha1(Context context);
public static native boolean checkSha1(Context context);
public static native void throwNativeCrash();



Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
com.example.ndk.ndkdemo.MyHandler
19 changes: 11 additions & 8 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

ext.kotlin_version = '1.6.10'
repositories {
google()
maven { url "http://maven.aliyun.com/nexus/content/groups/public" }
maven{ url "http://maven.aliyun.com/nexus/content/repositories/jcenter"}
jcenter()
maven { url 'https://maven.aliyun.com/repository/google' }
google()
mavenCentral()
maven { url "https://jitpack.io" }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
classpath 'com.android.tools.build:gradle:3.5.4'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"


// NOTE: Do not place your application dependencies here; they belong
Expand All @@ -19,10 +21,11 @@ buildscript {

allprojects {
repositories {
google()
maven { url "http://maven.aliyun.com/nexus/content/groups/public" }
maven{ url "http://maven.aliyun.com/nexus/content/repositories/jcenter"}
jcenter()
maven { url 'https://maven.aliyun.com/repository/google' }
google()
mavenCentral()
maven { url "https://jitpack.io" }
}
}

Expand Down
2 changes: 2 additions & 0 deletions gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@

# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
android.enableJetifier=true
android.useAndroidX=true
org.gradle.jvmargs=-Xmx1536m

# When configured, Gradle will run in incubating parallel mode.
Expand Down
6 changes: 3 additions & 3 deletions gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#Sat Jul 06 14:09:41 GMT+08:00 2019
#Thu Jun 30 18:39:24 CST 2022
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-bin.zip
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip
zipStoreBase=GRADLE_USER_HOME
Empty file modified gradlew
100644 → 100755
Empty file.
1 change: 1 addition & 0 deletions lib_signal/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
Loading

0 comments on commit e8a698f

Please sign in to comment.