android:处理应用程序崩溃并启动特定的活动 [英] android: Handle Application Crash and start a particular Activity
问题描述
我有一个应用程序,如果该应用程序在特定活动中崩溃,它会在其中一个中间父活动中重新启动.
I have an app and if the app crashes in a particular activity, it restarts at one of the intermediate parent activities.
这对我来说是个问题,因为我有一些输入的用户信息会在崩溃时丢失.
This is a problem for me since I have some inputted user info that is lost upon crash.
有什么办法可以强制应用在崩溃重启后从启动器屏幕启动?
Is there any way to force the app to start from the launcher screen after restarting from a crash?
谢谢.
推荐答案
Proposed Solution 1 -
在 manifest.xml 文件中将此标记 android:clearTaskOnLaunch="true"
添加到应始终启动的主要活动中.
Proposed Solution 1 -
Add this tag android:clearTaskOnLaunch="true"
in the manifest.xml file to your main activity which should always launch.
它不起作用的可能原因
当应用程序崩溃时,它会抛出一个Exception
,我们需要处理Exception
,否则我们将无法获得预期的行为
When the application crashes, it throws an Exception
and we need to handle the Exception
and otherwise we would not get the expected behavior
尝试处理任何未捕获的异常并告诉系统该做什么.要实现这一点,请尝试以下步骤.
Try to handle any uncaught Exception and tell the system what to do. To implement this, try the below steps.
- 创建一个扩展
Application
类 的类 - 处理
Application
子类中的uncaughtException
. - 在您的启动器
Activity
中,调用您的Application
类. - 捕获异常后,启动您的主要
Activity
(根据您的要求).
- Create a class extending
Application
Class - Handle
uncaughtException
in yourApplication
subclass. - In your launcher
Activity
, call yourApplication
class. - After catching an Exception, start your main
Activity
(as per your requirement).
代码示例
步骤 1 和 2
package com.casestudy.intentsandfilter;
import android.app.Application;
import android.content.Intent;
public class MyApplication extends Application
{
@Override
public void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(
new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException (Thread thread, Throwable e) {
handleUncaughtException (thread, e);
}
});
}
private void handleUncaughtException (Thread thread, Throwable e) {
// The following shows what I'd like, though it won't work like this.
Intent intent = new Intent (getApplicationContext(),DrawView.class);
startActivity(intent);
// Add some code logic if needed based on your requirement
}
}
步骤 3
public class MainActivity extends Activity {
protected MyApplication app;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the application instance
app = (MyApplication)getApplication();
.............
}
}
步骤 4
根据您的要求修改以下方法
Modify the below method as per your requirement
private void handleUncaughtException (Thread thread, Throwable e) {
// The following shows what I'd like, though it won't work like this.
Intent intent = new Intent (getApplicationContext(), HomeActivity.class);
startActivity(intent);
// Add some code logic if needed based on your requirement
}
这篇关于android:处理应用程序崩溃并启动特定的活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!