建议的解决方案 1 -
在 manifest.xml 文件中将此标签 android:clearTaskOnLaunch="true" 添加到您应该始终启动的主要活动中。
它不起作用的可能原因
当应用程序崩溃时,它会抛出一个Exception,我们需要处理Exception,否则我们将无法获得预期的行为
建议的解决方案 2
尝试处理任何未捕获的异常并告诉系统该做什么。要实现这一点,请尝试以下步骤。
- 创建一个扩展
ApplicationClass的类
- 在您的
Application 子类中处理 uncaughtException。
- 在您的启动器
Activity 中,调用您的Application 类。
- 捕获异常后,启动您的主要
Activity(根据您的要求)。
代码示例
第 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 步
根据您的要求修改以下方法
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
}