Example usage for android.net ConnectivityManager CONNECTIVITY_ACTION

List of usage examples for android.net ConnectivityManager CONNECTIVITY_ACTION

Introduction

In this page you can find the example usage for android.net ConnectivityManager CONNECTIVITY_ACTION.

Prototype

String CONNECTIVITY_ACTION

To view the source code for android.net ConnectivityManager CONNECTIVITY_ACTION.

Click Source Link

Document

A change in network connectivity has occurred.

Usage

From source file:com.avalond.ad_blocak.vpn.AdVpnService.java

private void connectivityChanged(Intent intent) {
    if (intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, 0) == ConnectivityManager.TYPE_VPN) {
        Log.i(TAG, "Ignoring connectivity changed for our own network");
        return;//from w  w w .  j  a  va  2s .  c o m
    }

    if (!ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
        Log.e(TAG, "Got bad intent on connectivity changed " + intent.getAction());
    }
    if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) {
        Log.i(TAG, "Connectivity changed to no connectivity, wait for a network");
        waitForNetVpn();
    } else {
        Log.i(TAG, "Network changed, try to reconnect");
        reconnect();
    }
}

From source file:com.esminis.server.library.activity.main.MainPresenterImpl.java

private void showInstallFinished(Context context) {
    if (view == null) {
        return;/*from ww  w .  jav a  2s . c om*/
    }
    if (installError != null) {
        view.setMessage(true, false, null,
                context.getString(R.string.server_installation_failed, installError.getMessage()));
        return;
    }
    view.showMainContent();
    view.setDocumentRoot(getRootDirectory(activity));
    view.setPort(getPort(activity), true);
    view.setInstallPackages(installPackageManager.getInstalled(), installPackageManager.getNewest());
    receiverManager.add(context, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION),
            new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    resetNetwork();
                }
            });
    receiverManager.add(context, new IntentFilter(MainActivity.getIntentActionServerStatus(context)),
            new BroadcastReceiver() {

                @Override
                public void onReceive(Context context, Intent intent) {
                    if (view != null
                            && MainActivity.getIntentActionServerStatus(context).equals(intent.getAction())) {
                        Bundle extras = intent.getExtras();
                        if (extras != null && extras.containsKey("errorLine")) {
                            resetLog();
                        } else {
                            if (extras != null && extras.getBoolean("running")) {
                                view.showButton(MainView.BUTTON_STOP);
                                view.setStatusLabel(Html.fromHtml(serverControl.getServerRunningLabel(activity,
                                        extras.getString("address"))));
                            } else {
                                view.showButton(MainView.BUTTON_START);
                                view.setStatusLabel(activity.getString(R.string.server_stopped));
                            }
                        }
                    }
                }

            });
    resetNetwork();
    serverStatus();
}

From source file:org.adblockplus.android.ProxyService.java

@SuppressLint("NewApi")
@Override//from ww w.  j a  v  a  2  s .co  m
public void onCreate() {
    super.onCreate();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
        // Proxy is running in separate thread, it's just some resolution request during initialization.
        // Not worth spawning a separate thread for this.
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
        StrictMode.setThreadPolicy(policy);
    }

    // Get port for local proxy
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    Resources resources = getResources();

    // Try to read user proxy settings
    String proxyHost = null;
    String proxyPort = null;
    String proxyExcl = null;
    String proxyUser = null;
    String proxyPass = null;

    if (NATIVE_PROXY_SUPPORTED) {
        // Read system settings
        proxyHost = System.getProperty("http.proxyHost");
        proxyPort = System.getProperty("http.proxyPort");
        proxyExcl = System.getProperty("http.nonProxyHosts");

        Log.d(TAG, "PRX: " + proxyHost + ":" + proxyPort + "(" + proxyExcl + ")");
        // not used but left for future reference
        String[] px = ProxySettings.getUserProxy(getApplicationContext());
        if (px != null)
            Log.d(TAG, "PRX: " + px[0] + ":" + px[1] + "(" + px[2] + ")");
    } else {
        // Read application settings
        proxyHost = prefs.getString(getString(R.string.pref_proxyhost), null);
        proxyPort = prefs.getString(getString(R.string.pref_proxyport), null);
        proxyUser = prefs.getString(getString(R.string.pref_proxyuser), null);
        proxyPass = prefs.getString(getString(R.string.pref_proxypass), null);
    }

    // Check for root privileges and try to install transparent proxy
    if (RootTools.isAccessGiven()) {
        try {
            initIptables();

            StringBuffer cmd = new StringBuffer();
            int uid = getPackageManager().getPackageInfo(getPackageName(), 0).applicationInfo.uid;
            cmd.append(iptables);
            cmd.append(IPTABLES_RETURN.replace("{{UID}}", String.valueOf(uid)));
            String rules = cmd.toString();
            RootTools.sendShell(rules, DEFAULT_TIMEOUT);
            transparent = true;
        } catch (FileNotFoundException e) {
            // ignore - this is "normal" case
        } catch (NameNotFoundException e) {
            Log.e(TAG, "Failed to initialize iptables", e);
        } catch (IOException e) {
            Log.e(TAG, "Failed to initialize iptables", e);
        } catch (RootToolsException e) {
            Log.e(TAG, "Failed to initialize iptables", e);
        } catch (TimeoutException e) {
            Log.e(TAG, "Failed to initialize iptables", e);
        }
    }

    if (!transparent) {
        // Try to set native proxy
        nativeProxyAutoConfigured = ProxySettings.setConnectionProxy(getApplicationContext(), LOCALHOST, port,
                "");

        if (NATIVE_PROXY_SUPPORTED) {
            registerReceiver(connectionReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
            registerReceiver(connectionReceiver, new IntentFilter(Proxy.PROXY_CHANGE_ACTION));
        }
    }

    // Save current native proxy situation. The service is always started on the first run so
    // we will always have a correct value from the box
    SharedPreferences.Editor editor = prefs.edit();
    editor.putBoolean(getString(R.string.pref_proxyautoconfigured), transparent || nativeProxyAutoConfigured);
    editor.commit();

    registerReceiver(proxyReceiver, new IntentFilter(ProxyService.BROADCAST_PROXY_FAILED));
    registerReceiver(filterReceiver, new IntentFilter(AdblockPlus.BROADCAST_FILTERING_CHANGE));
    registerReceiver(filterReceiver, new IntentFilter(AdblockPlus.BROADCAST_FILTER_MATCHES));

    // Start proxy
    if (proxy == null) {
        // Select available port and bind to it, use previously selected port by default
        portVariants[0] = prefs.getInt(getString(R.string.pref_lastport), -1);
        ServerSocket listen = null;
        String msg = null;
        for (int p : portVariants) {
            if (p < 0)
                continue;
            try {
                listen = new ServerSocket(p, 1024);
                port = p;
                break;
            } catch (IOException e) {
                Log.e(TAG, null, e);
                msg = e.getMessage();
            }
        }
        if (listen == null) {
            sendBroadcast(new Intent(BROADCAST_PROXY_FAILED).putExtra("msg", msg));
            return;
        }

        // Save selected port
        editor.putInt(getString(R.string.pref_lastport), port);
        editor.commit();

        // Initialize proxy
        proxyConfiguration.put("handler", "main");
        proxyConfiguration.put("main.prefix", "");
        proxyConfiguration.put("main.class", "sunlabs.brazil.server.ChainHandler");
        if (transparent) {
            proxyConfiguration.put("main.handlers", "urlmodifier adblock");
            proxyConfiguration.put("urlmodifier.class", "org.adblockplus.brazil.TransparentProxyHandler");
        } else {
            proxyConfiguration.put("main.handlers", "https adblock");
            proxyConfiguration.put("https.class", "org.adblockplus.brazil.SSLConnectionHandler");
        }
        proxyConfiguration.put("adblock.class", "org.adblockplus.brazil.RequestHandler");
        if (logRequests)
            proxyConfiguration.put("adblock.proxylog", "yes");

        configureUserProxy(proxyConfiguration, proxyHost, proxyPort, proxyExcl, proxyUser, proxyPass);

        proxy = new ProxyServer();
        proxy.logLevel = Server.LOG_DIAGNOSTIC;
        proxy.setup(listen, proxyConfiguration.getProperty("handler"), proxyConfiguration);
        proxy.start();
    }

    if (transparent) {
        // Redirect traffic via iptables
        try {
            StringBuffer cmd = new StringBuffer();
            cmd.append(iptables);
            cmd.append(IPTABLES_ADD_HTTP.replace("{{PORT}}", String.valueOf(port)));
            String rules = cmd.toString();
            RootTools.sendShell(rules, DEFAULT_TIMEOUT);
        } catch (FileNotFoundException e) {
            // ignore - this is "normal" case
        } catch (IOException e) {
            Log.e(TAG, "Failed to initialize iptables", e);
        } catch (RootToolsException e) {
            Log.e(TAG, "Failed to initialize iptables", e);
        } catch (TimeoutException e) {
            Log.e(TAG, "Failed to initialize iptables", e);
        }
    }

    prefs.registerOnSharedPreferenceChangeListener(this);

    // Lock service
    hideIcon = prefs.getBoolean(getString(R.string.pref_hideicon), resources.getBoolean(R.bool.def_hideicon));
    startForeground(ONGOING_NOTIFICATION_ID, getNotification());

    // If automatic setting of proxy was blocked, check if user has set it manually
    boolean manual = isManual();
    if (manual && NATIVE_PROXY_SUPPORTED) {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
                Context.CONNECTIVITY_SERVICE);
        updateNoTrafficCheck(connectivityManager);
    }

    sendStateChangedBroadcast();
    Log.i(TAG, "Service started");
}

From source file:com.scooter1556.sms.android.fragment.HomeFragment.java

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    Log.d(TAG, "onAttach()");

    mediaFragmentListener = (MediaFragmentListener) context;

    // Register connectivity receiver
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    getActivity().registerReceiver(connectivityChangeReceiver, intentFilter);
}

From source file:piuk.blockchain.android.WalletApplication.java

public void connect() {
    if (timer != null) {
        try {//w ww  . java 2  s. c  om
            timer.cancel();

            timer.purge();

            timer = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    final IntentFilter intentFilter = new IntentFilter();

    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);

    registerReceiver(broadcastReceiver, intentFilter);

    if (!WebsocketService.isRunning)
        startService(websocketServiceIntent);
}

From source file:com.misterpereira.android.kiteplayer.ui.MediaBrowserFragment.java

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

    // fetch browsing information to fill the listview:
    MediaBrowser mediaBrowser = mMediaFragmentListener.getMediaBrowser();

    LogHelper.d(TAG, "fragment.onStart, mediaId=", mMediaId, "  onConnected=" + mediaBrowser.isConnected());

    if (mediaBrowser.isConnected()) {
        onConnected();/*from  w  w  w .j  a  va2 s.  co m*/
    }

    // Registers BroadcastReceiver to track network connection changes.
    this.getActivity().registerReceiver(mConnectivityChangeReceiver,
            new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}

From source file:org.span.manager.MainActivity.java

@Override
public void onResume() {
    super.onResume();
    Log.d(TAG, "onResume()"); // DEBUG

    // check if the battery temperature should be displayed
    if (app.prefs.getString("batterytemppref", "fahrenheit").equals("disabled") == false) {
        // create the IntentFilter that will be used to listen
        // to battery status broadcasts
        intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(intentReceiver, intentFilter);
        batteryTemperatureLayout.setVisibility(View.VISIBLE);
    } else {//  w  w  w  . ja va  2  s  .  c  om
        try {
            unregisterReceiver(this.intentReceiver);
        } catch (Exception e) {
            ;
        }
        batteryTemperatureLayout.setVisibility(View.INVISIBLE);
    }

    // Register to receive updates about the device network state
    registerReceiver(intentReceiver, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION));
    registerReceiver(intentReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

    /*
      Window window = getWindow();
      // window.addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD);
      // window.addFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED);
      window.addFlags(LayoutParams.FLAG_TURN_SCREEN_ON);
      window.addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
      */
}

From source file:org.jorge.cmp.service.ChatIntentService.java

private Boolean login(final LoLin1Account acc) {
    ChatServer chatServer;//from w ww  .j av  a  2 s  .com
    chatServer = ChatServer.valueOf(acc.getRealmEnum().name().toUpperCase(Locale.ENGLISH));
    try {
        api = new LoLChat(LoLin1Application.getInstance().getContext(), ConnectivityManager.CONNECTIVITY_ACTION,
                chatServer, Boolean.FALSE);
    } catch (IOException e) {
        Crashlytics.logException(e);
        e.printStackTrace(System.err);
        if (!(e instanceof SSLException)) {
            launchBroadcastLoginFailed();
        }
        return Boolean.FALSE;
    }
    Boolean loginSuccess = Boolean.FALSE;
    try {
        loginSuccess = api.login(acc.getUsername(), acc.getPassword());
    } catch (IOException e) {
        Crashlytics.logException(e);
    }
    if (loginSuccess) {
        api.reloadRoster();
        isConnected = Boolean.TRUE;
        return Boolean.TRUE;
    } else {
        isConnected = Boolean.FALSE;
        return Boolean.FALSE;
    }
}

From source file:dk.microting.softkeyboard.autoupdateapk.AutoUpdateApk.java

private void setupVariables(Context ctx) {
    context = ctx;//from ww w.  j ava2  s.  c  o m

    packageName = context.getPackageName();
    preferences = context.getSharedPreferences(packageName + "_" + TAG, Context.MODE_PRIVATE);
    last_update = preferences.getLong("last_update", 0);
    NOTIFICATION_ID += crc32(packageName);

    ApplicationInfo appinfo = context.getApplicationInfo();
    if (appinfo.icon != 0) {
        appIcon = appinfo.icon;
    } else {
        Log.w(TAG, "unable to find application icon");
    }
    if (appinfo.labelRes != 0) {
        appName = context.getString(appinfo.labelRes);
    } else {
        Log.w(TAG, "unable to find application label");
    }
    if (new File(appinfo.sourceDir).lastModified() > preferences.getLong(MD5_TIME, 0)) {
        preferences.edit().putString(MD5_KEY, MD5Hex(appinfo.sourceDir)).commit();
        preferences.edit().putLong(MD5_TIME, System.currentTimeMillis()).commit();

        String update_file = preferences.getString(UPDATE_FILE, "");
        if (update_file.length() > 0) {
            if (new File(context.getFilesDir().getAbsolutePath() + "/" + update_file).delete()) {
                preferences.edit().remove(UPDATE_FILE).commit();
            }
        }
    }
    raise_notification();

    if (haveInternetPermissions()) {
        context.registerReceiver(connectivity_receiver,
                new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }
}

From source file:com.danvelazco.fbwrapper.activity.BaseFacebookWebViewActivity.java

/**
 * {@inheritDoc}/*from   ww  w  . ja v a 2s  .  co m*/
 */
@Override
public void onResume() {
    super.onResume();

    // Pass lifecycle events to the WebView
    mWebView.onResume();

    // Start synchronizing the CookieSyncManager
    mCookieSyncManager.startSync();

    // Set the cache mode depending on connection type and availability
    updateCacheMode();

    // Register a Connectivity action receiver so that we can update the cache mode accordingly
    registerReceiver(mConnectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

    // Horrible lifecycle hack
    if (mCreatingActivity) {
        mCreatingActivity = false;
        return;
    }

    // Resume this activity properly, reload preferences, etc.
    onResumeActivity();
}