Example usage for android.net ConnectivityManager getNetworkInfo

List of usage examples for android.net ConnectivityManager getNetworkInfo

Introduction

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

Prototype

@Deprecated
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
@Nullable
public NetworkInfo getNetworkInfo(@Nullable Network network) 

Source Link

Document

Returns connection status information about a particular Network.

Usage

From source file:pubsub.io.android.Pubsub.java

/**
 * Detects if we have internet or not, checks both WiFi and 3G.
 * //w  w  w . j  a v  a 2  s  .  com
 * @return
 */
public boolean hasInternet() {
    if (DEBUG)
        Log.i(TAG, "hasInternet()");

    ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (DEBUG)
        Log.i(TAG, "Testing WiFi status");

    // First test wifi for status!
    NetworkInfo netInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        if (DEBUG)
            Log.i(TAG, "WiFi detected, connecting");
        return true;
    }

    if (DEBUG)
        Log.i(TAG, "No WiFi detected, trying mobile");

    netInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        if (DEBUG)
            Log.i(TAG, "Mobile detected, connecting");
        return true;
    }

    if (DEBUG)
        Log.i(TAG, "No Mobile detected, aborting");

    return false;
}

From source file:com.mobeelizer.mobile.android.MobeelizerRealConnectionManagerTest.java

@Before
public void init() throws Exception {
    PowerMockito.mockStatic(Log.class);
    PowerMockito.when(Log.class, "i", anyString(), anyString()).thenReturn(0);
    PowerMockito.when(Log.class, "e", anyString(), anyString()).thenReturn(0);
    PowerMockito.when(Log.class, "e", anyString(), anyString(), any(Throwable.class)).thenReturn(0);

    PowerMockito.mockStatic(Proxy.class);
    PowerMockito.when(Proxy.class, "getHost", any(Context.class)).thenReturn(null);
    PowerMockito.when(Proxy.class, "getPort", any(Context.class)).thenReturn(-1);

    httpClient = PowerMockito.mock(DefaultHttpClient.class);
    whenNew(DefaultHttpClient.class)
            .withArguments(any(ClientConnectionManager.class), any(BasicHttpParams.class))
            .thenReturn(httpClient);//  w  w w .  j a  v a  2  s .co m

    httpConnectionManager = PowerMockito.mock(ClientConnectionManager.class);
    when(httpClient.getConnectionManager()).thenReturn(httpConnectionManager);

    httpGet = PowerMockito.mock(HttpGet.class);
    whenNew(HttpGet.class).withArguments(anyString()).thenReturn(httpGet);

    httpPost = PowerMockito.mock(HttpPost.class);
    whenNew(HttpPost.class).withArguments(anyString()).thenReturn(httpPost);

    httpResponse = PowerMockito.mock(HttpResponse.class);
    when(httpClient.execute(httpGet)).thenReturn(httpResponse);
    when(httpClient.execute(httpPost)).thenReturn(httpResponse);

    httpEntity = PowerMockito.mock(HttpEntity.class);
    when(httpResponse.getEntity()).thenReturn(httpEntity);

    httpStatusLine = PowerMockito.mock(StatusLine.class);
    when(httpResponse.getStatusLine()).thenReturn(httpStatusLine);
    when(httpStatusLine.getStatusCode()).thenReturn(HttpStatus.SC_OK);

    application = mock(MobeelizerApplication.class);
    when(application.getVendor()).thenReturn("vendor");
    when(application.getApplication()).thenReturn("application");
    when(application.getInstance()).thenReturn("instance");
    when(application.getDevice()).thenReturn("device");
    when(application.getDeviceIdentifier()).thenReturn("deviceIdentifier");
    when(application.getUser()).thenReturn("user");
    when(application.getPassword()).thenReturn("password");
    when(application.getUrl()).thenReturn("http://url/app");

    Context context = PowerMockito.mock(Context.class);
    when(application.getContext()).thenReturn(context);

    ConnectivityManager connectivityService = PowerMockito.mock(ConnectivityManager.class);
    when(context.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityService);

    networkWifiInfo = PowerMockito.mock(NetworkInfo.class);
    when(connectivityService.getNetworkInfo(ConnectivityManager.TYPE_WIFI)).thenReturn(networkWifiInfo);
    when(networkWifiInfo.isConnected()).thenReturn(true);

    NetworkInfo networkMobileInfo = PowerMockito.mock(NetworkInfo.class);
    when(connectivityService.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)).thenReturn(networkMobileInfo);

    database = mock(MobeelizerInternalDatabase.class);
    when(application.getInternalDatabase()).thenReturn(database);

    connectionManager = new MobeelizerRealConnectionManager(application);
}

From source file:cm.aptoide.pt.RemoteInTab.java

public boolean updateRepos() {
    pd = ProgressDialog.show(this, "Please Wait", "Updating applications list...", true);
    pd.setIcon(android.R.drawable.ic_dialog_info);

    //Check for connection first!
    ConnectivityManager netstate = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    if (netstate.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED
            || netstate.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED) {
        db.removeAll();/*ww w .j  a va 2  s .c om*/
        myTabHost.setCurrentTabByTag("inst");
        new Thread() {
            public void run() {
                try {
                    Vector<ServerNode> serv = db.getServers();
                    for (ServerNode node : serv) {
                        if (node.inuse) {
                            downloadList(node.uri);
                            xmlPass(node.uri, true);
                        }
                    }
                } catch (Exception e) {
                }
                update_handler.sendEmptyMessage(0);
            }
        }.start();
        return true;
    } else {
        pd.dismiss();
        Toast.makeText(RemoteInTab.this, "Could not connect to the network.", Toast.LENGTH_LONG).show();
        return false;
    }
}

From source file:com.putlocker.upload.DownloadService.java

@Override
protected void onHandleIntent(Intent intent) {
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Download Wakelock");
    wl.acquire();/*from   w  ww  .  j ava  2s  . c  o m*/

    ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    WifiLock wifiLock = null;
    // We only want to aquire the wifi wake lock
    if (mWifi.isConnected()) {
        wifiLock = ((WifiManager) this.getSystemService(Context.WIFI_SERVICE))
                .createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY, "WlanSilencerScanLock");
        wifiLock.acquire();
    }

    if (intent.hasExtra(JOB_EXTRA_DOWNLOAD)) {
        handleDownloadIntent(intent);
    } else {
        handleUploadIntent(intent);
    }

    if (wifiLock != null && wifiLock.isHeld()) {
        wifiLock.release();
    }

    wl.release();
}

From source file:net.freifunk.android.discover.Main.java

void updateMaps() {
    final String URL = "https://raw.githubusercontent.com/NiJen/AndroidFreifunkNord/master/MapUrls.json";

    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    final ConnectivityManager connManager = (ConnectivityManager) getSystemService(
            this.getBaseContext().CONNECTIVITY_SERVICE);
    final NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    MapMaster mapMaster = MapMaster.getInstance();
    final DatabaseHelper databaseHelper = DatabaseHelper.getInstance(this.getApplicationContext());
    final RequestQueueHelper requestHelper = RequestQueueHelper.getInstance(this.getApplicationContext());

    final HashMap<String, NodeMap> mapList = databaseHelper.getAllNodeMaps();

    final boolean sync_wifi = sharedPrefs.getBoolean("sync_wifi", true);
    final int sync_frequency = Integer.parseInt(sharedPrefs.getString("sync_frequency", "0"));

    if (sync_wifi == true) {
        Log.d(TAG, "Performing online update ONLY via wifi, every " + sync_frequency + " minutes");
    } else {/*  ww w . ja  v  a  2 s .co m*/
        Log.d(TAG, "Performing online update ALWAYS, every " + sync_frequency + " minutes");
    }

    updateTask = new TimerTask() {
        @Override
        public void run() {
            /* load from database */
            for (NodeMap map : mapList.values()) {
                map.loadNodes();
            }

            /* load from web */
            if (connManager.getActiveNetworkInfo() != null
                    && (sync_wifi == false || mWifi.isConnected() == true)) {
                Log.d(TAG, "Performing online update. Next update at " + scheduledExecutionTime());
                requestHelper.add(new JsonObjectRequest(URL, null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        try {
                            MapMaster mapMaster = MapMaster.getInstance();

                            Iterator mapkeys = jsonObject.keys();
                            while (mapkeys.hasNext()) {
                                String mapName = mapkeys.next().toString();
                                String mapUrl = jsonObject.getString(mapName);

                                NodeMap m = new NodeMap(mapName, mapUrl);
                                databaseHelper.addNodeMap(m);

                                // only update, if not already found in database
                                if (!mapList.containsKey(m.getMapName())) {
                                    m.loadNodes();
                                }
                            }
                        } catch (JSONException e) {
                            Log.e(TAG, e.toString());
                        } finally {
                            requestHelper.RequestDone();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e(TAG, volleyError.toString());
                        requestHelper.RequestDone();
                    }
                }));
            } else {
                Log.d(TAG, "Online update is skipped. Next try at " + scheduledExecutionTime());
            }
        }
    };

    Timer timer = new Timer();

    if (sync_frequency > 0) {
        timer.schedule(updateTask, 0, (sync_frequency * 60 * 1000));
    } else {
        timer.schedule(updateTask, 0);
    }

}

From source file:org.sufficientlysecure.keychain.ui.transfer.presenter.TransferPresenter.java

private boolean isWifiConnected() {
    ConnectivityManager connManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo wifiNetwork = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    return wifiNetwork.isConnected();
}

From source file:com.google.plus.samples.photohunt.ThemeViewActivity.java

private void startCameraIntent() {
    ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (!mWifi.isConnected()) {
        Toast.makeText(this, getString(R.string.toast_connect_wifi), Toast.LENGTH_LONG).show();
    }/*from   w w w.  j  ava2s . c o  m*/

    Intent cameraIntent = Intents.getCameraIntent();
    startActivityForResult(cameraIntent, REQUEST_CODE_IMAGE_CAPTURE);
}

From source file:com.chalmers.schmaps.GoogleMapSearchLocation.java

/**
 * Check if the device is connected to internet.
 * Need three if-statements because getActiveNetworkInfo() may return null
 * and end up with a force close. So thats the last thing to check.
 * @return true if there is an internet connection
 *///w ww . j av a 2s. c o m
public boolean gotInternetConnection() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (wifiNetwork != null && wifiNetwork.isConnected()) {
        return true;
    }

    NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (mobileNetwork != null && mobileNetwork.isConnected()) {
        return true;
    }

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()) {
        return true;
    }

    return false;
}

From source file:com.google.zxing.client.android.history.HistoryActivity.java

public boolean netWorkdisponibilidade(Context cont) {
    boolean conectado = false;
    ConnectivityManager conmag;
    conmag = (ConnectivityManager) cont.getSystemService(Context.CONNECTIVITY_SERVICE);
    conmag.getActiveNetworkInfo();//from   w  ww. j a v a2s . c om
    // Verifica o WIFI
    if (conmag.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) {
        conectado = true;
        Toast.makeText(this, R.string.toast_is_net_wifi, Toast.LENGTH_LONG).show();
    }
    // Verifica o 3G
    else if (conmag.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected()) {
        conectado = true;
        Toast.makeText(this, R.string.toast_is_net_3g, Toast.LENGTH_LONG).show();
    } else {
        conectado = false;
    }
    return conectado;
}

From source file:org.cirdles.chroni.AliquotMenuActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handles menu item selection
    switch (item.getItemId()) {
    case R.id.returnToMenu: // Takes user to main menu by finishing the Activity
        finish();/*from w w w.j  a va2  s.c  om*/
        return true;
    case R.id.viewAliquotsMenu: // Takes user to aliquot menu
        Intent openAliquotFiles = new Intent("android.intent.action.FILEPICKER");
        openAliquotFiles.putExtra("Default_Directory", "From_Aliquot_Directory");
        startActivityForResult(openAliquotFiles, 1);
        return true;
    case R.id.viewReportSettingsMenu: // Takes user to report settings menu
        Intent openReportSettingsFiles = new Intent("android.intent.action.FILEPICKER");
        openReportSettingsFiles.putExtra("Default_Directory", "Report_Settings_Directory");
        startActivity(openReportSettingsFiles);
        return true;
    case R.id.importFilesMenu: // Takes user to import files menu
        Intent importFiles = new Intent("android.intent.action.IMPORTFILES");
        startActivity(importFiles);
        return true;
    case R.id.viewRootMenu:
        Intent openRootDirectory = new Intent("android.intent.action.FILEPICKER");
        openRootDirectory.putExtra("Default_Directory", "Root_Directory");
        startActivity(openRootDirectory);
        return true;
    case R.id.aboutScreen: // Takes user to about screen
        Intent openAboutScreen = new Intent("android.intent.action.ABOUT");
        startActivity(openAboutScreen);
        return true;
    case R.id.helpMenu: // Takes user to help blog
        // Checks internet connection before downloading files
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
                Context.CONNECTIVITY_SERVICE);
        NetworkInfo mobileWifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (mobileWifi.isConnected()) {
            Intent openHelpBlog = new Intent(Intent.ACTION_VIEW,
                    Uri.parse(getString(R.string.chroni_help_address)));
            startActivity(openHelpBlog);

        } else {
            new AlertDialog.Builder(this)
                    .setMessage("You are not connected to WiFi, mobile data rates may apply. "
                            + "Do you wish to continue?")
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Intent openHelpBlog = new Intent(Intent.ACTION_VIEW,
                                    Uri.parse(getString(R.string.chroni_help_address)));
                            startActivity(openHelpBlog);
                        }
                    }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    }).show();
        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}