Example usage for java.lang.ref WeakReference WeakReference

List of usage examples for java.lang.ref WeakReference WeakReference

Introduction

In this page you can find the example usage for java.lang.ref WeakReference WeakReference.

Prototype

public WeakReference(T referent) 

Source Link

Document

Creates a new weak reference that refers to the given object.

Usage

From source file:com.amazonaws.mobile.auth.google.GoogleSignInProvider.java

private boolean getPermissionsIfNecessary(final Activity activity) {
    if (ContextCompat.checkSelfPermission(activity.getApplicationContext(),
            Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
        this.activityWeakReference = new WeakReference<Activity>(activity);
        ActivityCompat.requestPermissions(activity, new String[] { Manifest.permission.GET_ACCOUNTS },
                GET_ACCOUNTS_PERMISSION_REQUEST_CODE);
        return true;
    }/*from w w  w  .jav  a2  s  .  c  o m*/

    return false;
}

From source file:com.cleveroad.audiowidget.AudioWidget.java

@NonNull
private Controller newController() {
    return new Controller() {

        @Override// w  w w .j  a  v a  2 s  .c o m
        public void start() {
            playbackState.start(this);
        }

        @Override
        public void pause() {
            playbackState.pause(this);
        }

        @Override
        public void stop() {
            playbackState.stop(this);
        }

        @Override
        public int duration() {
            return playbackState.duration();
        }

        @Override
        public void duration(int duration) {
            playbackState.duration(duration);
        }

        @Override
        public int position() {
            return playbackState.position();
        }

        @Override
        public void position(int position) {
            playbackState.position(position);
        }

        @Override
        public void onControlsClickListener(@Nullable OnControlsClickListener onControlsClickListener) {
            AudioWidget.this.onControlsClickListener.onControlsClickListener(onControlsClickListener);
        }

        @Override
        public void onWidgetStateChangedListener(
                @Nullable OnWidgetStateChangedListener onWidgetStateChangedListener) {
            AudioWidget.this.onWidgetStateChangedListener = onWidgetStateChangedListener;
        }

        @Override
        public void albumCover(@Nullable Drawable albumCover) {
            expandCollapseWidget.albumCover(albumCover);
            playPauseButton.albumCover(albumCover);
        }

        @Override
        public void albumCoverBitmap(@Nullable Bitmap bitmap) {
            if (bitmap == null) {
                return;
            }
            WeakReference<Drawable> wrDrawable = albumCoverCache.get(bitmap.hashCode());
            if (wrDrawable != null) {
                Drawable drawable = wrDrawable.get();
                if (drawable != null) {
                    expandCollapseWidget.albumCover(drawable);
                    playPauseButton.albumCover(drawable);
                    return;
                }
            }
            Drawable albumCover = new BitmapDrawable(context.getResources(), bitmap);
            expandCollapseWidget.albumCover(albumCover);
            playPauseButton.albumCover(albumCover);
            albumCoverCache.put(bitmap.hashCode(), new WeakReference<>(albumCover));
        }
    };
}

From source file:com.cr_wd.android.network.HttpClient.java

/**
 * Performs a HTTP GET/POST Request/*from  w  ww  . ja v  a 2s  .  c  o m*/
 * 
 * @return id of the request
 */
protected int doRequest(final Method method, final String url, HttpHeaders headers, HttpParams params,
        final HttpHandler handler) {
    if (headers == null) {
        headers = new HttpHeaders();
    }
    if (params == null) {
        params = new HttpParams();
    }

    handler.client = this;

    final int requestId = incrementRequestId();

    class HandlerRunnable extends Handler implements Runnable {

        private final Method method;
        private String url;
        private final HttpHeaders headers;
        private final HttpParams params;
        private final HttpHandler handler;
        private HttpResponse response;

        private boolean canceled = false;
        private int retries = 0;

        protected HandlerRunnable(final Method method, final String url, final HttpHeaders headers,
                final HttpParams params, final HttpHandler handler) {
            this.method = method;
            this.url = url;
            this.headers = headers;
            this.params = params;
            this.handler = handler;
        }

        @Override
        public void run() {
            execute();
        }

        private void execute() {
            response = new HttpResponse(requestId, method, url);

            HttpURLConnection conn = null;
            try {
                /* append query string for GET requests */
                if (method == Method.GET) {
                    if (!params.urlParams.isEmpty()) {
                        url += ('?' + params.getParamString());
                    }
                }

                /* setup headers for POST requests */
                if (method == Method.POST) {
                    headers.addHeader("Accept-Charset", requestOptions.encoding);
                    if (params.hasMultipartParams()) {
                        final SimpleMultipart multipart = params.getMultipart();
                        headers.addHeader("Content-Type", multipart.getContentType());
                    } else {
                        headers.addHeader("Content-Type",
                                "application/x-www-form-urlencoded;charset=" + requestOptions.encoding);
                    }
                }

                if (canceled) {
                    postCancel();
                    return;
                }

                /* open and configure the connection */
                conn = (HttpURLConnection) new URL(url).openConnection();

                postStart();

                if (method == Method.GET) {
                    conn = (HttpURLConnection) new URL(url).openConnection();
                    conn.setRequestMethod("GET");
                } else if (method == Method.POST) {
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setUseCaches(false);
                }
                conn.setAllowUserInteraction(false);
                conn.setReadTimeout(requestOptions.readTimeout);
                conn.setConnectTimeout(requestOptions.connectTimeout);

                /* add headers to the connection */
                for (final Map.Entry<String, List<String>> entry : headers.getHeaders().entrySet()) {
                    for (final String value : entry.getValue()) {
                        conn.addRequestProperty(entry.getKey(), value);
                    }
                }

                if (canceled) {
                    try {
                        conn.disconnect();
                    } catch (final Exception e) {
                    }
                    postCancel();
                    return;
                }

                response.requestProperties = conn.getRequestProperties();

                /* do post */
                if (method == Method.POST) {
                    InputStream is;

                    if (params.hasMultipartParams()) {
                        is = params.getMultipart().getContent();
                    } else {
                        is = new ByteArrayInputStream(params.getParamString().getBytes());
                    }

                    final OutputStream os = conn.getOutputStream();

                    writeStream(os, is);
                } else {
                    conn.connect();
                }

                if (canceled) {
                    try {
                        conn.disconnect();
                    } catch (final Exception e) {
                    }
                    postCancel();
                    return;
                }

                response.contentEncoding = conn.getContentEncoding();
                response.contentLength = conn.getContentLength();
                response.contentType = conn.getContentType();
                response.date = conn.getDate();
                response.expiration = conn.getExpiration();
                response.headerFields = conn.getHeaderFields();
                response.ifModifiedSince = conn.getIfModifiedSince();
                response.lastModified = conn.getLastModified();
                response.responseCode = conn.getResponseCode();
                response.responseMessage = conn.getResponseMessage();

                /* do get */
                if (conn.getResponseCode() < 400) {
                    response.responseBody = readStream(conn.getInputStream());
                    postSuccess();
                } else {
                    response.responseBody = readStream(conn.getErrorStream());
                    response.throwable = new Exception(response.responseMessage);
                    postError();
                }

            } catch (final Exception e) {
                if (retries < requestOptions.maxRetries) {
                    retries++;
                    postRetry();
                    execute();
                } else {
                    response.responseBody = e.getMessage();
                    response.throwable = e;
                    postError();
                }
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }
        }

        private String readStream(final InputStream is) throws IOException {
            final BufferedInputStream bis = new BufferedInputStream(is);
            final ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int read = 0;
            final byte[] buffer = new byte[8192];
            while (true) {
                if (canceled) {
                    break;
                }

                read = bis.read(buffer);
                if (read == -1) {
                    break;
                }
                baf.append(buffer, 0, read);
            }

            try {
                bis.close();
            } catch (final IOException e) {
            }

            try {
                is.close();
            } catch (final IOException e) {
            }

            return new String(baf.toByteArray());
        }

        private void writeStream(final OutputStream os, final InputStream is) throws IOException {
            final BufferedInputStream bis = new BufferedInputStream(is);
            int read = 0;
            final byte[] buffer = new byte[8192];
            while (true) {
                if (canceled) {
                    break;
                }

                read = bis.read(buffer);
                if (read == -1) {
                    break;
                }
                os.write(buffer, 0, read);
            }

            if (!canceled) {
                os.flush();
            }

            try {
                os.close();
            } catch (final IOException e) {
            }

            try {
                bis.close();
            } catch (final IOException e) {
            }

            try {
                is.close();
            } catch (final IOException e) {
            }
        }

        @Override
        public void handleMessage(final Message msg) {
            if (msg.what == HttpHandler.MESSAGE_CANCEL) {
                canceled = true;
            }
        }

        private void postSuccess() {
            postMessage(HttpHandler.MESSAGE_SUCCESS);
        }

        private void postError() {
            postMessage(HttpHandler.MESSAGE_ERROR);
        }

        private void postCancel() {
            postMessage(HttpHandler.MESSAGE_CANCEL);
        }

        private void postStart() {
            postMessage(HttpHandler.MESSAGE_START);
        }

        private void postRetry() {
            postMessage(HttpHandler.MESSAGE_RETRY);
        }

        private void postMessage(final int what) {
            final Message msg = handler.obtainMessage();
            msg.what = what;
            msg.arg1 = requestId;
            msg.obj = response;
            handler.sendMessage(msg);
        }
    }
    ;
    /* Create a new HandlerRunnable and start it */
    final HandlerRunnable hr = new HandlerRunnable(method, url, headers, params, handler);
    requests.put(requestId, new WeakReference<Handler>(hr));
    new Thread(hr).start();

    /* Return with the request id */
    return requestId;
}

From source file:com.google.blockly.model.BlockFactory.java

/**
 * Create a new {@link Field} instance from JSON.  If the type is not recognized
 * null will be returned. If the JSON is invalid or there is an error reading the data a
 * {@link RuntimeException} will be thrown.
 *
 * @param blockType The type id of the block within this field will be contained.
 * @param json The JSON to generate the Field from.
 *
 * @return A Field of the appropriate type.
 *
 * @throws RuntimeException//from ww  w .  j  a  v a 2  s .c  o m
 */
public Field loadFieldFromJson(String blockType, JSONObject json) throws BlockLoadingException {
    String type = null;
    try {
        type = json.getString("type");
    } catch (JSONException e) {
        throw new BlockLoadingException("Error getting the field type.", e);
    }

    // If new fields are added here FIELD_TYPES should also be updated.
    Field field = null;
    switch (type) {
    case Field.TYPE_LABEL_STRING:
        field = FieldLabel.fromJson(json);
        break;
    case Field.TYPE_INPUT_STRING:
        field = FieldInput.fromJson(json);
        break;
    case Field.TYPE_ANGLE_STRING:
        field = FieldAngle.fromJson(json);
        break;
    case Field.TYPE_CHECKBOX_STRING:
        field = FieldCheckbox.fromJson(json);
        break;
    case Field.TYPE_COLOR_STRING:
        field = FieldColor.fromJson(json);
        break;
    case Field.TYPE_DATE_STRING:
        field = FieldDate.fromJson(json);
        break;
    case Field.TYPE_VARIABLE_STRING:
        field = FieldVariable.fromJson(json);
        break;
    case Field.TYPE_DROPDOWN_STRING:
        field = FieldDropdown.fromJson(json);
        String fieldName = field.getName();
        if (!TextUtils.isEmpty(blockType) && !TextUtils.isEmpty(fieldName)) {
            // While block type names should be unique, if there is a collision, the latest
            // block and its option type wins.
            mDropdownOptions.put(new BlockTypeFieldName(blockType, fieldName),
                    new WeakReference<>(((FieldDropdown) field).getOptions()));
        }
        break;
    case Field.TYPE_IMAGE_STRING:
        field = FieldImage.fromJson(json);
        break;
    case Field.TYPE_NUMBER_STRING:
        field = FieldNumber.fromJson(json);
        break;
    default:
        Log.w(TAG, "Unknown field type.");
        break;
    }
    return field;
}

From source file:com.rapidminer.gui.new_plotter.configuration.PlotConfiguration.java

/**
 * This functions registers a {@link PlotConfigurationListener} as prioritized. This means that
 * is is being informed at first when new events are being processed. At the moment only one
 * prioritized listener may be registered at the same time. Check if you may register via
 * getPrioritizedListenerCount()./*from  ww  w . jav a 2s . c o  m*/
 */
public void addPlotConfigurationListener(PlotConfigurationListener l, boolean prioritized) {
    if (prioritized) {
        synchronized (prioritizedListeners) {
            prioritizedListeners.add(new WeakReference<PlotConfigurationListener>(l));
        }
    } else {
        synchronized (defaultListeners) {
            defaultListeners.add(new WeakReference<PlotConfigurationListener>(l));
        }
    }
}

From source file:android.support.v7ox.widget.AppCompatDrawableManager.java

private boolean addCachedDelegateDrawable(@NonNull final Context context, final long key,
        @NonNull final Drawable drawable) {
    final ConstantState cs = drawable.getConstantState();
    if (cs != null) {
        synchronized (mDelegateDrawableCacheLock) {
            LongSparseArray<WeakReference<ConstantState>> cache = mDelegateDrawableCaches.get(context);
            if (cache == null) {
                cache = new LongSparseArray<>();
                mDelegateDrawableCaches.put(context, cache);
            }/*from w w w. j a  va2 s .co m*/
            cache.put(key, new WeakReference<ConstantState>(cs));
        }
        return true;
    }
    return false;
}

From source file:com.baidu.asynchttpclient.AsyncHttpClient.java

/**
 * Perform a HTTP POST request and track the Android Context which initiated the request.
 * /* w  ww .jav  a 2 s  . co  m*/
 * @param context the Android Context which initiated the request.
 * @param url the URL to send the request to.
 * @param entity a raw {@link HttpEntity} to send with the request, for example, use this to send string/json/xml
 *            payloads to a server by passing a {@link org.apache.http.entity.StringEntity}.
 * @param contentType the content type of the payload you are sending, for example application/json if sending a
 *            json payload.
 * @param responseHandler the response handler instance that should handle the response.
 */
public WeakReference<Future<?>> post(Context context, String url, HttpEntity entity, String contentType,
        AsyncHttpResponseHandler responseHandler) {
    return new WeakReference<Future<?>>(sendRequest(httpClient, httpContext,
            addEntityToRequestBase(new HttpPost(url), entity), contentType, responseHandler, context));
}

From source file:android.support.v7.widget.AppCompatDrawableManager.java

private boolean addDrawableToCache(@NonNull final Context context, final long key,
        @NonNull final Drawable drawable) {
    final ConstantState cs = drawable.getConstantState();
    if (cs != null) {
        synchronized (mDrawableCacheLock) {
            LongSparseArray<WeakReference<ConstantState>> cache = mDrawableCaches.get(context);
            if (cache == null) {
                cache = new LongSparseArray<>();
                mDrawableCaches.put(context, cache);
            }/*w  ww .  jav a 2s . c o m*/
            cache.put(key, new WeakReference<ConstantState>(cs));
        }
        return true;
    }
    return false;
}

From source file:com.gh.bmd.jrt.android.v4.core.LoaderInvocation.java

@Override
@SuppressWarnings("unchecked")
@SuppressFBWarnings(value = "BC_UNCONFIRMED_CAST_OF_RETURN_VALUE", justification = "class comparison with == is done")
public void onCall(@Nonnull final List<? extends INPUT> inputs, @Nonnull final ResultChannel<OUTPUT> result) {

    final Logger logger = mLogger;
    final Object context = mContext.get();

    if (context == null) {

        logger.dbg("avoiding running invocation since context is null");
        return;//from  w  w  w . ja  v  a2s  . c  om
    }

    final Context loaderContext;
    final LoaderManager loaderManager;

    if (context instanceof FragmentActivity) {

        final FragmentActivity activity = (FragmentActivity) context;
        loaderContext = activity.getApplicationContext();
        loaderManager = activity.getSupportLoaderManager();
        logger.dbg("running invocation bound to activity: %s", activity);

    } else if (context instanceof Fragment) {

        final Fragment fragment = (Fragment) context;
        loaderContext = fragment.getActivity().getApplicationContext();
        loaderManager = fragment.getLoaderManager();
        logger.dbg("running invocation bound to fragment: %s", fragment);

    } else {

        throw new IllegalArgumentException("invalid context type: " + context.getClass().getCanonicalName());
    }

    int loaderId = mLoaderId;

    if (loaderId == ContextRoutineBuilder.AUTO) {

        loaderId = mConstructor.getDeclaringClass().hashCode();

        for (final Object arg : mArgs) {

            loaderId = 31 * loaderId + recursiveHashCode(arg);
        }

        loaderId = 31 * loaderId + inputs.hashCode();
        logger.dbg("generating invocation ID: %d", loaderId);
    }

    final Loader<InvocationResult<OUTPUT>> loader = loaderManager.getLoader(loaderId);
    final boolean isClash = isClash(loader, loaderId, inputs);
    final WeakIdentityHashMap<Object, SparseArray<WeakReference<RoutineLoaderCallbacks<?>>>> callbackMap = sCallbackMap;
    SparseArray<WeakReference<RoutineLoaderCallbacks<?>>> callbackArray = callbackMap.get(context);

    if (callbackArray == null) {

        callbackArray = new SparseArray<WeakReference<RoutineLoaderCallbacks<?>>>();
        callbackMap.put(context, callbackArray);
    }

    final WeakReference<RoutineLoaderCallbacks<?>> callbackReference = callbackArray.get(loaderId);
    RoutineLoaderCallbacks<OUTPUT> callbacks = (callbackReference != null)
            ? (RoutineLoaderCallbacks<OUTPUT>) callbackReference.get()
            : null;

    if ((callbacks == null) || (loader == null) || isClash) {

        final RoutineLoader<INPUT, OUTPUT> routineLoader;

        if (!isClash && (loader != null) && (loader.getClass() == RoutineLoader.class)) {

            routineLoader = (RoutineLoader<INPUT, OUTPUT>) loader;

        } else {

            routineLoader = null;
        }

        final RoutineLoaderCallbacks<OUTPUT> newCallbacks = createCallbacks(loaderContext, loaderManager,
                routineLoader, inputs, loaderId);

        if (callbacks != null) {

            logger.dbg("resetting existing callbacks [%d]", loaderId);
            callbacks.reset();
        }

        callbackArray.put(loaderId, new WeakReference<RoutineLoaderCallbacks<?>>(newCallbacks));
        callbacks = newCallbacks;
    }

    logger.dbg("setting result cache type [%d]: %s", loaderId, mCacheStrategyType);
    callbacks.setCacheStrategy(mCacheStrategyType);

    final OutputChannel<OUTPUT> outputChannel = callbacks.newChannel();

    if (isClash) {

        logger.dbg("restarting loader [%d]", loaderId);
        loaderManager.restartLoader(loaderId, Bundle.EMPTY, callbacks);

    } else {

        logger.dbg("initializing loader [%d]", loaderId);
        loaderManager.initLoader(loaderId, Bundle.EMPTY, callbacks);
    }

    result.pass(outputChannel);
}

From source file:uk.ac.horizon.ug.exploding.client.BackgroundThread.java

/** add listener */
public static void addClientStateListener(ClientStateListener listener, Context context, int flags,
        Set<String> types) {
    checkThread(context);/*from  w  ww . j  a v  a 2s .  c  o m*/
    ListenerInfo li = new ListenerInfo();
    li.listener = new WeakReference<ClientStateListener>(listener);
    li.flags = flags;
    li.types = types;
    listeners.add(li);
}