Exemplo n.º 1
1
 /** 初始化 */
 public void init(Context context) {
   this.context = context;
   // 获取系统默认的UncaughtException处理器
   mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
   // 设置该CrashHandler为程序的默认处理器
   Thread.setDefaultUncaughtExceptionHandler(this);
 }
Exemplo n.º 2
0
  private void handleTaskEvents(PropertyChangeEvent evt) {
    String taskId = null;
    if (evt.getSource() instanceof SolaTask) {
      taskId = ((SolaTask) evt.getSource()).getId();
    }

    if (evt.getPropertyName().equals(SolaTask.EVENT_STATE)) {
      StateValue state = (StateValue) evt.getNewValue();
      if (state.name().equalsIgnoreCase(SolaTask.TASK_DONE)) {
        tasks.remove(taskId);
      }
    }

    if (evt.getPropertyName().equals(SolaTask.REMOVE_TASK)) {
      tasks.remove(taskId);
    }

    if (evt.getPropertyName().equals(SolaTask.EXCEPTION_RISED)) {
      if (Throwable.class.isAssignableFrom(evt.getNewValue().getClass())) {
        UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        if (defaultHandler != null) {
          Thread.getDefaultUncaughtExceptionHandler()
              .uncaughtException(Thread.currentThread(), (Throwable) evt.getNewValue());
        } else {
          DefaultExceptionHandler.handleException((Throwable) evt.getNewValue());
        }
      }
      if (taskId != null) {
        tasks.remove(taskId);
      }
    }

    propertySupport.firePropertyChange(evt);
  }
 /**
  * 異常處理初始化
  *
  * @param context
  */
 public void init(Context context) {
   this.mContext = context;
   // 獲取系統默認的UncaughtException處理器
   defalutHandler = Thread.getDefaultUncaughtExceptionHandler();
   // 設置該CrashHandler為程序的默認處理器
   Thread.setDefaultUncaughtExceptionHandler(this);
 }
 public void Init(Context context) {
   Log.d(LOG, "init");
   PreviousHandler = Thread.getDefaultUncaughtExceptionHandler();
   Thread.setDefaultUncaughtExceptionHandler(this);
   RecoltInformations(context);
   CurContext = context;
 }
Exemplo n.º 5
0
 /**
  * 初始化,注册Context对象, 获取系统默认的UncaughtException处理器, 设置该CrashHandler为程序的默认处理器
  *
  * @param ctx
  */
 public void init(Context ctx) {
   mContext = ctx;
   mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
   Thread.setDefaultUncaughtExceptionHandler(this);
   SharedPreferences userInfo = ctx.getSharedPreferences("userInfo", 0);
   userName = userInfo.getString("username", null);
 }
 public static void regist() {
   UncaughtExceptionHandler cur_handler = Thread.getDefaultUncaughtExceptionHandler();
   if (cur_handler instanceof ExceptionHandler) return;
   orig_handler = cur_handler;
   Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
   log.d("setDefaultUncaughtExceptionHandler");
 }
Exemplo n.º 7
0
  @Override
  public void onCreate() {
    super.onCreate();

    Thread.setDefaultUncaughtExceptionHandler(
        new MyUncaughtExceptionHandler(Thread.getDefaultUncaughtExceptionHandler()));
  }
Exemplo n.º 8
0
 private void setUncaughtExceptionHandler() {
   Thread.UncaughtExceptionHandler handler = Thread.getDefaultUncaughtExceptionHandler();
   if (!(handler instanceof SubsonicActivity.SubsonicUncaughtExceptionHandler)) {
     Thread.setDefaultUncaughtExceptionHandler(
         new SubsonicActivity.SubsonicUncaughtExceptionHandler(this));
   }
 }
Exemplo n.º 9
0
  /**
   * 初始化
   *
   * @param context
   */
  public void initialize(Context context) {

    if (mInitialized) {
      return;
    }

    Set<String> neededPermissions = new TreeSet<>();
    neededPermissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (!checkPermissions(context, neededPermissions)) {
      StringBuilder sb = new StringBuilder();
      for (String permission : neededPermissions) {
        sb.append(permission).append("\n");
      }
      throw new IllegalArgumentException("Permissions needed:\n " + sb.toString());
    }

    // 在单例中使用全局Application Context
    mContext = context.getApplicationContext();

    // 获取系统默认的UncaughtException处理器
    mLocalExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();

    // 设置该CrashHandler为程序的默认处理器
    Thread.setDefaultUncaughtExceptionHandler(this);

    mInitialized = true;
  }
Exemplo n.º 10
0
  /** Set own uncaught exception handler to log crashes */
  public static void init() {
    new SendTask(false).start();

    sDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
    if (!(sDefaultHandler instanceof RemoteLog)) {
      Thread.setDefaultUncaughtExceptionHandler(new RemoteLog());
    }
  }
Exemplo n.º 11
0
  @SuppressLint("NewApi")
  public static final void init(Application application) {
    if (Thread.getDefaultUncaughtExceptionHandler() instanceof CrashHelper) {
      return;
    }

    CrashHelper helper = new CrashHelper();
    Thread.setDefaultUncaughtExceptionHandler(helper);
  }
Exemplo n.º 12
0
 public DefaultExceptionHandler() {
   defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
   intent =
       PendingIntent.getActivity(
           OsmandApplication.this.getBaseContext(),
           0,
           new Intent(
               OsmandApplication.this.getBaseContext(), getAppCustomization().getMapActivity()),
           0);
 }
  /**
   * Send @param t and any exception wrapped by @param r to the default uncaught exception handler,
   * or log them if none such is set up
   */
  public static void logExceptionsAfterExecute(Runnable r, Throwable t) {
    Throwable hiddenThrowable = extractThrowable(r);
    if (hiddenThrowable != null) handleOrLog(hiddenThrowable);

    // ThreadPoolExecutor will re-throw exceptions thrown by its Task (which
    // will be seen by
    // the default uncaught exception handler) so we only need to do
    // anything if that handler
    // isn't set up yet.
    if (t != null && Thread.getDefaultUncaughtExceptionHandler() == null) handleOrLog(t);
  }
Exemplo n.º 14
0
 @Override
 public void onSuccess(Object result) {
   if (isShutdown.get()) {
     LOG.info("Wait queue scheduler worker exited with success!");
   } else {
     LOG.error("Wait queue scheduler worker exited with success!");
     Thread.getDefaultUncaughtExceptionHandler()
         .uncaughtException(
             Thread.currentThread(),
             new IllegalStateException("WaitQueue worked exited before shutdown"));
   }
 }
Exemplo n.º 15
0
 @Test
 public void testPiwikExceptionHandler() throws Exception {
   Tracker tracker = createTracker();
   assertFalse(Thread.getDefaultUncaughtExceptionHandler() instanceof PiwikExceptionHandler);
   QuickTrack.trackUncaughtExceptions(tracker);
   assertTrue(Thread.getDefaultUncaughtExceptionHandler() instanceof PiwikExceptionHandler);
   try {
     int i = 1 / 0;
     assertNotEquals(i, 0);
   } catch (Exception e) {
     (Thread.getDefaultUncaughtExceptionHandler()).uncaughtException(Thread.currentThread(), e);
   }
   QueryHashMap<String, String> queryParams = parseEventUrl(tracker.getLastEvent());
   validateDefaultQuery(queryParams);
   assertEquals(queryParams.get(QueryParams.EVENT_CATEGORY), "Exception");
   assertTrue(
       queryParams
           .get(QueryParams.EVENT_ACTION)
           .startsWith("org.piwik.sdk.QuickTrackTest/testPiwikExceptionHandler:"));
   assertEquals(queryParams.get(QueryParams.EVENT_NAME), "/ by zero");
   assertEquals(queryParams.get(QueryParams.EVENT_VALUE), "1");
 }
Exemplo n.º 16
0
  private ExceptionHandler(Context context, boolean chained) {

    PackageManager mPackManager = context.getPackageManager();
    PackageInfo mPackInfo;
    try {
      mPackInfo = mPackManager.getPackageInfo(context.getPackageName(), 0);
      versionName = mPackInfo.versionName;
      versionCode = mPackInfo.versionCode;
    } catch (PackageManager.NameNotFoundException e) {
      // ignore
    }
    if (chained) previousHandler = Thread.getDefaultUncaughtExceptionHandler();
    else previousHandler = null;
    stacktraceDir = String.format("/Android/data/%s/files/", context.getPackageName());
  }
Exemplo n.º 17
0
 @Override
 public final void run() {
   try {
     if (!mGifDrawable.isRecycled()) {
       doWork();
     }
   } catch (Throwable throwable) {
     final Thread.UncaughtExceptionHandler uncaughtExceptionHandler =
         Thread.getDefaultUncaughtExceptionHandler();
     if (uncaughtExceptionHandler != null) {
       uncaughtExceptionHandler.uncaughtException(Thread.currentThread(), throwable);
     }
     // throw throwable;
   }
 }
Exemplo n.º 18
0
  /**
   * This test creates three empty files and lets their leases expire. This triggers release of the
   * leases. The empty files are supposed to be closed by that without causing
   * ConcurrentModificationException.
   */
  public void testLeaseExpireEmptyFiles() throws Exception {
    final Thread.UncaughtExceptionHandler oldUEH = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(
        new Thread.UncaughtExceptionHandler() {
          public void uncaughtException(Thread t, Throwable e) {
            if (e instanceof ConcurrentModificationException) {
              FSNamesystem.LOG.error("t=" + t, e);
              isConcurrentModificationException = true;
            }
          }
        });

    System.out.println("testLeaseExpireEmptyFiles start");
    final long leasePeriod = 1000;
    final int DATANODE_NUM = 3;

    final Configuration conf = new HdfsConfiguration();
    conf.setInt(DFSConfigKeys.DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY, 1000);
    conf.setInt("dfs.heartbeat.interval", 1);

    // create cluster
    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(DATANODE_NUM).build();
    try {
      cluster.waitActive();
      DistributedFileSystem dfs = (DistributedFileSystem) cluster.getFileSystem();

      // create a new file.
      TestFileCreation.createFile(dfs, new Path("/foo"), DATANODE_NUM);
      TestFileCreation.createFile(dfs, new Path("/foo2"), DATANODE_NUM);
      TestFileCreation.createFile(dfs, new Path("/foo3"), DATANODE_NUM);

      // set the soft and hard limit to be 1 second so that the
      // namenode triggers lease recovery
      cluster.setLeasePeriod(leasePeriod, leasePeriod);
      // wait for the lease to expire
      try {
        Thread.sleep(5 * leasePeriod);
      } catch (InterruptedException e) {
      }

      assertFalse(isConcurrentModificationException);
    } finally {
      Thread.setDefaultUncaughtExceptionHandler(oldUEH);
      cluster.shutdown();
    }
  }
Exemplo n.º 19
0
 public static HttpErrorCollector registerInVM(
     Context applicationContext, String version, MyceliumWalletApi api) {
   // Initialize error collector
   boolean emailOnErrors = applicationContext.getResources().getBoolean(R.bool.email_on_errors);
   if (!emailOnErrors) {
     return null;
   }
   Thread.UncaughtExceptionHandler orig = Thread.getDefaultUncaughtExceptionHandler();
   if ((orig instanceof HttpErrorCollector)) {
     return (HttpErrorCollector) orig;
   }
   Log.i(
       Constants.TAG,
       "registering exception handler from thread " + Thread.currentThread().getName());
   HttpErrorCollector ret =
       new HttpErrorCollector(orig, api, version, buildMetaData(applicationContext));
   Thread.setDefaultUncaughtExceptionHandler(ret);
   return ret;
 }
Exemplo n.º 20
0
  /** http://stackoverflow.com/a/26560727 */
  private void setupExceptionHandler() {
    final Thread.UncaughtExceptionHandler oldHandler = Thread.getDefaultUncaughtExceptionHandler();

    Thread.setDefaultUncaughtExceptionHandler(
        new Thread.UncaughtExceptionHandler() {
          @Override
          public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
            // Do your own error handling here

            // try to write log file to the image path.
            writeException(paramThread, paramThrowable);

            if (oldHandler != null)
              oldHandler.uncaughtException(
                  paramThread, paramThrowable); // Delegates to Android's error handling
            else System.exit(2); // Prevents the service/app from freezing
          }
        });
  }
 /**
  * 初始化
  *
  * @param context 上下文
  * @return {@code true}: 成功<br>
  *     {@code false}: 失败
  */
 public boolean init(Context context) {
   if (mInitialized) return true;
   if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
     crashDir =
         context.getExternalCacheDir().getPath() + File.separator + "crash" + File.separator;
   } else {
     crashDir = context.getCacheDir().getPath() + File.separator + "crash" + File.separator;
   }
   try {
     PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
     versionName = pi.versionName;
     versionCode = pi.versionCode;
   } catch (PackageManager.NameNotFoundException e) {
     e.printStackTrace();
     return false;
   }
   mHandler = Thread.getDefaultUncaughtExceptionHandler();
   Thread.setDefaultUncaughtExceptionHandler(this);
   return mInitialized = true;
 }
Exemplo n.º 22
0
  public static void main(String[] args) {
    // first of all config log
    configLogFile();

    final UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(
        new UncaughtExceptionHandler() {
          @Override
          public void uncaughtException(Thread t, Throwable e) {
            if (!(e instanceof ThreadDeath)) {
              ExceptionHandler.handle("Error in thread " + t.getName(), e); // $NON-NLS-1$
            }
            defaultHandler.uncaughtException(t, e);
          }
        });

    MAIN_APP = new OsmExtractionUI();
    MAIN_APP.frame.setBounds(DataExtractionSettings.getSettings().getWindowBounds());
    MAIN_APP.frame.setVisible(true);
  }
Exemplo n.º 23
0
  @Override
  public void onCreate() {
    super.onCreate();
    TiScriptRunner.getInstance().setAppPackageName(getPackageName());
    if (DBG) {
      Log.d(LCAT, "Application onCreate");
    }

    final UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(
        new UncaughtExceptionHandler() {

          public void uncaughtException(Thread t, Throwable e) {
            String tiVer = buildVersion + "," + buildTimestamp + "," + buildHash;
            Log.e(
                "TiUncaughtHandler",
                "Sending event: exception on thread: "
                    + t.getName()
                    + " msg:"
                    + e.toString()
                    + "; Titanium "
                    + tiVer,
                e);
            postAnalyticsEvent(TiAnalyticsEventFactory.createErrorEvent(t, e, tiVer));
            defaultHandler.uncaughtException(t, e);
          }
        });

    baseUrl = "file:///android_asset/Resources/";

    File fullPath = new File(baseUrl, getStartFilename("app.js"));
    baseUrl = fullPath.getParent();

    methodMap = new HashMap<Class<?>, HashMap<String, Method>>(25);
    proxyMap = new HashMap<String, SoftReference<KrollProxy>>(5);

    appProperties = new TiProperties(getApplicationContext(), APPLICATION_PREFERENCES_NAME, false);
    systemProperties = new TiProperties(getApplicationContext(), "system", true);

    // systemProperties.setString("ti.version", buildVersion); // was always setting "1.0"
  }
Exemplo n.º 24
0
  /** Define custom ExceptionHandler which takes action on OutOfMemoryError. */
  private void setExceptionHandler() {
    final UncaughtExceptionHandler defaultExceptionHandler =
        Thread.getDefaultUncaughtExceptionHandler();

    UncaughtExceptionHandler customExceptionHandler =
        new UncaughtExceptionHandler() {
          @Override
          public void uncaughtException(final Thread thread, final Throwable ex) {
            if (ex instanceof OutOfMemoryError) {
              // Store info about OutOfMemoryError
              PreferenceUtil.setSharedPreferenceBoolean(
                  R.string.key_internal_outofmemoryerror, true);
            }

            // re-throw critical exception further to the os
            defaultExceptionHandler.uncaughtException(thread, ex);
          }
        };

    Thread.setDefaultUncaughtExceptionHandler(customExceptionHandler);
  }
Exemplo n.º 25
0
 @Override
 protected void afterExecute(Runnable r, Throwable t) {
   // We must make sure that we don't swallow exceptions, we must propagate them back.
   if ((t == null) && (r instanceof Future<?>)) {
     try {
       Future<?> future = (Future<?>) r;
       assert future.isDone();
       future.get();
     } catch (CancellationException ce) {
       t = ce;
     } catch (ExecutionException ee) {
       t = ee.getCause();
     } catch (InterruptedException ie) {
       Thread.currentThread().interrupt(); // ignore/reset
     }
   }
   if (t != null) {
     Thread.getDefaultUncaughtExceptionHandler()
         .uncaughtException(Thread.currentThread(), t);
   }
 };
/**
 * SampleApplication.java
 *
 * <p>This file is a part of the Yandex.Metrica for Apps.
 *
 * <p>Version for Android © 2013 YANDEX
 *
 * <p>You may not use this file except in compliance with the License. You may obtain a copy of the
 * License at http://legal.yandex.com/metrica_termsofuse/
 */
public class SampleApplication extends Application {

  private static final Thread.UncaughtExceptionHandler mDefaultExceptionHandler =
      Thread.getDefaultUncaughtExceptionHandler();

  @Override
  public void onCreate() {
    super.onCreate();

    /** Initialize metrica */
    Counter.initialize(this);

    /** Can be set programmatically or into the AndroidManifest.xml */
    /** Counter.sharedInstance().setApiKey("1111"); */

    /** Can be set programmatically or into the AndroidManifest.xml */
    /** Counter.sharedInstance().setCustomAppVersion("1.0"); */
  }

  static Thread.UncaughtExceptionHandler getDefaultExceptionHandler() {
    return mDefaultExceptionHandler;
  }
}
Exemplo n.º 27
0
  /**
   * Can only be constructed from within this class.
   *
   * @param context Context for the application in which ACRA is running.
   * @param prefs SharedPreferences used by ACRA.
   * @param enabled Whether this ErrorReporter should capture Exceptions and forward their reports.
   */
  ErrorReporter(Application context, SharedPreferences prefs, boolean enabled) {

    this.mContext = context;
    this.prefs = prefs;
    this.enabled = enabled;

    // Store the initial Configuration state.
    final String initialConfiguration = ConfigurationCollector.collectConfiguration(mContext);

    // Sets the application start date.
    // This will be included in the reports, will be helpful compared to
    // user_crash date.
    final Time appStartDate = new Time();
    appStartDate.setToNow();

    if (Compatibility.getAPILevel() >= 14) { // ActivityLifecycleCallback
      // only available for API14+
      ApplicationHelper.registerActivityLifecycleCallbacks(
          context,
          new ActivityLifecycleCallbacksCompat() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
              if (ACRA.DEV_LOGGING)
                ACRA.log.d(ACRA.LOG_TAG, "onActivityCreated " + activity.getClass());
              if (!(activity instanceof CrashReportDialog)) {
                // Ignore CrashReportDialog because we want the last
                // application Activity that was started so that we can
                // explicitly kill it off.
                lastActivityCreated = new WeakReference<Activity>(activity);
              }
            }

            @Override
            public void onActivityStarted(Activity activity) {
              if (ACRA.DEV_LOGGING)
                ACRA.log.d(ACRA.LOG_TAG, "onActivityStarted " + activity.getClass());
            }

            @Override
            public void onActivityResumed(Activity activity) {
              if (ACRA.DEV_LOGGING)
                ACRA.log.d(ACRA.LOG_TAG, "onActivityResumed " + activity.getClass());
            }

            @Override
            public void onActivityPaused(Activity activity) {
              if (ACRA.DEV_LOGGING)
                ACRA.log.d(ACRA.LOG_TAG, "onActivityPaused " + activity.getClass());
            }

            @Override
            public void onActivityStopped(Activity activity) {
              if (ACRA.DEV_LOGGING)
                ACRA.log.d(ACRA.LOG_TAG, "onActivityStopped " + activity.getClass());
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
              if (ACRA.DEV_LOGGING)
                ACRA.log.i(ACRA.LOG_TAG, "onActivitySaveInstanceState " + activity.getClass());
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
              if (ACRA.DEV_LOGGING)
                ACRA.log.i(ACRA.LOG_TAG, "onActivityDestroyed " + activity.getClass());
            }
          });
    }

    crashReportDataFactory =
        new CrashReportDataFactory(mContext, prefs, appStartDate, initialConfiguration);

    // If mDfltExceptionHandler is not null, initialization is already done.
    // Don't do it twice to avoid losing the original handler.
    mDfltExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(this);
  }
Exemplo n.º 28
0
 public VlcCrashHandler() {
   this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
 }
Exemplo n.º 29
0
 protected void init() {
   mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
   Thread.setDefaultUncaughtExceptionHandler(this);
 }
 public final void a(Context paramContext)
 {
   boolean bool2 = true;
   if (paramContext == null) {
     dav.b("Context cannot be null");
   }
   Object localObject;
   dbd localdbd;
   dao localdao;
   do
   {
     return;
     localObject = czv.a();
     localdbd = new dbd(paramContext.getApplicationContext());
     localdao = dao.a(paramContext.getApplicationContext());
     if (paramContext == null) {
       dav.b("Context cannot be null");
     }
   } while (w != null);
   w = paramContext.getApplicationContext();
   x = localdao;
   y = ((dbi)localObject);
   h = localdbd;
   n = h.a("ga_trackingId");
   if (TextUtils.isEmpty(n))
   {
     n = h.a("ga_api_key");
     if (TextUtils.isEmpty(n))
     {
       dav.b("EasyTracker requested, but missing required ga_trackingId");
       g = new czp(this);
       return;
     }
   }
   a = true;
   o = h.a("ga_appName");
   p = h.a("ga_appVersion");
   r = h.c("ga_debug");
   s = h.b("ga_sampleFrequency");
   if (s == null) {
     s = new Double(h.a("ga_sampleRate", 100));
   }
   q = h.a("ga_dispatchPeriod", 1800);
   d = (h.a("ga_sessionTimeout", 30) * 1000);
   boolean bool1 = bool2;
   if (!h.c("ga_autoActivityTracking")) {
     if (!h.c("ga_auto_activity_tracking")) {
       break label548;
     }
   }
   label548:
   for (bool1 = bool2;; bool1 = false)
   {
     b = bool1;
     t = h.c("ga_anonymizeIp");
     u = h.c("ga_reportUncaughtExceptions");
     g = x.a(n);
     if (!TextUtils.isEmpty(o))
     {
       dav.c("setting appName to " + o);
       g.a(o);
     }
     if (p != null) {
       g.b(p);
     }
     g.a(t);
     g.a(s.doubleValue());
     paramContext = x;
     bool1 = r;
     dam.a.a(dan.L);
     a = bool1;
     dav.a = bool1;
     y.a(q);
     if (!u) {
       break;
     }
     localObject = v;
     paramContext = (Context)localObject;
     if (localObject == null) {
       paramContext = new czs(g, y, Thread.getDefaultUncaughtExceptionHandler(), w);
     }
     Thread.setDefaultUncaughtExceptionHandler(paramContext);
     return;
   }
 }