android - 新 Activity 有时无法开始

标签 android android-activity android-pendingintent

在某些情况下,我需要在我的应用程序中调用 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 只是一个静态文本。

最佳答案

这不可靠。如果您导致虚拟机关闭,您将无法显示任何内容,因为不再有虚拟机在运行。唯一可靠的方法是确保 BroadcastReceiverActivity在不同的操作系统进程中运行以显示您的消息。这也不是 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/

相关文章:

android - 为 Android 开发流媒体服务器

android - 从 pendingintent 启动后 startactivity 不起作用

android - AlarmManager 过早触发 PendingIntent

android - Android UI 线程的工作方式与 Swing UI 线程类似吗?

android - 如何获取AlarmManager调用的唯一pendingIntent的ID?

android - Android 中的自定义形状按钮 - 我做得对吗?

android - Zxing 项目作为项目中的库不会构建

iphone - iPhone 和/或 Android 上的 Ocropus 引擎

java - 我正在尝试使用 ListView 按钮从 cutomlistadapter 打开 Android Activity 。我尽了最大努力但没有结果?

android - 从后台线程调用 startActivity 且主线程被阻塞时,Activity 启动有延迟