org.chromium.net.NetworkChangeNotifier Java Examples

The following examples show how to use org.chromium.net.NetworkChangeNotifier. 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 File: AccountManagerHelper.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 #2
Source File: AccountManagerHelper.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 #3
Source File: WebappActivity.java    From delion with 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 #4
Source File: DeviceConditions.java    From 365browser with 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 #5
Source File: ConnectivityTask.java    From AndroidChromium with 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 File: ConnectivityTask.java    From 365browser with 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 #7
Source File: WebappActivity.java    From AndroidChromium with 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 #8
Source File: ConnectivityTask.java    From delion with 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 #9
Source File: ContextualSearchTabHelper.java    From AndroidChromium with 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 #10
Source File: AccountManagerHelper.java    From 365browser with 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 #11
Source File: MinidumpUploadRetry.java    From 365browser with 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 #12
Source File: WebappActivity.java    From 365browser with 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 #13
Source File: ContextualSearchTabHelper.java    From 365browser with 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 #14
Source File: ContextualSearchTabHelper.java    From 365browser with 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 #15
Source File: ChromeBrowserInitializer.java    From 365browser with 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 #16
Source File: MinidumpUploadRetry.java    From AndroidChromium with 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 #17
Source File: ChromeBrowserInitializer.java    From delion with 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 #18
Source File: UmaSessionStats.java    From delion with 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 #19
Source File: UmaSessionStats.java    From delion with 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 #20
Source File: ChromeBrowserInitializer.java    From AndroidChromium with 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 #21
Source File: MinidumpUploadRetry.java    From delion with 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 #22
Source File: OfflinePageUtils.java    From AndroidChromium with 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 #23
Source File: OfflinePageUtils.java    From delion with 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 #24
Source File: OfflinePageUtils.java    From 365browser with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isConnected() {
    return NetworkChangeNotifier.isOnline();
}
 
Example #25
Source File: OfflinePageTabObserver.java    From delion with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
void startObservingNetworkChanges() {
    NetworkChangeNotifier.addConnectionTypeObserver(this);
}
 
Example #26
Source File: MinidumpUploadRetry.java    From 365browser with Apache License 2.0 4 votes vote down vote up
private MinidumpUploadRetry(
        Context context, CrashReportingPermissionManager permissionManager) {
    this.mContext = context;
    this.mPermissionManager = permissionManager;
    NetworkChangeNotifier.addConnectionTypeObserver(this);
}
 
Example #27
Source File: OfflinePageTabObserver.java    From delion with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
void stopObservingNetworkChanges() {
    NetworkChangeNotifier.removeConnectionTypeObserver(this);
}
 
Example #28
Source File: OfflinePageUtils.java    From delion with 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 #29
Source File: ContextualSearchManager.java    From 365browser with Apache License 2.0 4 votes vote down vote up
/** Handles this {@link ContextualSearchNetworkCommunicator} vector when not under test. */
@Override
public boolean isOnline() {
    return NetworkChangeNotifier.isOnline();
}
 
Example #30
Source File: MinidumpUploadRetry.java    From delion with Apache License 2.0 4 votes vote down vote up
private MinidumpUploadRetry(Context context) {
    this.mContext = context;
    NetworkChangeNotifier.addConnectionTypeObserver(this);
}