Example usage for android.net NetworkInfo isConnectedOrConnecting

List of usage examples for android.net NetworkInfo isConnectedOrConnecting

Introduction

In this page you can find the example usage for android.net NetworkInfo isConnectedOrConnecting.

Prototype

@Deprecated
public boolean isConnectedOrConnecting() 

Source Link

Document

Indicates whether network connectivity exists or is in the process of being established.

Usage

From source file:es.upv.riromu.arbre.main.MainActivity.java

/******************************************/
public void sendData(View view) {
    ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    try {/* ww w  . j ava2  s .c o m*/

        Calendar c = Calendar.getInstance();
        SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
        String formattedDate = df.format(c.getTime());
        String result = "";

        if (image_uri != null) {
            UploadImageTask task1 = new UploadImageTask(this, new Callback() {
                public void run(Object result) {
                    upload = result.toString();
                    //do something here with the result
                }
            });

            if (state[PICK_IMAGE]) {
                File f = new File(Util.getRealPathFromURI(this, image_uri));
                task1.execute(f, 1);
            } else {
                File f = new File(image_uri.getPath());
                task1.execute(f, 1);
            }

            UploadImageTask task2 = new UploadImageTask(this, new Callback() {
                public void run(Object result) {
                    //do something here with the result
                    upload = result.toString();
                }
            });

            File f = createJSONFile(histograma);
            task2.execute(f, 2);

            UploadImageTask task3 = new UploadImageTask(this, new Callback() {
                public void run(Object result) {
                    //do something here with the result
                    upload = result.toString();

                }
            });
            ImageView imv = (ImageView) findViewById(R.id.image_intro);
            Bitmap bm = ((BitmapDrawable) imv.getDrawable()).getBitmap();
            f = createImageFile(bm);
            task3.execute(f, 3);

            UploadImageTask task4 = new UploadImageTask(this, new Callback() {
                public void run(Object result) {
                    //do something here with the result
                    upload = result.toString();

                }
            });

            f = createJSONFile(mascara);
            task4.execute(f, 4);

            UploadImageTask task5 = new UploadImageTask(this, new Callback() {
                public void run(Object result) {
                    //do something here with the result
                    upload = result.toString();

                }
            });

            f = createImageFile(histogram);
            task5.execute(f, 5);
            resetVariables();
        }

    } catch (Exception e) {
        Log.e(TAG, "Error" + e.getMessage());
    }

}

From source file:com.ibuildapp.romanblack.WebPlugin.WebPlugin.java

@Override
public void create() {
    try {/*w  w w .  j  a v a  2s  . co  m*/

        setContentView(R.layout.romanblack_html_main);
        root = (FrameLayout) findViewById(R.id.romanblack_root_layout);
        webView = new ObservableWebView(this);
        webView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT));
        root.addView(webView);

        webView.setHorizontalScrollBarEnabled(false);
        setTitle("HTML");

        Intent currentIntent = getIntent();
        Bundle store = currentIntent.getExtras();
        widget = (Widget) store.getSerializable("Widget");
        if (widget == null) {
            handler.sendEmptyMessageDelayed(INITIALIZATION_FAILED, 100);
            return;
        }
        appName = widget.getAppName();

        if (widget.getPluginXmlData().length() == 0) {
            if (currentIntent.getStringExtra("WidgetFile").length() == 0) {
                handler.sendEmptyMessageDelayed(INITIALIZATION_FAILED, 100);
                return;
            }
        }

        if (widget.getTitle() != null && widget.getTitle().length() > 0) {
            setTopBarTitle(widget.getTitle());
        } else {
            setTopBarTitle(getResources().getString(R.string.romanblack_html_web));
        }

        currentUrl = (String) getSession();
        if (currentUrl == null) {
            currentUrl = "";
        }

        ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni != null && ni.isConnectedOrConnecting()) {
            isOnline = true;
        }

        // topbar initialization
        setTopBarLeftButtonText(getString(R.string.common_home_upper), true, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

        if (isOnline) {
            webView.getSettings().setJavaScriptEnabled(true);
        }

        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.getSettings().setGeolocationEnabled(true);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setUseWideViewPort(false);
        webView.getSettings().setSavePassword(false);
        webView.clearHistory();
        webView.invalidate();

        if (Build.VERSION.SDK_INT >= 19) {
        }
        webView.getSettings().setUserAgentString(
                "Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; Nexus One Build/FRG83) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1");

        webView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.invalidate();

                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                }
                    break;
                case MotionEvent.ACTION_UP: {
                    if (!v.hasFocus()) {
                        v.requestFocus();
                    }
                }
                    break;

                case MotionEvent.ACTION_MOVE: {
                }
                    break;

                }
                return false;
            }
        });

        webView.setBackgroundColor(Color.WHITE);
        try {
            if (widget.getBackgroundColor() != Color.TRANSPARENT) {
                webView.setBackgroundColor(widget.getBackgroundColor());
            }
        } catch (IllegalArgumentException e) {
        }

        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition,
                    String mimetype, long contentLength) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                startActivity(intent);
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {

            FrameLayout.LayoutParams LayoutParameters = new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);

            @Override
            public void onGeolocationPermissionsShowPrompt(final String origin,
                    final GeolocationPermissions.Callback callback) {
                AlertDialog.Builder builder = new AlertDialog.Builder(WebPlugin.this);
                builder.setTitle(R.string.location_dialog_title);
                builder.setMessage(R.string.location_dialog_description);
                builder.setCancelable(true);

                builder.setPositiveButton(R.string.location_dialog_allow,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                callback.invoke(origin, true, false);
                            }
                        });

                builder.setNegativeButton(R.string.location_dialog_not_allow,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                callback.invoke(origin, false, false);
                            }
                        });

                AlertDialog alert = builder.create();
                alert.show();
            }

            @Override
            public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
                if (customView != null) {
                    customViewCallback.onCustomViewHidden();
                    return;
                }

                view.setBackgroundColor(Color.BLACK);
                view.setLayoutParams(LayoutParameters);
                root.addView(view);
                customView = view;
                customViewCallback = callback;
                webView.setVisibility(View.GONE);
            }

            @Override
            public void onHideCustomView() {
                if (customView == null) {
                    return;
                } else {
                    closeFullScreenVideo();
                }
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg) {

                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);//Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                isMedia = true;
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);

            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
            }

            //For Android 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                isMedia = true;
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);

            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                    FileChooserParams fileChooserParams) {
                isV21 = true;
                mUploadMessageV21 = filePathCallback;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
                return true;
            }

            @Override
            public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) {
                super.onReceivedTouchIconUrl(view, url, precomposed);
            }
        });

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

                if (state == states.EMPTY) {
                    currentUrl = url;
                    setSession(currentUrl);
                    state = states.LOAD_START;
                    handler.sendEmptyMessage(SHOW_PROGRESS);
                }
            }

            @Override
            public void onLoadResource(WebView view, String url) {

                if (!alreadyLoaded
                        && (url.startsWith("http://www.youtube.com/get_video_info?")
                                || url.startsWith("https://www.youtube.com/get_video_info?"))
                        && Build.VERSION.SDK_INT < 11) {
                    try {
                        String path = url.contains("https://www.youtube.com/get_video_info?")
                                ? url.replace("https://www.youtube.com/get_video_info?", "")
                                : url.replace("http://www.youtube.com/get_video_info?", "");

                        String[] parqamValuePairs = path.split("&");

                        String videoId = null;

                        for (String pair : parqamValuePairs) {
                            if (pair.startsWith("video_id")) {
                                videoId = pair.split("=")[1];
                                break;
                            }
                        }

                        if (videoId != null) {
                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com"))
                                    .setData(Uri.parse("http://www.youtube.com/watch?v=" + videoId)));
                            needRefresh = true;
                            alreadyLoaded = !alreadyLoaded;

                            return;
                        }
                    } catch (Exception ex) {
                    }
                } else {
                    super.onLoadResource(view, url);
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (hideProgress) {
                    if (TextUtils.isEmpty(WebPlugin.this.url)) {
                        state = states.LOAD_COMPLETE;
                        handler.sendEmptyMessage(HIDE_PROGRESS);
                        super.onPageFinished(view, url);
                    } else {
                        view.loadUrl("javascript:(function(){" + "l=document.getElementById('link');"
                                + "e=document.createEvent('HTMLEvents');" + "e.initEvent('click',true,true);"
                                + "l.dispatchEvent(e);" + "})()");
                        hideProgress = false;
                    }
                } else {
                    state = states.LOAD_COMPLETE;
                    handler.sendEmptyMessage(HIDE_PROGRESS);
                    super.onPageFinished(view, url);
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                if (errorCode == WebViewClient.ERROR_BAD_URL) {
                    startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse(url)),
                            DOWNLOAD_REQUEST_CODE);
                }
            }

            @Override
            public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(WebPlugin.this);
                builder.setMessage(R.string.notification_error_ssl_cert_invalid);
                builder.setPositiveButton(WebPlugin.this.getResources().getString(R.string.wp_continue),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                handler.proceed();
                            }
                        });
                builder.setNegativeButton(WebPlugin.this.getResources().getString(R.string.wp_cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                handler.cancel();
                            }
                        });
                final AlertDialog dialog = builder.create();
                dialog.show();
            }

            @Override
            public void onFormResubmission(WebView view, Message dontResend, Message resend) {
                super.onFormResubmission(view, dontResend, resend);
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return super.shouldInterceptRequest(view, request);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                try {

                    if (url.contains("youtube.com/watch")) {
                        if (Build.VERSION.SDK_INT < 11) {
                            try {
                                startActivity(
                                        new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com"))
                                                .setData(Uri.parse(url)));
                                return true;
                            } catch (Exception ex) {
                                return false;
                            }
                        } else {
                            return false;
                        }
                    } else if (url.contains("paypal.com")) {
                        if (url.contains("&bn=ibuildapp_SP")) {
                            return false;
                        } else {
                            url = url + "&bn=ibuildapp_SP";

                            webView.loadUrl(url);

                            return true;
                        }
                    } else if (url.contains("sms:")) {
                        try {
                            Intent smsIntent = new Intent(Intent.ACTION_VIEW);
                            smsIntent.setData(Uri.parse(url));
                            startActivity(smsIntent);
                            return true;
                        } catch (Exception ex) {
                            Log.e("", ex.getMessage());
                            return false;
                        }
                    } else if (url.contains("tel:")) {
                        Intent callIntent = new Intent(Intent.ACTION_CALL);
                        callIntent.setData(Uri.parse(url));
                        startActivity(callIntent);
                        return true;
                    } else if (url.contains("mailto:")) {
                        MailTo mailTo = MailTo.parse(url);

                        Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
                        emailIntent.setType("plain/text");
                        emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                                new String[] { mailTo.getTo() });

                        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, mailTo.getSubject());
                        emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, mailTo.getBody());
                        WebPlugin.this.startActivity(Intent.createChooser(emailIntent,
                                getString(R.string.romanblack_html_send_email)));
                        return true;
                    } else if (url.contains("rtsp:")) {
                        Uri address = Uri.parse(url);
                        Intent intent = new Intent(Intent.ACTION_VIEW, address);

                        final PackageManager pm = getPackageManager();
                        final List<ResolveInfo> matches = pm.queryIntentActivities(intent, 0);
                        if (matches.size() > 0) {
                            startActivity(intent);
                        } else {
                            Toast.makeText(WebPlugin.this, getString(R.string.romanblack_html_no_video_player),
                                    Toast.LENGTH_SHORT).show();
                        }

                        return true;
                    } else if (url.startsWith("intent:") || url.startsWith("market:")
                            || url.startsWith("col-g2m-2:")) {
                        Intent it = new Intent();
                        it.setData(Uri.parse(url));
                        startActivity(it);

                        return true;
                    } else if (url.contains("//play.google.com/")) {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                        return true;
                    } else {
                        if (url.contains("ibuildapp.com-1915109")) {
                            String param = Uri.parse(url).getQueryParameter("widget");
                            finish();
                            if (param != null && param.equals("1001"))
                                com.appbuilder.sdk.android.Statics.launchMain();
                            else if (param != null && !"".equals(param)) {
                                View.OnClickListener widget = Statics.linkWidgets.get(Integer.valueOf(param));
                                if (widget != null)
                                    widget.onClick(view);
                            }
                            return false;
                        }

                        currentUrl = url;
                        setSession(currentUrl);
                        if (!isOnline) {
                            handler.sendEmptyMessage(HIDE_PROGRESS);
                            handler.sendEmptyMessage(STOP_LOADING);
                        } else {
                            String pageType = "application/html";
                            if (!url.contains("vk.com")) {
                                getPageType(url);
                            }
                            if (pageType.contains("application") && !pageType.contains("html")
                                    && !pageType.contains("xml")) {
                                startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse(url)),
                                        DOWNLOAD_REQUEST_CODE);
                                return super.shouldOverrideUrlLoading(view, url);
                            } else {
                                view.getSettings().setLoadWithOverviewMode(true);
                                view.getSettings().setUseWideViewPort(true);
                                view.setBackgroundColor(Color.WHITE);
                            }
                        }
                        return false;
                    }

                } catch (Exception ex) { // Error Logging
                    return false;
                }
            }
        });

        handler.sendEmptyMessage(SHOW_PROGRESS);

        new Thread() {
            @Override
            public void run() {

                EntityParser parser;
                if (widget.getPluginXmlData() != null) {
                    if (widget.getPluginXmlData().length() > 0) {
                        parser = new EntityParser(widget.getPluginXmlData());
                    } else {
                        String xmlData = readXmlFromFile(getIntent().getStringExtra("WidgetFile"));
                        parser = new EntityParser(xmlData);
                    }
                } else {
                    String xmlData = readXmlFromFile(getIntent().getStringExtra("WidgetFile"));
                    parser = new EntityParser(xmlData);
                }

                parser.parse();

                url = parser.getUrl();
                html = parser.getHtml();

                if (url.length() > 0 && !isOnline) {
                    handler.sendEmptyMessage(NEED_INTERNET_CONNECTION);
                } else {
                    if (isOnline) {
                    } else {
                        if (html.length() == 0) {
                        }
                    }
                    if (html.length() > 0 || url.length() > 0) {
                        handler.sendEmptyMessageDelayed(SHOW_HTML, 700);
                    } else {
                        handler.sendEmptyMessage(HIDE_PROGRESS);
                        handler.sendEmptyMessage(INITIALIZATION_FAILED);
                    }
                }
            }
        }.start();

    } catch (Exception ex) {
    }
}

From source file:com.landenlabs.all_devtool.NetFragment.java

public void updateList() {
    // Time today = new Time(Time.getCurrentTimezone());
    // today.setToNow();
    // today.format(" %H:%M:%S")
    Date dt = new Date();
    m_titleTime.setText(m_timeFormat.format(dt));

    boolean expandAll = m_list.isEmpty();
    m_list.clear();/*from  w  ww . ja  v  a 2s .c o m*/

    // Swap colors
    int color = m_rowColor1;
    m_rowColor1 = m_rowColor2;
    m_rowColor2 = color;

    ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);

    try {
        String androidIDStr = Settings.Secure.getString(getContext().getContentResolver(),
                Settings.Secure.ANDROID_ID);
        addBuild("Android ID", androidIDStr);

        try {
            AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getContext());
            final String adIdStr = adInfo.getId();
            final boolean isLAT = adInfo.isLimitAdTrackingEnabled();
            addBuild("Ad ID", adIdStr);
        } catch (IOException e) {
            // Unrecoverable error connecting to Google Play services (e.g.,
            // the old version of the service doesn't support getting AdvertisingId).
        } catch (GooglePlayServicesNotAvailableException e) {
            // Google Play services is not available entirely.
        }

        /*
        try {
        InstanceID instanceID = InstanceID.getInstance(getContext());
        if (instanceID != null) {
            // Requires a Google Developer project ID.
            String authorizedEntity = "<need to make this on google developer site>";
            instanceID.getToken(authorizedEntity, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            addBuild("Instance ID", instanceID.getId());
        }
        } catch (Exception ex) {
        }
        */

        ConfigurationInfo info = actMgr.getDeviceConfigurationInfo();
        addBuild("OpenGL", info.getGlEsVersion());
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    // --------------- Connection Services -------------
    try {
        ConnectivityManager connMgr = (ConnectivityManager) getActivity()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
        if (netInfo != null) {
            Map<String, String> netListStr = new LinkedHashMap<String, String>();

            putIf(netListStr, "Available", "Yes", netInfo.isAvailable());
            putIf(netListStr, "Connected", "Yes", netInfo.isConnected());
            putIf(netListStr, "Connecting", "Yes", !netInfo.isConnected() && netInfo.isConnectedOrConnecting());
            putIf(netListStr, "Roaming", "Yes", netInfo.isRoaming());
            putIf(netListStr, "Extra", netInfo.getExtraInfo(), !TextUtils.isEmpty(netInfo.getExtraInfo()));
            putIf(netListStr, "WhyFailed", netInfo.getReason(), !TextUtils.isEmpty(netInfo.getReason()));
            if (Build.VERSION.SDK_INT >= 16) {
                putIf(netListStr, "Metered", "Avoid heavy use", connMgr.isActiveNetworkMetered());
            }

            netListStr.put("NetworkType", netInfo.getTypeName());
            if (connMgr.getAllNetworkInfo().length > 1) {
                netListStr.put("Available Networks:", " ");
                for (NetworkInfo netI : connMgr.getAllNetworkInfo()) {
                    if (netI.isAvailable()) {
                        netListStr.put(" " + netI.getTypeName(), netI.isAvailable() ? "Yes" : "No");
                    }
                }
            }

            if (netInfo.isConnected()) {
                try {
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                            .hasMoreElements();) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                                .hasMoreElements();) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress()) {
                                if (inetAddress.getHostAddress() != null) {
                                    String ipType = (inetAddress instanceof Inet4Address) ? "IPv4" : "IPv6";
                                    netListStr.put(intf.getName() + " " + ipType, inetAddress.getHostAddress());
                                }
                                // if (!TextUtils.isEmpty(inetAddress.getHostName()))
                                //     listStr.put( "HostName", inetAddress.getHostName());
                            }
                        }
                    }
                } catch (Exception ex) {
                    m_log.e("Network %s", ex.getMessage());
                }
            }

            addBuild("Network...", netListStr);
        }
    } catch (Exception ex) {
        m_log.e("Network %s", ex.getMessage());
    }

    // --------------- Telephony Services -------------
    TelephonyManager telephonyManager = (TelephonyManager) getActivity()
            .getSystemService(Context.TELEPHONY_SERVICE);
    if (telephonyManager != null) {
        Map<String, String> cellListStr = new LinkedHashMap<String, String>();
        try {
            cellListStr.put("Version", telephonyManager.getDeviceSoftwareVersion());
            cellListStr.put("Number", telephonyManager.getLine1Number());
            cellListStr.put("Service", telephonyManager.getNetworkOperatorName());
            cellListStr.put("Roaming", telephonyManager.isNetworkRoaming() ? "Yes" : "No");
            cellListStr.put("Type", getNetworkTypeName(telephonyManager.getNetworkType()));

            if (Build.VERSION.SDK_INT >= 17) {
                if (telephonyManager.getAllCellInfo() != null) {
                    for (CellInfo cellInfo : telephonyManager.getAllCellInfo()) {
                        String cellName = cellInfo.getClass().getSimpleName();
                        int level = 0;
                        if (cellInfo instanceof CellInfoCdma) {
                            level = ((CellInfoCdma) cellInfo).getCellSignalStrength().getLevel();
                        } else if (cellInfo instanceof CellInfoGsm) {
                            level = ((CellInfoGsm) cellInfo).getCellSignalStrength().getLevel();
                        } else if (cellInfo instanceof CellInfoLte) {
                            level = ((CellInfoLte) cellInfo).getCellSignalStrength().getLevel();
                        } else if (cellInfo instanceof CellInfoWcdma) {
                            if (Build.VERSION.SDK_INT >= 18) {
                                level = ((CellInfoWcdma) cellInfo).getCellSignalStrength().getLevel();
                            }
                        }
                        cellListStr.put(cellName, "Level% " + String.valueOf(100 * level / 4));
                    }
                }
            }

            for (NeighboringCellInfo cellInfo : telephonyManager.getNeighboringCellInfo()) {
                int level = cellInfo.getRssi();
                cellListStr.put("Cell level%", String.valueOf(100 * level / 31));
            }

        } catch (Exception ex) {
            m_log.e("Cell %s", ex.getMessage());
        }

        if (!cellListStr.isEmpty()) {
            addBuild("Cell...", cellListStr);
        }
    }

    // --------------- Bluetooth Services (API18) -------------
    if (Build.VERSION.SDK_INT >= 18) {
        try {
            BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (bluetoothAdapter != null) {

                Map<String, String> btListStr = new LinkedHashMap<String, String>();

                btListStr.put("Enabled", bluetoothAdapter.isEnabled() ? "yes" : "no");
                btListStr.put("Name", bluetoothAdapter.getName());
                btListStr.put("ScanMode", String.valueOf(bluetoothAdapter.getScanMode()));
                btListStr.put("State", String.valueOf(bluetoothAdapter.getState()));
                Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
                // If there are paired devices
                if (pairedDevices.size() > 0) {
                    // Loop through paired devices
                    for (BluetoothDevice device : pairedDevices) {
                        // Add the name and address to an array adapter to show in a ListView
                        btListStr.put("Paired:" + device.getName(), device.getAddress());
                    }
                }

                BluetoothManager btMgr = (BluetoothManager) getActivity()
                        .getSystemService(Context.BLUETOOTH_SERVICE);
                if (btMgr != null) {
                    // btMgr.getAdapter().
                }
                addBuild("Bluetooth", btListStr);
            }

        } catch (Exception ex) {

        }
    }

    // --------------- Wifi Services -------------
    final WifiManager wifiMgr = (WifiManager) getContext().getApplicationContext()
            .getSystemService(Context.WIFI_SERVICE);

    if (wifiMgr != null && wifiMgr.isWifiEnabled() && wifiMgr.getDhcpInfo() != null) {

        if (mSystemBroadcastReceiver == null) {
            mSystemBroadcastReceiver = new SystemBroadcastReceiver(wifiMgr);
            getActivity().registerReceiver(mSystemBroadcastReceiver, INTENT_FILTER_SCAN_AVAILABLE);
        }

        if (ActivityCompat.checkSelfPermission(getContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(getContext(),
                        Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            if (wifiMgr.getScanResults() == null || wifiMgr.getScanResults().size() != mLastScanSize) {
                mLastScanSize = wifiMgr.getScanResults().size();
                wifiMgr.startScan();
            }
        }

        Map<String, String> wifiListStr = new LinkedHashMap<String, String>();
        try {
            DhcpInfo dhcpInfo = wifiMgr.getDhcpInfo();

            wifiListStr.put("DNS1", Formatter.formatIpAddress(dhcpInfo.dns1));
            wifiListStr.put("DNS2", Formatter.formatIpAddress(dhcpInfo.dns2));
            wifiListStr.put("Default Gateway", Formatter.formatIpAddress(dhcpInfo.gateway));
            wifiListStr.put("IP Address", Formatter.formatIpAddress(dhcpInfo.ipAddress));
            wifiListStr.put("Subnet Mask", Formatter.formatIpAddress(dhcpInfo.netmask));
            wifiListStr.put("Server IP", Formatter.formatIpAddress(dhcpInfo.serverAddress));
            wifiListStr.put("Lease Time(sec)", String.valueOf(dhcpInfo.leaseDuration));

            WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
            if (wifiInfo != null) {
                wifiListStr.put("LinkSpeed Mbps", String.valueOf(wifiInfo.getLinkSpeed()));
                int numberOfLevels = 10;
                int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels + 1);
                wifiListStr.put("Signal%", String.valueOf(100 * level / numberOfLevels));
                if (Build.VERSION.SDK_INT >= 23) {
                    wifiListStr.put("MAC", getMacAddr());
                } else {
                    wifiListStr.put("MAC", wifiInfo.getMacAddress());
                }
            }

        } catch (Exception ex) {
            m_log.e("Wifi %s", ex.getMessage());
        }

        if (!wifiListStr.isEmpty()) {
            addBuild("WiFi...", wifiListStr);
        }

        try {
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(getContext(),
                            Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                List<ScanResult> listWifi = wifiMgr.getScanResults();
                if (listWifi != null && !listWifi.isEmpty()) {
                    int idx = 0;

                    for (ScanResult scanResult : listWifi) {
                        Map<String, String> wifiScanListStr = new LinkedHashMap<String, String>();
                        wifiScanListStr.put("SSID", scanResult.SSID);
                        if (Build.VERSION.SDK_INT >= 23) {
                            wifiScanListStr.put("  Name", scanResult.operatorFriendlyName.toString());
                            wifiScanListStr.put("  Venue", scanResult.venueName.toString());
                        }

                        //        wifiScanListStr.put("  BSSID ",scanResult.BSSID);
                        wifiScanListStr.put("  Capabilities", scanResult.capabilities);
                        //       wifiScanListStr.put("  Center Freq", String.valueOf(scanResult.centerFreq0));
                        //       wifiScanListStr.put("  Freq width", String.valueOf(scanResult.channelWidth));
                        wifiScanListStr.put("  Level, Freq",
                                String.format("%d, %d", scanResult.level, scanResult.frequency));
                        if (Build.VERSION.SDK_INT >= 17) {
                            Date wifiTime = new Date(scanResult.timestamp);
                            wifiScanListStr.put("  Time", wifiTime.toLocaleString());
                        }
                        addBuild(String.format("WiFiScan #%d", ++idx), wifiScanListStr);
                    }
                }
            }
        } catch (Exception ex) {
            m_log.e("WifiList %s", ex.getMessage());
        }

        try {
            List<WifiConfiguration> listWifiCfg = wifiMgr.getConfiguredNetworks();

            for (WifiConfiguration wifiCfg : listWifiCfg) {
                Map<String, String> wifiCfgListStr = new LinkedHashMap<String, String>();
                if (Build.VERSION.SDK_INT >= 23) {
                    wifiCfgListStr.put("Name", wifiCfg.providerFriendlyName);
                }
                wifiCfgListStr.put("SSID", wifiCfg.SSID);
                String netStatus = "";
                switch (wifiCfg.status) {
                case WifiConfiguration.Status.CURRENT:
                    netStatus = "Connected";
                    break;
                case WifiConfiguration.Status.DISABLED:
                    netStatus = "Disabled";
                    break;
                case WifiConfiguration.Status.ENABLED:
                    netStatus = "Enabled";
                    break;
                }
                wifiCfgListStr.put(" Status", netStatus);
                wifiCfgListStr.put(" Priority", String.valueOf(wifiCfg.priority));
                if (null != wifiCfg.wepKeys) {
                    //               wifiCfgListStr.put(" wepKeys", TextUtils.join(",", wifiCfg.wepKeys));
                }
                String protocols = "";
                if (wifiCfg.allowedProtocols.get(WifiConfiguration.Protocol.RSN))
                    protocols = "RSN ";
                if (wifiCfg.allowedProtocols.get(WifiConfiguration.Protocol.WPA))
                    protocols = protocols + "WPA ";
                wifiCfgListStr.put(" Protocols", protocols);

                String keyProt = "";
                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE))
                    keyProt = "none";
                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP))
                    keyProt = "WPA+EAP ";
                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK))
                    keyProt = "WPA+PSK ";
                wifiCfgListStr.put(" Keys", keyProt);

                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)) {
                    // Remove network connections with no Password.
                    // wifiMgr.removeNetwork(wifiCfg.networkId);
                }

                addBuild("WiFiCfg #" + wifiCfg.networkId, wifiCfgListStr);
            }

        } catch (Exception ex) {
            m_log.e("Wifi Cfg List %s", ex.getMessage());
        }
    }

    if (expandAll) {
        // updateList();
        int count = m_list.size();
        for (int position = 0; position < count; position++)
            m_listView.expandGroup(position);
    }

    m_adapter.notifyDataSetChanged();
}

From source file:uni.oulu.mentor.TeacherVisionActivity.java

/**
 * Checks if the network connection is OK
 *///from ww w .j a va  2 s .c  o m
public static boolean networkConnected(Context context) {
    ConnectivityManager connMan = (ConnectivityManager) context.getSystemService(Activity.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMan.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnectedOrConnecting())
        return true;
    else
        return false;
}

From source file:com.dwdesign.tweetings.util.Utils.java

public static boolean hasActiveConnection(final Context context) {
    if (context == null)
        return false;
    final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting())
        return true;
    return false;
}

From source file:org.tvbrowser.tvbrowser.TvBrowser.java

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();

    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }/*from   ww w .  ja v  a  2  s .  c  o m*/

    return false;
}

From source file:com.codename1.impl.android.AndroidImplementation.java

/**
 * @inheritDoc// w w w. j  a v a2  s.c om
 */
public void setCurrentAccessPoint(String id) {

    if (apIds == null) {
        getAPIds();
    }
    NetworkInfo info = (NetworkInfo) apIds.get(id);
    if (info == null || info.isConnectedOrConnecting()) {
        return;

    }
    ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    cm.setNetworkPreference(info.getType());
}