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:org.exobel.routerkeygen.AutoConnectService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent == null) {
        stopSelf();/*from w  w  w .ja va 2 s  .co  m*/
        return START_NOT_STICKY;
    }
    attempts = 0;
    currentNetworkId = -1;
    network = intent.getParcelableExtra(SCAN_RESULT);
    keys = intent.getStringArrayListExtra(KEY_LIST);
    final ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    final NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (mWifi.isConnected()) {
        if (wifi.disconnect()) {
            // besides disconnecting, we clean any previous configuration
            Wifi.cleanPreviousConfiguration(wifi, network, network.capabilities);
            mNotificationManager.notify(UNIQUE_ID, createProgressBar(getString(R.string.app_name),
                    getString(R.string.not_auto_connect_waiting), 0));
            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                public void run() {
                    tryingConnection();
                }
            }, DISCONNECT_WAITING_TIME);
        } else {
            mNotificationManager.notify(UNIQUE_ID,
                    getSimple(getString(R.string.msg_error), getString(R.string.msg_error_key_testing))
                            .build());
            stopSelf();
            return START_NOT_STICKY;
        }
    } else {
        Wifi.cleanPreviousConfiguration(wifi, network, network.capabilities);
        tryingConnection();
    }
    return START_STICKY;
}

From source file:com.fairphone.updater.UpdaterService.java

private boolean hasInternetConnection() {

    ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    boolean is3g = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();

    boolean isWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();

    return isWifi || is3g;
}

From source file:com.near.chimerarevo.services.NewsService.java

@Override
protected void onHandleIntent(Intent i) {
    ConnectivityManager mConnManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    if (mConnManager != null) {
        mWifi = mConnManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        mMobile = mConnManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if (!isMobileConnected() && !isWiFiConnected())
            return;
    }// ww  w .  j a v  a 2  s .  c  om

    if (i.getBooleanExtra("shouldNotCreateNotification", false))
        mHandler.post(new DisplayToast(this, getResources().getString(R.string.text_loading)));

    Request request = new Request.Builder().url(URLUtils.getUrl()).build();

    try {
        Response response = OkHttpUtils.getInstance().newCall(request).execute();

        String body = response.body().string().trim();

        if (!body.isEmpty())
            if (readOfflineFile(body)) {
                ArrayList<String> mJson = new ArrayList<>();
                mJson.add((new JsonParser()).parse(body).toString());
                SysUtils.writeOfflineFile(this, mJson, "posts.ser");

                Intent update = new Intent(this, PostsListWidgetProvider.class);
                update.setAction(PostsListWidgetProvider.REFRESH_VIEWS_ACTION);
                sendBroadcast(update);

                update = new Intent(this, PostsLRWidgetProvider.class);
                update.setAction(PostsLRWidgetProvider.REFRESH_VIEWS_ACTION);
                sendBroadcast(update);

                if (!i.getBooleanExtra("shouldNotCreateNotification", false))
                    createNotification();
            }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:de.teambluebaer.patientix.activities.LoginActivity.java

/**
 * On press of the "Login" button, the users can access to the APP
 * with their PIN and after the StartActivity will be loaded.
 *
 * @param v default parameter to change something of the view
 */// w  w  w  .  j a  va  2  s .  c  o  m
public void onClickLoginButton(View v) {
    ConnectivityManager connManager = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (mWifi.isConnected()) {
        if (passwordHash(editTextPassword.getText().toString()).equals(Constants.PIN)) {
            new GetTabletID().execute();
        } else {
            editTextPassword.setText("");
            Toast.makeText(this, "Falscher PIN!!!", Toast.LENGTH_LONG).show();
        }
    } else {
        editTextPassword.setText("");
        Toast.makeText(this, "WiFi ist abgeschaltet, bitte schalten sie das WiFi wieder ein.",
                Toast.LENGTH_LONG).show();
    }
}

From source file:android_network.hetnet.vpn_service.Util.java

public static String getNetworkInfo(Context context) {
    StringBuilder sb = new StringBuilder();
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo ani = cm.getActiveNetworkInfo();
    List<NetworkInfo> listNI = new ArrayList<>();

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
        listNI.addAll(Arrays.asList(cm.getAllNetworkInfo()));
    else//  ww  w .j a  v  a  2  s  .  c  o m
        for (Network network : cm.getAllNetworks()) {
            NetworkInfo ni = cm.getNetworkInfo(network);
            if (ni != null)
                listNI.add(ni);
        }

    for (NetworkInfo ni : listNI) {
        sb.append(ni.getTypeName()).append('/').append(ni.getSubtypeName()).append(' ')
                .append(ni.getDetailedState())
                .append(TextUtils.isEmpty(ni.getExtraInfo()) ? "" : " " + ni.getExtraInfo())
                .append(ni.getType() == ConnectivityManager.TYPE_MOBILE
                        ? " " + Util.getNetworkGeneration(ni.getSubtype())
                        : "")
                .append(ni.isRoaming() ? " R" : "")
                .append(ani != null && ni.getType() == ani.getType() && ni.getSubtype() == ani.getSubtype()
                        ? " *"
                        : "")
                .append("\r\n");
    }

    try {
        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        if (nis != null)
            while (nis.hasMoreElements()) {
                NetworkInterface ni = nis.nextElement();
                if (ni != null && !ni.isLoopback()) {
                    List<InterfaceAddress> ias = ni.getInterfaceAddresses();
                    if (ias != null)
                        for (InterfaceAddress ia : ias)
                            sb.append(ni.getName()).append(' ').append(ia.getAddress().getHostAddress())
                                    .append('/').append(ia.getNetworkPrefixLength()).append(' ')
                                    .append(ni.getMTU()).append(' ').append(ni.isUp() ? '^' : 'v')
                                    .append("\r\n");
                }
            }
    } catch (Throwable ex) {
        sb.append(ex.toString()).append("\r\n");
    }

    if (sb.length() > 2)
        sb.setLength(sb.length() - 2);

    return sb.toString();
}

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

/**
 * Creates the necessary application directories: CIRDLES, Aliquot and Report Settings folders
 *///w  w w .  j a v a  2s .  co m
protected void createDirectories() throws FileNotFoundException {

    if (ContextCompat.checkSelfPermission(this,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,
                new String[] { android.Manifest.permission.WRITE_EXTERNAL_STORAGE }, 1);
    }

    if (ContextCompat.checkSelfPermission(this,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        // establishes the CIRDLES directories
        File chroniDirectory = new File(Environment.getExternalStorageDirectory() + "/CHRONI/");
        File aliquotDirectory = new File(Environment.getExternalStorageDirectory() + "/CHRONI/Aliquot");
        File reportSettingsDirectory = new File(
                Environment.getExternalStorageDirectory() + "/CHRONI/Report Settings");

        // gives default aliquot a path
        File defaultAliquotDirectory = new File(reportSettingsDirectory, "Default Aliquot");

        defaultReportSettingsPresent = false; // determines whether the default report settings is present or not
        defaultReportSettings2Present = false; // determines whether the default report settings 2 is present or not
        defaultAliquotPresent = false; // determines whether the aliquot is present or not

        // creates the directories if they are not there
        chroniDirectory.mkdirs();
        aliquotDirectory.mkdirs();
        reportSettingsDirectory.mkdirs();

        // checks internet connection before downloading files
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mobileWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        // checks to see if the default Report Settings files are present
        File[] reportSettingsFiles = reportSettingsDirectory.listFiles(); // Lists files in CHRONI directory
        for (File f : reportSettingsFiles) {
            if (f.getName().contentEquals("Default Report Settings.xml"))
                defaultReportSettingsPresent = true;

            if (f.getName().contentEquals("Default Report Settings 2.xml"))
                defaultReportSettings2Present = true;
        }

        // checks to see if the default Aliquot file is present
        File[] aliquotFiles = aliquotDirectory.listFiles();
        for (File f : aliquotFiles)
            if (f.getName().contentEquals("Default Aliquot.xml"))
                defaultAliquotPresent = true;

        if (mobileWifi.isConnected()) {
            // Downloads default report settings 1 if not present
            if (!defaultReportSettingsPresent) {
                // Downloads the default report settings file if absent
                URLFileReader downloader = new URLFileReader(HomeScreenActivity.this, "HomeScreen",
                        "https://raw.githubusercontent.com/CIRDLES/cirdles.github.com/master/assets/Default%20Report%20Settings%20XML/Default%20Report%20Settings.xml",
                        "url");
                downloader.startFileDownload(); // begins download
                defaultReportSettingsPresent = true;
                saveInitialLaunch();
                saveCurrentReportSettings(); // Notes that files have been downloaded and application has been properly initialized
            }

            if (!defaultReportSettings2Present) {
                // Downloads the second default report settings file if absent
                URLFileReader downloader2 = new URLFileReader(HomeScreenActivity.this, "HomeScreen",
                        "https://raw.githubusercontent.com/CIRDLES/cirdles.github.com/master/assets/Default%20Report%20Settings%20XML/Default%20Report%20Settings%202.xml",
                        "url");
                downloader2.startFileDownload(); // begins download
                defaultReportSettings2Present = true;
                saveInitialLaunch();
                saveCurrentReportSettings(); // Notes that files have been downloaded and application has been properly initialized
            }

            if (!defaultAliquotPresent) {
                URLFileReader downloader3 = new URLFileReader(HomeScreenActivity.this, "HomeScreenAliquot",
                        "https://raw.githubusercontent.com/CIRDLES/cirdles.github.com/master/assets/Default-Aliquot-XML/Default%20Aliquot.xml",
                        "url");
                downloader3.startFileDownload();
                defaultAliquotPresent = true;
                saveInitialLaunch();
                saveCurrentAliquot();
            }

        }
    }

}

From source file:com.master.metehan.filtereagle.Util.java

public static String getNetworkInfo(Context context) {
    StringBuilder sb = new StringBuilder();
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo ani = cm.getActiveNetworkInfo();
    List<NetworkInfo> listNI = new ArrayList<>();

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
        listNI.addAll(Arrays.asList(cm.getAllNetworkInfo()));
    else//from  www .  j  a v a 2  s  .co m
        for (Network network : cm.getAllNetworks()) {
            NetworkInfo ni = cm.getNetworkInfo(network);
            if (ni != null)
                listNI.add(ni);
        }

    for (NetworkInfo ni : listNI) {
        sb.append(ni.getTypeName()).append('/').append(ni.getSubtypeName()).append(' ')
                .append(ni.getDetailedState())
                .append(TextUtils.isEmpty(ni.getExtraInfo()) ? "" : " " + ni.getExtraInfo())
                .append(ni.getType() == ConnectivityManager.TYPE_MOBILE
                        ? " " + Util.getNetworkGeneration(ni.getSubtype())
                        : "")
                .append(ni.isRoaming() ? " R" : "")
                .append(ani != null && ni.getType() == ani.getType() && ni.getSubtype() == ani.getSubtype()
                        ? " *"
                        : "")
                .append("\r\n");
    }

    try {
        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        if (nis != null) {
            sb.append("\r\n");
            while (nis.hasMoreElements()) {
                NetworkInterface ni = nis.nextElement();
                if (ni != null) {
                    List<InterfaceAddress> ias = ni.getInterfaceAddresses();
                    if (ias != null)
                        for (InterfaceAddress ia : ias)
                            sb.append(ni.getName()).append(' ').append(ia.getAddress().getHostAddress())
                                    .append('/').append(ia.getNetworkPrefixLength()).append(' ')
                                    .append(ni.getMTU()).append("\r\n");
                }
            }
        }
    } catch (Throwable ex) {
        sb.append(ex.toString()).append("\r\n");
    }

    if (sb.length() > 2)
        sb.setLength(sb.length() - 2);

    return sb.toString();
}

From source file:com.iiitd.networking.UDPMessenger.java

/**
 * Sends a broadcast message (TAG EPOCH_TIME message). Opens a new socket in case it's closed.
 * @param message the message to send (multicast). It can't be null or 0-characters long.
 * @return/*from   w  w  w  . j  ava 2 s.c o  m*/
 * @throws IllegalArgumentException
 */
public boolean sendMessage(String message) throws IllegalArgumentException {
    if (message == null || message.length() == 0)
        throw new IllegalArgumentException();

    // Check for WiFi connectivity
    ConnectivityManager connManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    if (mWifi == null || !mWifi.isConnected()) {
        Log.d(DEBUG_TAG,
                "Sorry! You need to be in a WiFi network in order to send UDP multicast packets. Aborting.");
        return false;
    }

    // Check for IP address
    WifiManager wim = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    int ip = wim.getConnectionInfo().getIpAddress();

    // Create the send socket
    if (socket == null) {
        try {
            socket = new DatagramSocket();
        } catch (SocketException e) {
            Log.d(DEBUG_TAG, "There was a problem creating the sending socket. Aborting.");
            e.printStackTrace();
            return false;
        }
    }

    // Build the packet
    DatagramPacket packet;
    Message msg = new Message(TAG, message);
    byte data[] = msg.toString().getBytes();

    WifiInfo wifiInfo = wim.getConnectionInfo();
    int ipa = wifiInfo.getIpAddress();
    String ipAddress = Formatter.formatIpAddress(ipa);

    try {
        //         packet = new DatagramPacket(data, data.length, InetAddress.getByName(ipToString(ip, true)), MULTICAST_PORT);
        packet = new DatagramPacket(data, data.length, InetAddress.getByName(ipAddress), MULTICAST_PORT);
    } catch (UnknownHostException e) {
        Log.d(DEBUG_TAG, "It seems that " + ipToString(ip, true) + " is not a valid ip! Aborting.");
        e.printStackTrace();
        return false;
    }

    try {
        socket.send(packet);
    } catch (IOException e) {
        Log.d(DEBUG_TAG, "There was an error sending the UDP packet. Aborted.");
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:com.example.prasadnr.traquad.TraQuad.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tra_quad);
    ConnectivityManager connManager = (ConnectivityManager) getSystemService(TraQuad.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    Builder alert = new AlertDialog.Builder(TraQuad.this);

    WifiManager managerWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    Method[] wmMethods = managerWifi.getClass().getDeclaredMethods();
    for (Method method : wmMethods) {
        if (method.getName().equals("isWifiApEnabled")) {

            try {
                isWifiAPenabled = (boolean) method.invoke(managerWifi);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();//www .j a v  a 2  s  .  c o m
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    final ProgressDialog pDialog;
    MediaController mediaController = new MediaController(this);

    pDialog = new ProgressDialog(TraQuad.this);
    pDialog.setTitle("TraQuad app (Connecting...)");
    pDialog.setMessage("Buffering...Please wait...");
    pDialog.setCancelable(true);

    if (!isWifiAPenabled) {

        alert.setTitle("WiFi Hotspot Settings");
        alert.setMessage("Can you please connect WiFi-hotspot?");
        alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                irritation = true;
                startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
                pDialog.show();
            }
        });
        alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                //Dismiss AlertDialog
                pDialog.show();
                Toast.makeText(getApplicationContext(), "Please connect your WiFi!", Toast.LENGTH_LONG).show();
            }
        });
        alert.setCancelable(false);
        AlertDialog alertDialog = alert.create();
        alertDialog.show();
    }

    WebView webView = (WebView) findViewById(R.id.webView);

    if (irritation == true | isWifiAPenabled) {
        pDialog.show();
    }

    mediaController.setAnchorView(webView);
    mediaController.setVisibility(View.GONE);

    extra = getIntent().getStringExtra("VideosId");
    webView = (WebView) findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setPluginState(WebSettings.PluginState.ON);

    final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
    final String IPaddressNew = globalVariable.getIP();
    final String httpString = "http://";
    final String commandPort = String.valueOf(1500);
    final String streamPort = String.valueOf(8080);
    final String IPaddressStream = httpString + IPaddressNew + ":" + streamPort;
    final String IPaddressCommand = httpString + IPaddressNew + ":" + commandPort;
    TextView sendCharacter = (TextView) findViewById(R.id.sendCharacter);

    try {
        webView.loadUrl(IPaddressStream);
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), IPaddressNew + ":Error!", Toast.LENGTH_LONG).show();
    }

    webView.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String url) {
            pDialog.dismiss();
        }
    });

    final Button switchact = (Button) findViewById(R.id.btn2);
    switchact.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent act1 = new Intent(view.getContext(), Joypad.class);
            startActivity(act1);

        }
    });

    final Button hometraquad = (Button) findViewById(R.id.button5);

    hometraquad.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            Intent acthometraquad = new Intent(TraQuad.this, MainActivity.class);
            startActivity(acthometraquad);
        }
    });

}

From source file:com.drinviewer.droiddrinviewer.DrinViewerBroadcastReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
        NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
        if (networkInfo.isConnected()) {
            /**/*from w w w .j a  v  a2s .com*/
             * WiFi is connected, get its broadcast 
             * address and start the discovery process
             * repeated at a fixed time interval
             */
            wifiBroadcastAddress = getWiFiBroadcastAddress(context);
            startAlarmRepeater(context);
        } else {
            wifiBroadcastAddress = null;
        }
    } else if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
        NetworkInfo networkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
        if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI && !networkInfo.isConnected()) {
            /**
             * WiFi is disconnected, stop the discovery
             * process repeating, it would be a waste of resources
             */
            wifiBroadcastAddress = null;
            stopAlarmRepeater(context);
        }
    } else if (intent.getAction().equals(context.getResources().getString(R.string.broadcast_startdiscovery))
            || intent.getAction()
                    .equals(context.getResources().getString(R.string.broadcast_cleanhostcollection))) {

        boolean startService = true;
        /**
         * Calls the DiscoverServerService asking to do a discovery
         * or a clean host collection by simply forwarding the received action
         */
        Intent service = new Intent(context, DiscoverServerService.class);
        service.setAction(intent.getAction());

        if (intent.getAction().equals(context.getResources().getString(R.string.broadcast_startdiscovery))) {

            ConnectivityManager connManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            wifiBroadcastAddress = (mWifi.isConnected()) ? getWiFiBroadcastAddress(context) : null;
            startService = wifiBroadcastAddress != null;
            service.putExtra("wifiBroadcastAddress", wifiBroadcastAddress);
        }

        if (startService)
            startWakefulService(context, service);

        if (intent.getBooleanExtra("stopservice", false)) {
            context.stopService(service);
        }
    } else if (intent.getAction()
            .equals(context.getResources().getString(R.string.broadcast_startalarmrepeater))) {
        /**
         * start the alarm repeater only if WiFi is connected already
         * used by ServerListFragment.onServiceConnected method to start the discovery
         * if the application is launched being already connected to a WiFi network
         */
        ConnectivityManager connManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (mWifi.isConnected()) {
            // if we're called from the activity, try to get a broadcast address
            if (intent.getBooleanExtra("forcegetbroadcast", false))
                wifiBroadcastAddress = getWiFiBroadcastAddress(context);
            startAlarmRepeater(context);
        } else {
            wifiBroadcastAddress = null;
        }
    } else if (intent.getAction()
            .equals(context.getResources().getString(R.string.broadcast_stopalarmrepeater))) {
        /**
         *  stop the alarm repeater. period.
         *  used by DrinViewerApplication.onTerminate method
         */
        wifiBroadcastAddress = null;
        stopAlarmRepeater(context);
    }
}