Search in sources :

Example 66 with WeakReference

use of java.lang.ref.WeakReference in project android_frameworks_base by ResurrectionRemix.

the class ImageReader method postEventFromNative.

/**
     * Called from Native code when an Event happens.
     *
     * This may be called from an arbitrary Binder thread, so access to the ImageReader must be
     * synchronized appropriately.
     */
private static void postEventFromNative(Object selfRef) {
    @SuppressWarnings("unchecked") WeakReference<ImageReader> weakSelf = (WeakReference<ImageReader>) selfRef;
    final ImageReader ir = weakSelf.get();
    if (ir == null) {
        return;
    }
    final Handler handler;
    synchronized (ir.mListenerLock) {
        handler = ir.mListenerHandler;
    }
    if (handler != null) {
        handler.sendEmptyMessage(0);
    }
}
Also used : WeakReference(java.lang.ref.WeakReference) Handler(android.os.Handler)

Example 67 with WeakReference

use of java.lang.ref.WeakReference in project atmosphere by Atmosphere.

the class TypeResolver method getTypeVariableMap.

private static Map<TypeVariable<?>, Type> getTypeVariableMap(final Class<?> targetType) {
    Reference<Map<TypeVariable<?>, Type>> ref = typeVariableCache.get(targetType);
    Map<TypeVariable<?>, Type> map = ref != null ? ref.get() : null;
    if (map == null) {
        map = new HashMap<TypeVariable<?>, Type>();
        // Populate interfaces
        buildTypeVariableMap(targetType.getGenericInterfaces(), map);
        // Populate super classes and interfaces
        Type genericType = targetType.getGenericSuperclass();
        Class<?> type = targetType.getSuperclass();
        while (type != null && !Object.class.equals(type)) {
            if (genericType instanceof ParameterizedType)
                buildTypeVariableMap((ParameterizedType) genericType, map);
            buildTypeVariableMap(type.getGenericInterfaces(), map);
            genericType = type.getGenericSuperclass();
            type = type.getSuperclass();
        }
        // Populate enclosing classes
        type = targetType;
        while (type.isMemberClass()) {
            genericType = type.getGenericSuperclass();
            if (genericType instanceof ParameterizedType)
                buildTypeVariableMap((ParameterizedType) genericType, map);
            type = type.getEnclosingClass();
        }
        if (cacheEnabled)
            typeVariableCache.put(targetType, new WeakReference<Map<TypeVariable<?>, Type>>(map));
    }
    return map;
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) GenericArrayType(java.lang.reflect.GenericArrayType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) TypeVariable(java.lang.reflect.TypeVariable) WeakReference(java.lang.ref.WeakReference) Map(java.util.Map) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap)

Example 68 with WeakReference

use of java.lang.ref.WeakReference in project DroidPlugin by DroidPluginTeam.

the class PluginManager method onServiceDisconnected.

@Override
public void onServiceDisconnected(ComponentName componentName) {
    Log.i(TAG, "onServiceDisconnected disconnected!");
    mPluginManager = null;
    Iterator<WeakReference<ServiceConnection>> iterator = sServiceConnection.iterator();
    while (iterator.hasNext()) {
        WeakReference<ServiceConnection> wsc = iterator.next();
        ServiceConnection sc = wsc != null ? wsc.get() : null;
        if (sc != null) {
            sc.onServiceDisconnected(componentName);
        } else {
            iterator.remove();
        }
    }
    //服务连接断开,需要重新连接。
    connectToService();
}
Also used : ServiceConnection(android.content.ServiceConnection) WeakReference(java.lang.ref.WeakReference)

Example 69 with WeakReference

use of java.lang.ref.WeakReference in project CustomActivityOnCrash by Ereza.

the class CustomActivityOnCrash method install.

/**
     * Installs CustomActivityOnCrash on the application using the default error activity.
     *
     * @param context Context to use for obtaining the ApplicationContext. Must not be null.
     */
public static void install(Context context) {
    try {
        if (context == null) {
            Log.e(TAG, "Install failed: context is null!");
        } else {
            if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                Log.w(TAG, "CustomActivityOnCrash will be installed, but may not be reliable in API lower than 14");
            }
            //INSTALL!
            final Thread.UncaughtExceptionHandler oldHandler = Thread.getDefaultUncaughtExceptionHandler();
            if (oldHandler != null && oldHandler.getClass().getName().startsWith(CAOC_HANDLER_PACKAGE_NAME)) {
                Log.e(TAG, "You have already installed CustomActivityOnCrash, doing nothing!");
            } else {
                if (oldHandler != null && !oldHandler.getClass().getName().startsWith(DEFAULT_HANDLER_PACKAGE_NAME)) {
                    Log.e(TAG, "IMPORTANT WARNING! You already have an UncaughtExceptionHandler, are you sure this is correct? If you use ACRA, Crashlytics or similar libraries, you must initialize them AFTER CustomActivityOnCrash! Installing anyway, but your original handler will not be called.");
                }
                application = (Application) context.getApplicationContext();
                //We define a default exception handler that does what we want so it can be called from Crashlytics/ACRA
                Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

                    @Override
                    public void uncaughtException(Thread thread, final Throwable throwable) {
                        Log.e(TAG, "App has crashed, executing CustomActivityOnCrash's UncaughtExceptionHandler", throwable);
                        if (hasCrashedInTheLastSeconds(application)) {
                            Log.e(TAG, "App already crashed in the last 2 seconds, not starting custom error activity because we could enter a restart loop. Are you sure that your app does not crash directly on init?", throwable);
                            if (oldHandler != null) {
                                oldHandler.uncaughtException(thread, throwable);
                                return;
                            }
                        } else {
                            setLastCrashTimestamp(application, new Date().getTime());
                            if (errorActivityClass == null) {
                                errorActivityClass = guessErrorActivityClass(application);
                            }
                            if (isStackTraceLikelyConflictive(throwable, errorActivityClass)) {
                                Log.e(TAG, "Your application class or your error activity have crashed, the custom activity will not be launched!");
                                if (oldHandler != null) {
                                    oldHandler.uncaughtException(thread, throwable);
                                    return;
                                }
                            } else if (launchErrorActivityWhenInBackground || !isInBackground) {
                                final Intent intent = new Intent(application, errorActivityClass);
                                StringWriter sw = new StringWriter();
                                PrintWriter pw = new PrintWriter(sw);
                                throwable.printStackTrace(pw);
                                String stackTraceString = sw.toString();
                                //And: http://stackoverflow.com/questions/11451393/what-to-do-on-transactiontoolargeexception#comment46697371_12809171
                                if (stackTraceString.length() > MAX_STACK_TRACE_SIZE) {
                                    String disclaimer = " [stack trace too large]";
                                    stackTraceString = stackTraceString.substring(0, MAX_STACK_TRACE_SIZE - disclaimer.length()) + disclaimer;
                                }
                                if (enableAppRestart && restartActivityClass == null) {
                                    //We can set the restartActivityClass because the app will terminate right now,
                                    //and when relaunched, will be null again by default.
                                    restartActivityClass = guessRestartActivityClass(application);
                                } else if (!enableAppRestart) {
                                    //In case someone sets the activity and then decides to not restart
                                    restartActivityClass = null;
                                }
                                intent.putExtra(EXTRA_STACK_TRACE, stackTraceString);
                                intent.putExtra(EXTRA_RESTART_ACTIVITY_CLASS, restartActivityClass);
                                intent.putExtra(EXTRA_SHOW_ERROR_DETAILS, showErrorDetails);
                                intent.putExtra(EXTRA_EVENT_LISTENER, eventListener);
                                intent.putExtra(EXTRA_IMAGE_DRAWABLE_ID, defaultErrorActivityDrawableId);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                if (eventListener != null) {
                                    eventListener.onLaunchErrorActivity();
                                }
                                application.startActivity(intent);
                            }
                        }
                        final Activity lastActivity = lastActivityCreated.get();
                        if (lastActivity != null) {
                            //We finish the activity, this solves a bug which causes infinite recursion.
                            //This is unsolvable in API<14, so beware!
                            //See: https://github.com/ACRA/acra/issues/42
                            lastActivity.finish();
                            lastActivityCreated.clear();
                        }
                        killCurrentProcess();
                    }
                });
                if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                    application.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {

                        int currentlyStartedActivities = 0;

                        @Override
                        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                            if (activity.getClass() != errorActivityClass) {
                                // Copied from ACRA:
                                // Ignore activityClass because we want the last
                                // application Activity that was started so that we can
                                // explicitly kill it off.
                                lastActivityCreated = new WeakReference<>(activity);
                            }
                        }

                        @Override
                        public void onActivityStarted(Activity activity) {
                            currentlyStartedActivities++;
                            isInBackground = (currentlyStartedActivities == 0);
                        //Do nothing
                        }

                        @Override
                        public void onActivityResumed(Activity activity) {
                        //Do nothing
                        }

                        @Override
                        public void onActivityPaused(Activity activity) {
                        //Do nothing
                        }

                        @Override
                        public void onActivityStopped(Activity activity) {
                            //Do nothing
                            currentlyStartedActivities--;
                            isInBackground = (currentlyStartedActivities == 0);
                        }

                        @Override
                        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                        //Do nothing
                        }

                        @Override
                        public void onActivityDestroyed(Activity activity) {
                        //Do nothing
                        }
                    });
                }
                Log.i(TAG, "CustomActivityOnCrash has been installed.");
            }
        }
    } catch (Throwable t) {
        Log.e(TAG, "An unknown error occurred while installing CustomActivityOnCrash, it may not have been properly initialized. Please report this as a bug if needed.", t);
    }
}
Also used : Bundle(android.os.Bundle) DefaultErrorActivity(cat.ereza.customactivityoncrash.activity.DefaultErrorActivity) Activity(android.app.Activity) Intent(android.content.Intent) Date(java.util.Date) SuppressLint(android.annotation.SuppressLint) StringWriter(java.io.StringWriter) WeakReference(java.lang.ref.WeakReference) Application(android.app.Application) PrintWriter(java.io.PrintWriter)

Example 70 with WeakReference

use of java.lang.ref.WeakReference in project AndroidChromium by JackyAndroid.

the class ChromeLauncherActivity method launchFirstRunExperience.

/**
     * Tries to launch the First Run Experience.  If ChromeLauncherActivity is running with the
     * wrong Intent flags, we instead relaunch ChromeLauncherActivity to make sure it runs in its
     * own task, which then triggers First Run.
     * @return Whether or not the First Run Experience needed to be shown.
     * @param forTabbedMode Whether the First Run Experience is launched for tabbed mode.
     */
private boolean launchFirstRunExperience(boolean forTabbedMode) {
    // Tries to launch the Generic First Run Experience for intent from GSA.
    boolean showLightweightFre = IntentHandler.determineExternalIntentSource(this.getPackageName(), getIntent()) != ExternalAppId.GSA;
    Intent freIntent = FirstRunFlowSequencer.checkIfFirstRunIsNecessary(this, getIntent(), showLightweightFre);
    if (freIntent == null)
        return false;
    if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
        if (CommandLine.getInstance().hasSwitch(ChromeSwitches.ENABLE_LIGHTWEIGHT_FIRST_RUN_EXPERIENCE)) {
            boolean isTabbedModeActive = false;
            boolean isLightweightFreActive = false;
            boolean isGenericFreActive = false;
            List<WeakReference<Activity>> activities = ApplicationStatus.getRunningActivities();
            for (WeakReference<Activity> weakActivity : activities) {
                Activity activity = weakActivity.get();
                if (activity == null) {
                    continue;
                }
                if (activity instanceof ChromeTabbedActivity) {
                    isTabbedModeActive = true;
                    continue;
                }
                if (activity instanceof LightweightFirstRunActivity) {
                    isLightweightFreActive = true;
                    // A Generic or a new Lightweight First Run Experience will be launched
                    // below, so finish the old Lightweight First Run Experience.
                    activity.setResult(Activity.RESULT_CANCELED);
                    activity.finish();
                    continue;
                }
                if (activity instanceof FirstRunActivity) {
                    isGenericFreActive = true;
                    continue;
                }
            }
            if (forTabbedMode) {
                if (isTabbedModeActive || isLightweightFreActive || !showLightweightFre) {
                    // Lets ChromeTabbedActivity checks and launches the Generic First Run
                    // Experience.
                    launchTabbedMode(false);
                    finish();
                    return true;
                }
            } else if (isGenericFreActive) {
                // Launch the Generic First Run Experience if it is active previously.
                freIntent = FirstRunFlowSequencer.createGenericFirstRunIntent(this, TextUtils.equals(getIntent().getAction(), Intent.ACTION_MAIN));
            }
        }
        // Add a PendingIntent so that the intent used to launch Chrome will be resent when
        // first run is completed or canceled.
        FirstRunFlowSequencer.addPendingIntent(this, freIntent, getIntent());
        startActivity(freIntent);
    } else {
        Intent newIntent = new Intent(getIntent());
        newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(newIntent);
    }
    finish();
    return true;
}
Also used : LightweightFirstRunActivity(org.chromium.chrome.browser.firstrun.LightweightFirstRunActivity) ChromeTabbedActivity(org.chromium.chrome.browser.ChromeTabbedActivity) LightweightFirstRunActivity(org.chromium.chrome.browser.firstrun.LightweightFirstRunActivity) FirstRunActivity(org.chromium.chrome.browser.firstrun.FirstRunActivity) WeakReference(java.lang.ref.WeakReference) WebappLauncherActivity(org.chromium.chrome.browser.webapps.WebappLauncherActivity) LightweightFirstRunActivity(org.chromium.chrome.browser.firstrun.LightweightFirstRunActivity) ChromeTabbedActivity(org.chromium.chrome.browser.ChromeTabbedActivity) CustomTabActivity(org.chromium.chrome.browser.customtabs.CustomTabActivity) SeparateTaskCustomTabActivity(org.chromium.chrome.browser.customtabs.SeparateTaskCustomTabActivity) UpgradeActivity(org.chromium.chrome.browser.upgrade.UpgradeActivity) FirstRunActivity(org.chromium.chrome.browser.firstrun.FirstRunActivity) Activity(android.app.Activity) CustomTabsIntent(android.support.customtabs.CustomTabsIntent) Intent(android.content.Intent)

Aggregations

WeakReference (java.lang.ref.WeakReference)291 ArrayList (java.util.ArrayList)32 HashMap (java.util.HashMap)24 Map (java.util.Map)24 Field (java.lang.reflect.Field)19 Activity (android.app.Activity)17 Iterator (java.util.Iterator)17 IOException (java.io.IOException)16 Method (java.lang.reflect.Method)15 File (java.io.File)14 URLClassLoader (java.net.URLClassLoader)14 Test (org.junit.Test)13 Reference (java.lang.ref.Reference)12 ReferenceQueue (java.lang.ref.ReferenceQueue)12 Resources (android.content.res.Resources)10 Handler (android.os.Handler)10 AbstractModule (com.google.inject.AbstractModule)10 Injector (com.google.inject.Injector)10 ArrayMap (android.util.ArrayMap)9 URL (java.net.URL)8