在某些情况下,我需要在我的应用程序中调用 exit()
(我知道这不是最好的完成方式,但这不是问题所在)。我还想显示一个新对话框,通知用户有关崩溃的信息。
我创建了一个新的 Activity 类,一个新的广播接收器,并在 list 中注册了它们。接下来,我调用:
Intent intent = new Intent(this, AppCloseReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent, 0);
try
{
pendingIntent.send();
}
catch(Exception ex){}
System.exit(0);
问题是有时会出现新窗口!首先我认为 System.exit(0);
在新 Activity 有机会开始之前触发(因为异步调用,我认为在文档中找不到它)所以我添加了 Thread。 sleep(1000)
在 pendingIntent.send();
和 System.exit(0);
之间,但结果是一样的 - 新窗口出现 有时。日志中没有任何内容,无一异常(exception)。
新 Activity 只是一个静态文本。
最佳答案
这不可靠。如果您导致虚拟机关闭,您将无法显示任何内容,因为不再有虚拟机在运行。唯一可靠的方法是确保 BroadcastReceiver
和 Activity
在不同的操作系统进程中运行以显示您的消息。这也不是 100% 可靠的,因为根据异常的性质,您现有的 VM 可能无法启动其他组件,但它可能比您当前的实现更可靠。例如,如果您的应用程序因 OutOfMemoryException
而崩溃,可能无法做任何有用的事情。
为确保一个组件在单独的进程中运行,添加
android:process=":other"
到<activity>
和 <receiver>
这些组件的 list 中的定义。
您还应该尝试延迟对 System.exit()
的调用让 VM 有机会实际启动对话。此外,您不需要使用 PendingIntent
为了这。尝试这样的事情:
Intent intent = new Intent(this, AppCloseReceiver.class);
sendBrodcast(intent);
// Start separate Thread to terminate the process
new Thread(new Runnable() {
@override
public void run() {
SystemClock.sleep(1000); // Sleep a bit to give the VM enough time to actually send the broadcast Intent
System.exit(0);
}
}).start();
关于android - 新 Activity 有时无法开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40346696/