简体   繁体   中英

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

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 (ie 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/

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

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.

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!

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);
}

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

   startActivity(activity,Error.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM