【问题标题】:New activity sometimes doesn't start新活动有时无法开始
【发布时间】:2016-10-31 16:46:19
【问题描述】:

在某些情况下,我需要在我的应用程序中调用exit()(我知道这不是完成的最佳方式,但这不是问题所在)。我还想显示一个新对话框,通知用户崩溃。

我创建了一个新的活动类,一个新的广播接收器,并在清单中注册了它们。接下来,我调用:

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); 在新活动有机会开始之前触发(因为异步调用,我认为在文档中找不到这个)所以我在pendingIntent.send();System.exit(0); 之间添加了Thread.sleep(1000),但结果是相同 - 有时会出现新窗口。日志中没有任何内容,也不例外。

新活动只是一个静态文本。

【问题讨论】:

  • 这绝对不可靠。调用System.exit() 基本上会关闭虚拟机。您无法保证关闭 VM 时会发生任何事情。您当然不能期望在 UI 中显示任何内容。请解释您的用例,也许我们可以提出替代方案。
  • 我的用例是在特定条件下exit,并告诉用户应用程序停止的原因。作为替代方案,我正在使用通知,但我想要更多的持久性解决方案,这些解决方案应该留在屏幕上并等到用户手动关闭它。

标签: android android-activity android-pendingintent


【解决方案1】:

这不可靠。如果您导致虚拟机关闭,您将无法显示任何内容,因为不再有虚拟机在运行。唯一可靠的方法是确保BroadcastReceiverActivity 在不同的操作系统进程中运行以显示您的消息。这也不是 100% 可靠的,因为根据异常的性质,您现有的 VM 可能无法启动其他组件,但它可能比您当前的实现更可靠。例如,如果您的应用由于OutOfMemoryException 而崩溃,则可能无法执行任何有用的操作。

为确保组件在单独的进程中运行,添加

android:process=":other"

到这些组件的清单中的<activity><receiver> 定义。

您还应该尝试延迟对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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-12
    • 2023-04-03
    • 2015-12-21
    • 1970-01-01
    • 2018-04-11
    • 2014-01-09
    • 1970-01-01
    相关资源
    最近更新 更多