Android:如何在“强制关闭”后自动重启应用程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2681499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:54:47  来源:igfitidea点击:

Android: How to auto-restart application after it's been "force closed"?

android

提问by Johnny

In an Android application, we usually got the "Force Closed" error if we didn't get the exceptions right.

在 Android 应用程序中,如果我们没有正确处理异常,我们通常会收到“强制关闭”错误。

How can I restart my application automatically if it force closed?

如果强制关闭,我如何自动重启我的应用程序?

Is there any specific permission is used for this?

是否有任何特定的权限用于此?

回答by Gyuri Majercsik

To accomplish this you have to do two things:

要做到这一点,你必须做两件事:

  1. Avoid the "Force close" - standard way of application crash.
  2. Setup a restart mechanism when the crash happens anyway.
  1. 避免“强制关闭” - 应用程序崩溃的标准方式。
  2. 无论如何设置崩溃发生时的重启机制。

See below how to do these:

请参阅下文如何执行这些操作:

  1. Call Thread.setDefaultUncaughtExceptionHandler()in order to catch all uncaught exception, in which case uncaughtException()method will be called. "Force close" will not appear and the application will be unresponsive, which is not a quite good thing. In order to restart your application when it crashed you should do the following :

  2. In the onCreatemethod, in your main activity initialize a PendingIntentmember:

    Intent intent = PendingIntent.getActivity(
        YourApplication.getInstance().getBaseContext(),
        0,
        new Intent(getIntent()),
        getIntent().getFlags());
    
  1. 调用Thread.setDefaultUncaughtExceptionHandler()以捕获所有未捕获的异常,在这种情况下uncaughtException()将调用方法。不会出现“强制关闭”并且应用程序没有响应,这不是一件好事。为了在崩溃时重新启动您的应用程序,您应该执行以下操作:

  2. 在该onCreate方法中,在您的主要活动中初始化一个PendingIntent成员:

    Intent intent = PendingIntent.getActivity(
        YourApplication.getInstance().getBaseContext(),
        0,
        new Intent(getIntent()),
        getIntent().getFlags());
    

Then put the following in your uncaughtException()method:

然后将以下内容放入您的uncaughtException()方法中:

AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 2000, intent);
System.exit(2);

You also must call System.exit(), otherwise will not work. In this way your application will restart after 2 seconds.

您还必须调用System.exit(),否则将无法正常工作。这样,您的应用程序将在 2 秒后重新启动。

Eventually you can set some flag in your intent that the application crashed and in your onCreate()method you can show a dialog "I'm sorry, the application crashed, hope never again :)".

最终,您可以在应用程序崩溃的意图中设置一些标志,并在您的onCreate()方法中显示一个对话框“对不起,应用程序崩溃了,希望再也不会:)”。

回答by Dave Webb

The trick is make sure it doesn't Force Close in the first place.

诀窍是确保它首先不会强制关闭。

If you use the Thread.setDefaultUncaughtExceptionHandler()methodyou can catch the Exceptions that are causing your application to Force Close.

如果您使用Thread.setDefaultUncaughtExceptionHandler()方法,您可以捕获导致您的应用程序强制关闭的异常。

Have a look at this questionfor an example of using an UncaughtExceptionHandlerto log the Exceptions raised by an application.

查看此问题以获取使用UncaughtExceptionHandler记录应用程序引发的异常的示例。

回答by Renetik

If you use Crittercism or some other error report service, accepted answer is almost right..

如果您使用 Crittercism 或其他一些错误报告服务,接受的答案几乎是正确的。

final UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
            public void uncaughtException(Thread thread, Throwable ex) {
              Intent launchIntent = new Intent(activity().getIntent());
              PendingIntent pending = PendingIntent.getActivity(CSApplication.getContext(), 0,
                    launchIntent, activity().getIntent().getFlags());
              getAlarmManager().set(AlarmManager.RTC, System.currentTimeMillis() + 2000, pending);
              defaultHandler.uncaughtException(thread, ex);
            }
});

回答by Satya

public class ForceCloseExceptionHandalingActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setContentView(MyLayout());
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
                myHandaling(paramThread, paramThrowable);
            }
        });
    }

    private ViewGroup MyLayout(){
        LinearLayout mainLayout = new LinearLayout(this);
        mainLayout.setOrientation(LinearLayout.VERTICAL);  
        Button btnHello =new Button(this);
        btnHello.setText("Show all button");
        btnHello.setOnClickListener(new OnClickListener() {         
            @Override
            public void onClick(View v) {                   
                setContentView(MyLayout2());            
            }
        });             
        mainLayout.addView(btnHello);       
        return mainLayout;
    }

    private ViewGroup MyLayout2(){
        LinearLayout mainLayout = new LinearLayout(this);
        mainLayout.setOrientation(LinearLayout.VERTICAL);  
        Button btnHello =new Button(this);
        btnHello.setText("I am a EEROR uncaughtException");
        btnHello.setOnClickListener(new OnClickListener() {         
            @Override
            public void onClick(View v) {                   
                Log.e("Alert","btn  uncaughtException::");
                Toast.makeText(ForceCloseExceptionHandalingActivity.this, "Alert uncaughtException222",Toast.LENGTH_LONG).show();
                View buttone = null;
                setContentView(buttone);            
            }
        });     
        Button btnHello2 =new Button(this);
        btnHello2.setText("I am a EEROR Try n catch");
        btnHello2.setOnClickListener(new OnClickListener() {            
            @Override
            public void onClick(View v) {   

                try{
                    View buttone = null;
                    setContentView(buttone);
                }
                catch (Exception e) {
                    Log.e("Alert","Try n catch:::");
                    Toast.makeText(ForceCloseExceptionHandalingActivity.this, "Alert Try n catch",Toast.LENGTH_LONG).show();
                    setContentView(MyLayout());
                }

            }
        });     
        mainLayout.addView(btnHello);
        mainLayout.addView(btnHello2);
        return mainLayout;
    }
    public void myHandaling(Thread paramThread, Throwable paramThrowable){
        Log.e("Alert","Lets See if it Works !!!" +"paramThread:::" +paramThread +"paramThrowable:::" +paramThrowable);
        Toast.makeText(ForceCloseExceptionHandalingActivity.this, "Alert uncaughtException111",Toast.LENGTH_LONG).show();
        Intent in =new Intent(ForceCloseExceptionHandalingActivity.this,com.satya.ForceCloseExceptionHandaling.ForceCloseExceptionHandalingActivity.class);
        startActivity(in);
        finish();
        android.os.Process.killProcess(android.os.Process.myPid()); 
    }
    @Override
    protected void onDestroy() {
        Log.e("Alert","onDestroy:::");
        Toast.makeText(ForceCloseExceptionHandalingActivity.this, "Alert onDestroy",Toast.LENGTH_LONG).show();
        super.onDestroy();  
    }

回答by Suraj Vaishnav

Just add this class in your package

只需在您的包中添加此类

public class MyExceptionHandler implements
    java.lang.Thread.UncaughtExceptionHandler {
private final Context myContext;
private final Class<?> myActivityClass;

public MyExceptionHandler(Context context, Class<?> c) {
    myContext = context;
    myActivityClass = c;
}

public void uncaughtException(Thread thread, Throwable exception) {
    StringWriter stackTrace = new StringWriter();
    exception.printStackTrace(new PrintWriter(stackTrace));
    System.err.println(stackTrace);// You can use LogCat too
    Intent intent = new Intent(myContext, myActivityClass);
    String s = stackTrace.toString();
    //you can use this String to know what caused the exception and in which Activity
    intent.putExtra("uncaughtException", "Exception is: " + stackTrace.toString());
    intent.putExtra("stacktrace", s);
    myContext.startActivity(intent);
    //for restarting the Activity
    Process.killProcess(Process.myPid());
    System.exit(0);
}}

Then simply call:

然后只需调用:

Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this,
            SplashScreenActivity.class));