Java Code Examples for org.chromium.net.NetworkChangeNotifier

The following examples show how to use org.chromium.net.NetworkChangeNotifier. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: delion   Source File: ConnectivityTask.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the connectivity that has been collected up until this call. This method fills in
 * {@link ConnectivityCheckResult#UNKNOWN} for results that have not been retrieved yet.
 *
 * @return the {@link FeedbackData}.
 */
public FeedbackData get() {
    ThreadUtils.assertOnUiThread();
    Map<Type, Integer> result = new EnumMap<Type, Integer>(Type.class);
    // Ensure the map is filled with a result for all {@link Type}s.
    for (Type type : Type.values()) {
        if (mResult.containsKey(type)) {
            result.put(type, mResult.get(type));
        } else {
            result.put(type, ConnectivityCheckResult.UNKNOWN);
        }
    }
    long elapsedTimeMs = SystemClock.elapsedRealtime() - mStartCheckTimeMs;
    int connectionType = NetworkChangeNotifier.getInstance().getCurrentConnectionType();
    return new FeedbackData(result, mTimeoutMs, elapsedTimeMs, connectionType);
}
 
Example 2
Source Project: delion   Source File: WebappActivity.java    License: Apache License 2.0 6 votes vote down vote up
private void initializeUI(Bundle savedInstanceState) {
    // We do not load URL when restoring from saved instance states.
    if (savedInstanceState == null && mWebappInfo.isInitialized()) {
        if (TextUtils.isEmpty(getActivityTab().getUrl())) {
            getActivityTab().loadUrl(new LoadUrlParams(
                    mWebappInfo.uri().toString(), PageTransition.AUTO_TOPLEVEL));
        }
    } else {
        if (NetworkChangeNotifier.isOnline()) getActivityTab().reloadIgnoringCache();
    }

    getActivityTab().addObserver(createTabObserver());
    getActivityTab().getTabWebContentsDelegateAndroid().setDisplayMode(
            WebDisplayMode.Standalone);
    // TODO(dominickn): send the web app into fullscreen if mDisplayMode is
    // WebDisplayMode.Fullscreen. See crbug.com/581522
}
 
Example 3
Source Project: AndroidChromium   Source File: ConnectivityTask.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the connectivity that has been collected up until this call. This method fills in
 * {@link ConnectivityCheckResult#UNKNOWN} for results that have not been retrieved yet.
 *
 * @return the {@link FeedbackData}.
 */
public FeedbackData get() {
    ThreadUtils.assertOnUiThread();
    Map<Type, Integer> result = new EnumMap<Type, Integer>(Type.class);
    // Ensure the map is filled with a result for all {@link Type}s.
    for (Type type : Type.values()) {
        if (mResult.containsKey(type)) {
            result.put(type, mResult.get(type));
        } else {
            result.put(type, ConnectivityCheckResult.UNKNOWN);
        }
    }
    long elapsedTimeMs = SystemClock.elapsedRealtime() - mStartCheckTimeMs;
    int connectionType = NetworkChangeNotifier.getInstance().getCurrentConnectionType();
    return new FeedbackData(result, mTimeoutMs, elapsedTimeMs, connectionType);
}
 
Example 4
Source Project: AndroidChromium   Source File: WebappActivity.java    License: Apache License 2.0 6 votes vote down vote up
private void initializeUI(Bundle savedInstanceState) {
    // We do not load URL when restoring from saved instance states.
    if (savedInstanceState == null && mWebappInfo.isInitialized()) {
        if (TextUtils.isEmpty(getActivityTab().getUrl())) {
            getActivityTab().loadUrl(new LoadUrlParams(
                    mWebappInfo.uri().toString(), PageTransition.AUTO_TOPLEVEL));
        }
    } else {
        if (NetworkChangeNotifier.isOnline()) getActivityTab().reloadIgnoringCache();
    }

    getActivityTab().addObserver(createTabObserver());
    getActivityTab().getTabWebContentsDelegateAndroid().setDisplayMode(
            WebDisplayMode.Standalone);
    // TODO(dominickn): send the web app into fullscreen if mDisplayMode is
    // WebDisplayMode.Fullscreen. See crbug.com/581522
}
 
Example 5
Source Project: 365browser   Source File: ConnectivityTask.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the connectivity that has been collected up until this call. This method fills in
 * {@link ConnectivityCheckResult#UNKNOWN} for results that have not been retrieved yet.
 *
 * @return the {@link FeedbackData}.
 */
public FeedbackData get() {
    ThreadUtils.assertOnUiThread();
    Map<Type, Integer> result = new EnumMap<Type, Integer>(Type.class);
    // Ensure the map is filled with a result for all {@link Type}s.
    for (Type type : Type.values()) {
        if (mResult.containsKey(type)) {
            result.put(type, mResult.get(type));
        } else {
            result.put(type, ConnectivityCheckResult.UNKNOWN);
        }
    }
    long elapsedTimeMs = SystemClock.elapsedRealtime() - mStartCheckTimeMs;
    int connectionType = NetworkChangeNotifier.getInstance().getCurrentConnectionType();
    return new FeedbackData(result, mTimeoutMs, elapsedTimeMs, connectionType);
}
 
Example 6
Source Project: 365browser   Source File: DeviceConditions.java    License: Apache License 2.0 6 votes vote down vote up
private static int getConnectionType(Context context) {
    // Get the connection type from chromium's internal object.
    int connectionType = NetworkChangeNotifier.getInstance().getCurrentConnectionType();

    // Sometimes the NetworkConnectionNotifier lags the actual connection type, especially when
    // the GCM NM wakes us from doze state.  If we are really connected, report the connection
    // type from android.
    if (connectionType == ConnectionType.CONNECTION_NONE) {
        // Get the connection type from android in case chromium's type is not yet set.
        ConnectivityManager cm =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
        if (isConnected) {
            connectionType = convertAndroidNetworkTypeToConnectionType(activeNetwork.getType());
        }
    }
    return connectionType;
}
 
Example 7
private void onGotAuthTokenResult(Account account, String authTokenType, String authToken,
        GetAuthTokenCallback callback, AtomicInteger numTries, AtomicBoolean errorEncountered,
        ConnectionRetry retry) {
    if (authToken != null || !errorEncountered.get() ||
            numTries.incrementAndGet() == MAX_TRIES ||
            !NetworkChangeNotifier.isInitialized()) {
        callback.tokenAvailable(authToken);
        return;
    }
    if (retry == null) {
        ConnectionRetry newRetry = new ConnectionRetry(account, authTokenType, callback,
                numTries, errorEncountered);
        NetworkChangeNotifier.addConnectionTypeObserver(newRetry);
    } else {
        NetworkChangeNotifier.addConnectionTypeObserver(retry);
    }
}
 
Example 8
private void onGotAuthTokenResult(Account account, String authTokenType, String authToken,
        GetAuthTokenCallback callback, AtomicInteger numTries, AtomicBoolean errorEncountered,
        ConnectionRetry retry) {
    if (authToken != null || !errorEncountered.get() ||
            numTries.incrementAndGet() == MAX_TRIES ||
            !NetworkChangeNotifier.isInitialized()) {
        callback.tokenAvailable(authToken);
        return;
    }
    if (retry == null) {
        ConnectionRetry newRetry = new ConnectionRetry(account, authTokenType, callback,
                numTries, errorEncountered);
        NetworkChangeNotifier.addConnectionTypeObserver(newRetry);
    } else {
        NetworkChangeNotifier.addConnectionTypeObserver(retry);
    }
}
 
Example 9
Source Project: delion   Source File: ChromeBrowserInitializer.java    License: Apache License 2.0 5 votes vote down vote up
public static void initNetworkChangeNotifier(Context context) {
    ThreadUtils.assertOnUiThread();
    TraceEvent.begin("NetworkChangeNotifier.init");
    // Enable auto-detection of network connectivity state changes.
    NetworkChangeNotifier.init(context);
    NetworkChangeNotifier.setAutoDetectConnectivityState(true);
    TraceEvent.end("NetworkChangeNotifier.init");
}
 
Example 10
Source Project: delion   Source File: UmaSessionStats.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Starts a new session for logging.
 * @param tabModelSelector A TabModelSelector instance for recording tab counts on page loads.
 * If null, UmaSessionStats does not record page loads and tab counts.
 */
public void startNewSession(TabModelSelector tabModelSelector) {
    ensureNativeInitialized();

    mTabModelSelector = tabModelSelector;
    if (mTabModelSelector != null) {
        mComponentCallbacks = new ComponentCallbacks() {
            @Override
            public void onLowMemory() {
                // Not required
            }

            @Override
            public void onConfigurationChanged(Configuration newConfig) {
                mKeyboardConnected = newConfig.keyboard != Configuration.KEYBOARD_NOKEYS;
            }
        };
        mContext.registerComponentCallbacks(mComponentCallbacks);
        mKeyboardConnected = mContext.getResources().getConfiguration()
                .keyboard != Configuration.KEYBOARD_NOKEYS;
        mTabModelSelectorTabObserver = new TabModelSelectorTabObserver(mTabModelSelector) {
            @Override
            public void onPageLoadFinished(Tab tab) {
                recordPageLoadStats(tab);
            }
        };
    }

    nativeUmaResumeSession(sNativeUmaSessionStats);
    NetworkChangeNotifier.addConnectionTypeObserver(this);
    updatePreferences();
    updateMetricsServiceState();
}
 
Example 11
Source Project: delion   Source File: UmaSessionStats.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Logs the current session.
 */
public void logAndEndSession() {
    if (mTabModelSelector != null) {
        mContext.unregisterComponentCallbacks(mComponentCallbacks);
        mTabModelSelectorTabObserver.destroy();
        mTabModelSelector = null;
    }

    nativeUmaEndSession(sNativeUmaSessionStats);
    NetworkChangeNotifier.removeConnectionTypeObserver(this);
    ContextUtils.getAppSharedPreferences()
            .edit()
            .putLong(LAST_USED_TIME_PREF, System.currentTimeMillis())
            .apply();
}
 
Example 12
Source Project: delion   Source File: OfflinePageUtils.java    License: Apache License 2.0 5 votes vote down vote up
/** Returns the current device conditions. May be overridden for testing. */
protected DeviceConditions getDeviceConditionsImpl(Context context) {
    IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    // Note this is a sticky intent, so we aren't really registering a receiver, just getting
    // the sticky intent.  That means that we don't need to unregister the filter later.
    Intent batteryStatus = context.registerReceiver(null, filter);
    if (batteryStatus == null) return null;

    return new DeviceConditions(isPowerConnected(batteryStatus),
            batteryPercentage(batteryStatus),
            NetworkChangeNotifier.getInstance().getCurrentConnectionType());
}
 
Example 13
Source Project: delion   Source File: MinidumpUploadRetry.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
@Override
public void onConnectionTypeChanged(int connectionType) {
    // Look for "favorable" connections. Note that we never
    // know what the user's crash upload preference is until
    // the time when we are actually uploading.
    if (connectionType == ConnectionType.CONNECTION_NONE) {
        return;
    }
    MinidumpUploadService.tryUploadAllCrashDumps(mContext);
    NetworkChangeNotifier.removeConnectionTypeObserver(this);
    sSingleton = null;
}
 
Example 14
Source Project: AndroidChromium   Source File: ChromeBrowserInitializer.java    License: Apache License 2.0 5 votes vote down vote up
public static void initNetworkChangeNotifier(Context context) {
    ThreadUtils.assertOnUiThread();
    TraceEvent.begin("NetworkChangeNotifier.init");
    // Enable auto-detection of network connectivity state changes.
    NetworkChangeNotifier.init(context);
    NetworkChangeNotifier.setAutoDetectConnectivityState(true);
    TraceEvent.end("NetworkChangeNotifier.init");
}
 
Example 15
Source Project: AndroidChromium   Source File: OfflinePageUtils.java    License: Apache License 2.0 5 votes vote down vote up
/** Returns the current device conditions. May be overridden for testing. */
protected DeviceConditions getDeviceConditionsImpl(Context context) {
    IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    // Note this is a sticky intent, so we aren't really registering a receiver, just getting
    // the sticky intent.  That means that we don't need to unregister the filter later.
    Intent batteryStatus = context.registerReceiver(null, filter);
    if (batteryStatus == null) return null;

    // Get the connection type from chromium's internal object.
    int connectionType = NetworkChangeNotifier.getInstance().getCurrentConnectionType();

    // Sometimes the NetworkConnectionNotifier lags the actual connection type, especially when
    // the GCM NM wakes us from doze state.  If we are really connected, report the connection
    // type from android.
    if (connectionType == ConnectionType.CONNECTION_NONE) {
        // Get the connection type from android in case chromium's type is not yet set.
        ConnectivityManager cm =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
        if (isConnected) {
            connectionType = convertAndroidNetworkTypeToConnectionType(activeNetwork.getType());
        }
    }

    return new DeviceConditions(
            isPowerConnected(batteryStatus), batteryPercentage(batteryStatus), connectionType);
}
 
Example 16
Source Project: AndroidChromium   Source File: ContextualSearchTabHelper.java    License: Apache License 2.0 5 votes vote down vote up
private ContextualSearchTabHelper(Tab tab) {
    mTab = tab;
    tab.addObserver(this);
    // Connect to a network, unless under test.
    if (NetworkChangeNotifier.isInitialized()) {
        NetworkChangeNotifier.addConnectionTypeObserver(this);
    }
}
 
Example 17
Source Project: AndroidChromium   Source File: MinidumpUploadRetry.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
@Override
public void onConnectionTypeChanged(int connectionType) {
    // Look for "favorable" connections. Note that we never
    // know what the user's crash upload preference is until
    // the time when we are actually uploading.
    if (connectionType == ConnectionType.CONNECTION_NONE) {
        return;
    }
    MinidumpUploadService.tryUploadAllCrashDumps(mContext);
    NetworkChangeNotifier.removeConnectionTypeObserver(this);
    sSingleton = null;
}
 
Example 18
Source Project: 365browser   Source File: ChromeBrowserInitializer.java    License: Apache License 2.0 5 votes vote down vote up
public static void initNetworkChangeNotifier(Context context) {
    ThreadUtils.assertOnUiThread();
    TraceEvent.begin("NetworkChangeNotifier.init");
    // Enable auto-detection of network connectivity state changes.
    NetworkChangeNotifier.init();
    NetworkChangeNotifier.setAutoDetectConnectivityState(true);
    TraceEvent.end("NetworkChangeNotifier.init");
}
 
Example 19
Source Project: 365browser   Source File: ContextualSearchTabHelper.java    License: Apache License 2.0 5 votes vote down vote up
private ContextualSearchTabHelper(Tab tab) {
    mTab = tab;
    tab.addObserver(this);
    // Connect to a network, unless under test.
    if (NetworkChangeNotifier.isInitialized()) {
        NetworkChangeNotifier.addConnectionTypeObserver(this);
    }
}
 
Example 20
Source Project: 365browser   Source File: ContextualSearchTabHelper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onDestroyed(Tab tab) {
    if (mNativeHelper != 0) {
        nativeDestroy(mNativeHelper);
        mNativeHelper = 0;
    }
    if (mTemplateUrlObserver != null) {
        TemplateUrlService.getInstance().removeObserver(mTemplateUrlObserver);
    }
    if (NetworkChangeNotifier.isInitialized()) {
        NetworkChangeNotifier.removeConnectionTypeObserver(this);
    }
    removeContextualSearchHooks(mBaseContentViewCore);
    mBaseContentViewCore = null;
}
 
Example 21
Source Project: 365browser   Source File: WebappActivity.java    License: Apache License 2.0 5 votes vote down vote up
protected void initializeUI(Bundle savedInstanceState) {
    // We do not load URL when restoring from saved instance states.
    if (savedInstanceState == null && mWebappInfo.isInitialized()) {
        if (TextUtils.isEmpty(getActivityTab().getUrl())) {
            getActivityTab().loadUrl(new LoadUrlParams(
                    mWebappInfo.uri().toString(), PageTransition.AUTO_TOPLEVEL));
        }
    } else {
        if (NetworkChangeNotifier.isOnline()) getActivityTab().reloadIgnoringCache();
    }

    getActivityTab().addObserver(createTabObserver());
    getActivityTab().getTabWebContentsDelegateAndroid().setDisplayMode(
            mWebappInfo.displayMode());
}
 
Example 22
Source Project: 365browser   Source File: MinidumpUploadRetry.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
@Override
public void onConnectionTypeChanged(int connectionType) {
    // Early-out if not connected at all - to avoid checking the current network state.
    if (connectionType == ConnectionType.CONNECTION_NONE) {
        return;
    }
    if (!mPermissionManager.isNetworkAvailableForCrashUploads()) {
        return;
    }
    MinidumpUploadService.tryUploadAllCrashDumps();
    NetworkChangeNotifier.removeConnectionTypeObserver(this);
    sSingleton = null;
}
 
Example 23
Source Project: 365browser   Source File: AccountManagerHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tries running the {@link AuthTask} in the background. This object is never registered
 * as a {@link ConnectionTypeObserver} when this method is called.
 */
private void attempt() {
    // Clear any transient error.
    mIsTransientError.set(false);
    new AsyncTask<Void, Void, T>() {
        @Override
        public T doInBackground(Void... params) {
            try {
                return mAuthTask.run();
            } catch (AuthException ex) {
                Log.w(TAG, "Failed to perform auth task", ex);
                mIsTransientError.set(ex.isTransientError());
            }
            return null;
        }
        @Override
        public void onPostExecute(T result) {
            if (result != null) {
                mAuthTask.onSuccess(result);
            } else if (!mIsTransientError.get() || mNumTries.incrementAndGet() >= MAX_TRIES
                    || !NetworkChangeNotifier.isInitialized()) {
                // Permanent error, ran out of tries, or we can't listen for network
                // change events; give up.
                mAuthTask.onFailure(mIsTransientError.get());
            } else {
                // Transient error with tries left; register for another attempt.
                NetworkChangeNotifier.addConnectionTypeObserver(ConnectionRetry.this);
            }
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
 
Example 24
Source Project: delion   Source File: OfflinePageTabObserver.java    License: Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
void startObservingNetworkChanges() {
    NetworkChangeNotifier.addConnectionTypeObserver(this);
}
 
Example 25
Source Project: delion   Source File: OfflinePageTabObserver.java    License: Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
void stopObservingNetworkChanges() {
    NetworkChangeNotifier.removeConnectionTypeObserver(this);
}
 
Example 26
Source Project: delion   Source File: OfflinePageUtils.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Returns true if the network is connected.
 */
public static boolean isConnected() {
    return NetworkChangeNotifier.isOnline();
}
 
Example 27
Source Project: delion   Source File: MinidumpUploadRetry.java    License: Apache License 2.0 4 votes vote down vote up
private MinidumpUploadRetry(Context context) {
    this.mContext = context;
    NetworkChangeNotifier.addConnectionTypeObserver(this);
}
 
Example 28
Source Project: AndroidChromium   Source File: OfflinePageTabObserver.java    License: Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
void startObservingNetworkChanges() {
    NetworkChangeNotifier.addConnectionTypeObserver(this);
}
 
Example 29
Source Project: AndroidChromium   Source File: OfflinePageTabObserver.java    License: Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
void stopObservingNetworkChanges() {
    NetworkChangeNotifier.removeConnectionTypeObserver(this);
}
 
Example 30
Source Project: AndroidChromium   Source File: OfflinePageUtils.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Returns true if the network is connected.
 */
public static boolean isConnected() {
    return NetworkChangeNotifier.isOnline();
}