我有一个应用程序,如果应用程序在特定活动中崩溃,它将在其中一个中间父活动重新启动。
这对我来说是一个问题,因为我有一些输入的用户信息在崩溃时丢失。
有没有办法强制应用程序从崩溃重启后从启动器屏幕启动?
谢谢。
将manifest.xml文件中的此标记android:clearTaskOnLaunch="true"
添加到应始终启动的主活动中。
可能的原因为什么它不起作用
当应用程序崩溃时,它抛出一个Exception
,我们需要处理Exception
,否则我们不会得到预期的行为
尝试处理任何未捕获的异常并告诉系统该做什么。要实现此功能,请尝试以下步骤。
Application
类的类uncaughtException
子类中处理Application
。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
}
首先,在App
中创建并设置AndroidManifest.xml
类
android:name=".App"
android:clearTaskOnLaunch="true"
然后将此代码放在App类中
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(
new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable e) {
Log.d("AppCrash", "Error just lunched ");
}
});
}}
也许没有办法做到这一点,但你可以标记它,以便你知道活动是通过用户操作启动还是刚刚崩溃后启动。
即,当您启动父活动时,将一些内容传递给startActivity意图。如果那不存在那么它就是在崩溃后开始的。
我设法用intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
开始我的主要活动,如下所示:
private void handleUncaughtException (Thread thread, Throwable e)
{
Intent intent = new Intent (getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}