我的应用部分是使用 C/C++ 在 native 应用中编写的。问题是,每当 C/C++ 部分由于某种原因崩溃时,应用程序就会死掉,然后自动重新启动。这会导致各种乱七八糟的问题
当然,它不应该在 native 部分崩溃,我正在努力排除它发生的所有原因。但是,如果确实发生了,我想:
- 优雅地退出
- 如果死机,至少不要尝试自动重启。
我很好奇为什么会发生这种行为。经过一番搜索后,我尝试将以下行放在 AndroidManifest.xml 的主要 Activity 元素中:
android:finishOnTaskLaunch="true"
但自动恢复仍然发生。
任何人都知道为什么会发生这种情况以及如何改变它?
更新:
我认为一个更根本的问题是,
如果发生原生崩溃,是否有类似于回调的东西?
其中一个答案建议“处理崩溃信号”。对于如何在应用程序或模块级别完成此操作的任何链接,我将不胜感激。
就目前而言,如果发生崩溃,应用程序就会消失,logcat 中没有任何内容,因此无法进行调试。
最佳答案
尝试处理崩溃信号(SIGSEGV 等)并在信号处理程序中向自己发送 kill。这个技巧对我有帮助。
例子:
#include <signal.h>
#include <unistd.h>
static void signal_handler(int signal, siginfo_t *info, void *reserved)
{
kill(getpid(),SIGKILL);
}
extern "C" jint JNI_OnLoad(JavaVM* vm, void* /*reserved*/)
{
struct sigaction handler;
memset(&handler, 0, sizeof(handler));
handler.sa_sigaction = signal_handler;
handler.sa_flags = SA_SIGINFO;
sigaction(SIGILL, &handler, NULL);
sigaction(SIGABRT, &handler, NULL);
sigaction(SIGBUS, &handler, NULL);
sigaction(SIGFPE, &handler, NULL);
sigaction(SIGSEGV, &handler, NULL);
sigaction(SIGSTKFLT, &handler, NULL);
return(JNI_VERSION_1_6);
}
更新2
如果你想在 android logcat 中查看 crashlog,你应该使用这个信号处理程序
static void signal_handler(int signal, siginfo_t *info, void *reserved)
{
struct sockaddr_un addr;
size_t namelen;
socklen_t alen;
int s, err;
char name[] = "android:debuggerd";
namelen = strlen(name);
// Test with length +1 for the *initial* '\0'.
if ((namelen + 1) > sizeof(addr.sun_path)) {
errno = EINVAL;
return;
}
/* This is used for abstract socket namespace, we need
* an initial '\0' at the start of the Unix socket path.
*
* Note: The path in this case is *not* supposed to be
* '\0'-terminated. ("man 7 unix" for the gory details.)
*/
memset (&addr, 0, sizeof addr);
addr.sun_family = AF_LOCAL;
addr.sun_path[0] = 0;
memcpy(addr.sun_path + 1, name, namelen);
alen = namelen + offsetof(struct sockaddr_un, sun_path) + 1;
s = socket(AF_LOCAL, SOCK_STREAM, 0);
if(s < 0) return;
RETRY_ON_EINTR(err,connect(s, (struct sockaddr *) &addr, alen));
if (err < 0) {
close(s);
s = -1;
}
pid_t tid = gettid();
if(s>=0)
{
/* debugger knows our pid from the credentials on the
* local socket but we need to tell it our tid. It
* is paranoid and will verify that we are giving a tid
* that's actually in our process
*/
int ret;
RETRY_ON_EINTR(ret, write(s, &tid, sizeof(unsigned)));
if (ret == sizeof(unsigned)) {
/* if the write failed, there is no point to read on
* the file descriptor. */
RETRY_ON_EINTR(ret, read(s, &tid, 1));
//notify_gdb_of_libraries();
}
close(s);
}
wait(NULL);
kill(getpid(),SIGKILL);
}
我从 android 源获取它(无法插入链接,因为 android.git.kernel.org 已关闭),但我不确定它是否会在未来的 Android 版本中工作
关于Android 应用程序在崩溃后自动重启,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7245550/