为什么context.startActivity(intent)没有启动活动,如何在Android中处理异常?

huangapple go评论71阅读模式
英文:

Why context.startActivity(intent) not starting the activity and how to handle exception in android?

问题

以下是您要翻译的代码部分:

public class ExceptionHandler implements Thread.UncaughtExceptionHandler {
    public static final String TAG = "异常处理器";
    private final Context activity;

    public ExceptionHandler(Context activity) {
        this.activity = activity;
    }

    @Override
    public void uncaughtException(@NonNull Thread thread, @NonNull Throwable throwable) {
        Intent error = new Intent(activity, ErrorCatcher.class);
        activity.startActivity(error);
    }
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.e(TAG, "onRestart: 嘿,刚刚创建了");
    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this.getApplicationContext()));
    // 其他方法和函数
}

请注意,我已经将HTML编码(")转换回正常文本。如果您需要更多帮助,请告诉我。

英文:

I have an exception handler which handles exception from an Activity class, the exception handler looks like this.

public class ExceptionHandler implements Thread.UncaughtExceptionHandler {
    public static final String TAG = "Exception handler";
    private final Context activity;

    public ExceptionHandler(Context activity) {
        this.activity = activity;
    }

    @Override
    public void uncaughtException(@NonNull Thread thread, @NonNull Throwable throwable) {
        Intent error = new Intent(activity, ErrorCatcher.class);
        activity.startActivity(error);
    }
}

it is initialized from the activity class

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.e(TAG, "onRestart: Hey just created");
        Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this.getApplicationContext()));
// other methods and function
}

when the control comes to the exception handler, the activity is not created, instead of a blank page that hangs my app.

The only message I get is

I/Timeline: Timeline: Activity_launch_request time:417281208 intent:Intent { cmp=com.yyy.xxx/com.yyy.xxx.Activities.Error }

EDIT: Ok, after some digging I find, if no exception is thrown then the activity is started (i.e I can see the Activity page) but when an exception is thrown that's when a blank page is displayed. Why is this the condition for only when an exception is thrown and what is a better way to handle exception in android?? any help?


EDIT 2 : it's similar to this https://codecrunch.co/blog/custom-error-handling-in-android/

答案1

得分: 3

在启动活动之前,添加error.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);。这里也有更完整的答案链接

英文:

before the startActivity, add error.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);. There are also more complete answers here

答案2

得分: 3

这段代码可能对你有帮助

Application application = (Application) context.getApplicationContext();
Intent intent = new Intent(application, ErrorActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
application.startActivity(intent);

如果不是的话,请通知我,我会给你发送完整的异常处理代码!

英文:

This code may be helpful for you

Application application = (Application) context.getApplicationContext();
Intent intent = new Intent(application, ErrorActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
application.startActivity(intent);

If not then notify me, I will send you complete code for exception handling!

答案3

得分: 1

当我使用try/catch而不是

Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this.getApplicationContext()));

来处理异常时,它起作用了,这可能不是最佳方法,但值得一试。

英文:

It worked for when i used try/catch instead of

Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this.getApplicationContext()));

to handle exception's , it might not be the best approch but it's worth a try.

答案4

得分: 1

首先,您正在使用“应用程序上下文”尝试启动一个活动。这可能会导致一些问题。这是可以做的,但我认为有一种更简单的方法来处理所有这些。

还应该注意到,您忘记了在以下代码块内的其余代码:

@Override
public void uncaughtException
    ....
    android.os.Process.killProcess(android.os.Process.myPid());
    System.exit(10);

为什么只有在抛出异常时才会出现这种情况...

这是因为您重写了uncaughtException方法。所以当出现未捕获的异常时,您将启动Error.class活动。

@Override
public void uncaughtException(@NonNull Thread thread, @NonNull Throwable throwable) {
    Intent error = new Intent(activity, ErrorCatcher.class);
    activity.startActivity(error);
}

...在Android中处理异常的更好方式是什么?

处理异常有许多方法,这实际上取决于用例。一般来说,您应该在发生错误时处理错误,至少在开始时应该如此。您可以在可能引发错误的方法上使用try/catch块来处理错误,或者您可以将错误"传递给上层",根据您的应用程序架构在适当的位置处理它,通过创建会引发错误的方法。没有更多的详细信息,我无法提供关于处理错误的最佳方式的准确响应。在我的应用程序中,如果需要用户通知,我通常会抛出一个toast,或者如果出现网络故障之类的问题,我会选择另一种路径。

异常处理是一个复杂的问题,应该以相应的方式处理。没有一种固定的正确答案来处理错误。但是,有一些基本原则:

  1. 处理所有异常。如果您有一个可能引发错误的方法,请确保用try/catch包装它并适当处理。这应该可以防止任何"未捕获的异常"。

  2. 在处理错误时要具体。看起来您试图为活动中的任何未捕获错误创建一个"捕获所有"的机制。我不会这样做。我会将所有代码都包装在try/catch块中,并根据错误发生的情况处理它们。就我对您的代码的理解,我猜您之所以得到一个空白屏幕是因为您没有为错误类创建布局,但我可能错了。

简而言之,如果我是您,我会摆脱以下内容:

@Override
public void uncaughtException(@NonNull Thread thread, @NonNull Throwable throwable) {
    Intent error = new Intent(activity, ErrorCatcher.class);
    activity.startActivity(error);
}

还要删除这个:

protected void onCreate(Bundle savedInstanceState) {
    Log.e(TAG, "onRestart: Hey just created");
    //Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this.getApplicationContext()));
}

然后,我会找出哪些方法会引发错误,并在调用它们时处理这些错误。这将是最简单的方法。然后,您可以考虑更大更复杂的错误处理方法。您不一定需要为错误创建一个新的活动。如果您想要这样做,我建议在finally块中执行。确保您已经为错误活动创建了布局;否则,它将是空白的;还要将错误活动添加到清单中(否则将会崩溃)。

try {
   // 在这里添加所有方法调用。
} catch (Exception E) {
   // 处理通用异常
} catch (ThreadException e) {
   // 处理线程异常
   ...为更具体的错误添加更多的catch块
} finally {
   // 在所有异常都被捕获后,可选地执行
   Intent error = new Intent(this, ErrorCatcher.class);
   startActivity(error);
}
英文:

First off, you are using an Application Context to try and start an activity. This may be causing some of your problems. This can be done, but I think there is a simpler way for all this to play out.

It should also be noted that you forgot the rest of the code inside the

  @Override
public void uncaughtException
    ....
    android.os.Process.killProcess(android.os.Process.myPid());
    System.exit(10);

> Why is this the condition for only when an exception is thrown...

It's because you have overridden the uncaughtException method. So when you get an uncaught exception, you are going to start the Error.class Activity.

  @Override
    public void uncaughtException(@NonNull Thread thread, @NonNull Throwable throwable) {
        Intent error = new Intent(activity, ErrorCatcher.class);
        activity.startActivity(error);
    }

> ...and what is a better way to handle exception in android??

There are a number of ways that you can handle an exception. It really depends on what the use case is. In general, you should be handling errors as they occur, at least in the beginning. You can either do this with a try/catch block on methods that can throw errors; or, you can "bubble up the error" to handle it in an appropriate place, depending on your app's architecture, by creating methods that throw errors. Without more detail, I'm not able to provide an accurate response as to the best way to handle errors. In my app's, I'll typically throw a toast, if it requires user notification, or another path if there is something like a network failure.

Exception handling is a complex issue and should be handled as such. There is no single right answer for how to handle errors. However, some basics are:

  1. Handle all exceptions. If you have a method that throws an error, make sure you wrap in a try/catch and handle appropriately. This should prevent any "uncaught exceptions".

  2. Be specific in the errors you are handling. It appears like you are trying to create a "catch-all" for any uncaught errors in your activity. I would not go about it that way. I would wrap all the code in a try/catch and handle the errors as they come up. As I think about your code, I'm guessing that the reason you get a blank screen is that you haven't created a layout for your error class, but I could be wrong.

TLDR; If I were you I'd get rid of the:

@Override
public void uncaughtException(@NonNull Thread thread, @NonNull Throwable throwable) {
    Intent error = new Intent(activity, ErrorCatcher.class);
    activity.startActivity(error);
}

Also get rid of this:

protected void onCreate(Bundle savedInstanceState) {
    Log.e(TAG, "onRestart: Hey just created");
    //Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this.getApplicationContext()));

From there I would figure out what methods are throwing errors and handle them when you call them. That is going to be the simplest method. From there you can consider a larger and more complex approach to error handling. You don't necessarily need to create a new activity for an error. If you want to, I'd do it in the finally block. Make sure you have created a layout for the error activity; otherwise, it will just be blank; added the error activity to the manifest (or it will crash).

try{
   //your add all your method calls here.
} catch (Exception E){
   //handle generic exception
} catch (ThreadException e){
   //handle the thread exception
   ...add more catches for more specific errors
} finally{
   //Optional call once all exceptions have been caught
   Intent error = new Intent(this, ErrorCatcher.class);
   startActivity(error);
}

答案5

得分: -1

你最好使用以下代码来启动活动,这是在你重写的未捕获异常方法中:

startActivity(activity, Error.class);
英文:

on your overrided uncaughtException method you better start the activity using this code

   startActivity(activity,Error.class);

huangapple
  • 本文由 发表于 2020年8月11日 04:42:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/63347752.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定