1 /* 2 * Copyright (C) 2020 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.car.messenger.impl; 18 19 import android.app.Application; 20 import android.os.Handler; 21 22 import androidx.annotation.NonNull; 23 import androidx.annotation.Nullable; 24 25 import com.android.car.messenger.core.util.L; 26 27 import java.lang.Thread.UncaughtExceptionHandler; 28 29 /** The application object */ 30 public class CarMessengerApp extends Application implements UncaughtExceptionHandler { 31 @Nullable private static UncaughtExceptionHandler sSystemUncaughtExceptionHandler; 32 33 @Override onCreate()34 public void onCreate() { 35 super.onCreate(); 36 AppFactoryImpl.register(this); 37 sSystemUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler(); 38 Thread.setDefaultUncaughtExceptionHandler(this); 39 } 40 41 @Override onLowMemory()42 public void onLowMemory() { 43 super.onLowMemory(); 44 L.d("onLowMemory"); 45 } 46 47 @Override uncaughtException(final Thread thread, final Throwable ex)48 public void uncaughtException(final Thread thread, final Throwable ex) { 49 final boolean background = getMainLooper().getThread() != thread; 50 if (background) { 51 L.e("Uncaught exception in background thread " + thread, ex); 52 final Handler handler = new Handler(getMainLooper()); 53 handler.post(() -> nullSafeUncaughtException(thread, ex)); 54 } else { 55 nullSafeUncaughtException(thread, ex); 56 } 57 } 58 nullSafeUncaughtException(@onNull Thread thread, @NonNull Throwable ex)59 private static void nullSafeUncaughtException(@NonNull Thread thread, @NonNull Throwable ex) { 60 if (sSystemUncaughtExceptionHandler != null) { 61 sSystemUncaughtExceptionHandler.uncaughtException(thread, ex); 62 } 63 } 64 } 65