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.mozilla.gecko.sync.setup.activities.SetupSyncActivity.java

private boolean hasInternet() {
    Logger.debug(LOG_TAG, "Checking internet connectivity.");
    ConnectivityManager connManager = (ConnectivityManager) mContext
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    NetworkInfo mobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    if (wifi.isConnected() || mobile.isConnected()) {
        Logger.debug(LOG_TAG, "Internet connected.");
        return true;
    }/*from w  w w  . j a v  a  2  s  .c o  m*/
    return false;
}

From source file:com.mattprecious.notisync.activity.MainActivity.java

private void setDefaults() {
    ConnectivityManager connec = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (mobile != null) {
        Preferences.setMode(this, Preferences.Mode.PRIMARY);
    } else {//from   ww  w  . j a v  a 2  s  .com
        Preferences.setMode(this, Preferences.Mode.SECONDARY);
    }

    Preferences.populateDefaults(this);
}

From source file:org.egov.android.view.activity.RegisterActivity.java

/**
 * internet connection test function//from   w  w  w  . j a  v  a 2s . com
 */
public boolean isInternetAvailable() {
    ConnectivityManager connectivity = (ConnectivityManager) getApplicationContext()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    boolean available = false;
    if (netInfo.isConnected()) {
        available = true;
    } else {
        netInfo = connectivity.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        available = netInfo.isConnected();
    }
    return available;
}

From source file:org.computeforcancer.android.BOINCActivity.java

private void determineStatus() {
    try {//w w  w .  j av a 2 s .  co m
        if (mIsBound) {
            ConnectivityManager conMngr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
            android.net.NetworkInfo wifi = conMngr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            if (!wifi.isConnected()) {
                BOINCActivity.monitor.setAutostart(false);
                BOINCActivity.monitor.setRunMode(BOINCDefs.RUN_MODE_NEVER);
            } else {
                SharedPreferences mSharedPreferences = getApplicationContext().getSharedPreferences(
                        "org.computeforcancer.android", Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);
                monitor.setAutostart(mSharedPreferences.getBoolean(SharedPrefs.AUTO_START, true));
                BOINCActivity.monitor.setRunMode(
                        mSharedPreferences.getBoolean(SharedPrefs.AUTO_START, true) ? BOINCDefs.RUN_MODE_AUTO
                                : BOINCDefs.RUN_MODE_NEVER);
            }
            Integer newComputingStatus = monitor.getComputingStatus();
            if (newComputingStatus != clientComputingStatus) {
                // computing status has changed, update and invalidate to force adaption of action items
                clientComputingStatus = newComputingStatus;
                supportInvalidateOptionsMenu();
            }
            /*
            if(numberProjectsInNavList != monitor.getProjects().size())
              numberProjectsInNavList = mDrawerListAdapter.compareAndAddProjects((ArrayList<Project>)monitor.getProjects());
            //setAppTitle();
            */}
    } catch (Exception e) {
    }
}

From source file:com.trigger_context.Main_Service.java

@Override
public void onCreate() {
    super.onCreate();
    main_Service = this;
    SharedPreferences users_sp = getSharedPreferences(Main_Service.USERS, MODE_PRIVATE);
    SharedPreferences data_sp = getSharedPreferences(Main_Service.MY_DATA, MODE_PRIVATE);
    conf_macs = new ArrayList<String>(users_sp.getAll().keySet());
    noti(conf_macs.toString(), "");
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getNetworkInfo(android.net.ConnectivityManager.TYPE_WIFI);
    Intent ServiceIntent = new Intent(this, Network_Service.class);

    if (info != null) {
        if (info.isConnected()) {
            Main_Service.wifi = true;
            Network.setWifiOn(true);/*  www  . j av  a  2 s.  c om*/
            Thread z = new Thread(new Network());
            z.start();
            try {
                z.join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // start service
            startService(ServiceIntent);
        }
    }
    users_sp.registerOnSharedPreferenceChangeListener(this);
    data_sp.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {

        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            // timeout n username can only be added or modified. not removed
            if (key.equals("username")) {
                username = sharedPreferences.getString("username", "defUsername");
            } else {
                timeout = sharedPreferences.getLong("timeout", 5 * 60) * 1000;
            }

        }
    });
    Log.i(LOG_TAG, "Main_Service-onCreate");
    noti("main serv", "started");
}

From source file:com.tarun.smartwomen.WebViewDemoActivity.java

@SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
@Override/* ww w .ja  v a  2  s .  c  o  m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.mainn);

    Intent intent = getIntent();
    reg = intent.getBooleanExtra("reg", false);

    i = (ImageView) findViewById(R.id.hj);

    try {

        big = new GifAnimationDrawable(getResources().openRawResource(R.raw.anim2));
        // big.setOneShot(true);
        android.util.Log.v("GifAnimationDrawable", "===>Four");
    } catch (IOException ioe) {

    }

    i.setImageDrawable(big);
    big.setVisible(true, true);

    sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
    // historyStack = new LinkedList<Link>();
    webview = (WebView) findViewById(R.id.webkit);

    WebSettings webSettings = webview.getSettings();
    webSettings.setJavaScriptEnabled(true);

    webSettings.setDomStorageEnabled(true);
    // webview.addJavascriptInterface(new WebViewDemoActivity(), "Android");
    // webview.getSettings().setJavaScriptEnabled(true);

    webview.getSettings().setBuiltInZoomControls(true);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
        // webview.getSettings().setPluginState(PluginState.ON);
        // webview.getSettings().setJavaScriptEnabled(true);
    } else {
        // IMPORTANT!! this method is no longer available since Android 4.3
        // so the code doesn't compile anymore
        // webview.getSettings().setPluginsEnabled(true);
    }

    // Internet

    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);
    connected = false;
    if ((null != connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) && connectivityManager
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)
            || (null != connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) && connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED)) {
        // we are connected to a network
        connected = true;
    }

    if (connected == false) {
        /*
         * Toast.makeText(Rss.this,
         * "Connect to internet and Restart Application",
         * Toast.LENGTH_SHORT).show();
         */
        webview.setVisibility(View.INVISIBLE);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(WebViewDemoActivity.this);

        // alertDialogBuilder.setTitle("Please connect to Internet");
        alertDialogBuilder.setMessage(
                "In order to provide the freshest recipes and juicing information this app must be connected to the internet, please check your internet settings");
        // set positive button: Yes message

        alertDialogBuilder.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // cancel the alert box and put a Toast to the user

                startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
            }
        });
        AlertDialog alertDialog = alertDialogBuilder.create();
        // show alert
        alertDialog.show();

    }

    // downloads
    // webview.setDownloadListener(new CustomDownloadListener());

    webview.setWebViewClient(new CustomWebViewClient());

    webview.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int progress) {

        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {

        }

    });

    // http://stackoverflow.com/questions/2083909/android-webview-refusing-user-input
    webview.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
                if (!v.hasFocus()) {
                    v.requestFocus();
                }
                break;
            }
            return false;
        }

    });

    if (reg == true) {
        if (Locale.getDefault().getLanguage().equals("es")) {

            webview.loadUrl("http://om-msmartwoman.com/member/register");
            // webview.loadUrl("http://live-juice-guru.gotpantheon.com/user/login");
        } else {
            webview.loadUrl("http://om-msmartwoman.com/member/register");
        }

        webview.requestFocus();
    } else {
        uhdj = sp.getString("your_int_key", "0");

        Log.e("Url is here ..............................", uhdj);
        // Welcome page loaded from assets directory
        if (Locale.getDefault().getLanguage().equals("es")) {

            webview.loadUrl(uhdj);
            // webview.loadUrl("http://live-juice-guru.gotpantheon.com/user/login");
        } else {
            webview.loadUrl(uhdj);
        }

        webview.requestFocus();
    }

}

From source file:com.alex.smartwomanmiddleeastfem.WebViewDemoActivity.java

@SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
@Override/*  w ww.  j  av a  2 s . c  o m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.mainn);

    Intent intent = getIntent();
    reg = intent.getBooleanExtra("reg", false);

    i = (ImageView) findViewById(R.id.hj);

    try {

        big = new GifAnimationDrawable(getResources().openRawResource(R.raw.anim2));
        // big.setOneShot(true);
        android.util.Log.v("GifAnimationDrawable", "===>Four");
    } catch (IOException ioe) {

    }

    i.setImageDrawable(big);
    big.setVisible(true, true);

    sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
    // historyStack = new LinkedList<Link>();
    webview = (WebView) findViewById(R.id.webkit);

    WebSettings webSettings = webview.getSettings();
    webSettings.setJavaScriptEnabled(true);

    webSettings.setDomStorageEnabled(true);
    // webview.addJavascriptInterface(new WebViewDemoActivity(), "Android");
    // webview.getSettings().setJavaScriptEnabled(true);

    webview.getSettings().setBuiltInZoomControls(true);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
        // webview.getSettings().setPluginState(PluginState.ON);
        // webview.getSettings().setJavaScriptEnabled(true);
    } else {
        // IMPORTANT!! this method is no longer available since Android 4.3
        // so the code doesn't compile anymore
        // webview.getSettings().setPluginsEnabled(true);
    }

    // Internet

    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);
    connected = false;
    if ((null != connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) && connectivityManager
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)
            || (null != connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) && connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED)) {
        // we are connected to a network
        connected = true;
    }

    if (connected == false) {
        /*
         * Toast.makeText(Rss.this,
         * "Connect to internet and Restart Application",
         * Toast.LENGTH_SHORT).show();
         */
        webview.setVisibility(View.INVISIBLE);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(WebViewDemoActivity.this);

        // alertDialogBuilder.setTitle("Please connect to Internet");
        alertDialogBuilder.setMessage(
                "Through our app offers some offline features, in order to stay actively connected to the SmartWoman community in realtime, you need an internet connection, tap here to check your settings or wait until you have connection.");
        // set positive button: Yes message

        alertDialogBuilder.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // cancel the alert box and put a Toast to the user

                startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
            }
        });
        AlertDialog alertDialog = alertDialogBuilder.create();
        // show alert
        alertDialog.show();

    }

    // downloads
    // webview.setDownloadListener(new CustomDownloadListener());

    webview.setWebViewClient(new CustomWebViewClient());

    webview.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int progress) {

        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {

        }

    });

    // http://stackoverflow.com/questions/2083909/android-webview-refusing-user-input
    webview.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
                if (!v.hasFocus()) {
                    v.requestFocus();
                }
                break;
            }
            return false;
        }

    });

    if (reg == true) {
        if (Locale.getDefault().getLanguage().equals("es")) {

            webview.loadUrl("http://www.qa-msmartwoman.com/member/register");
            // webview.loadUrl("http://live-juice-guru.gotpantheon.com/user/login");
        } else {
            webview.loadUrl("http://www.qa-msmartwoman.com/member/register");
        }

        webview.requestFocus();
    } else {
        uhdj = sp.getString("your_int_key", "0");

        //   Log.e("Url is here ..............................", uhdj);
        // Welcome page loaded from assets directory
        if (Locale.getDefault().getLanguage().equals("es")) {

            webview.loadUrl(uhdj);
            // webview.loadUrl("http://live-juice-guru.gotpantheon.com/user/login");
        } else {
            webview.loadUrl(uhdj);
        }

        webview.requestFocus();
    }

}

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    //Sets up activity layout
    super.onCreate(savedInstanceState);
    setTheme(android.R.style.Theme_Holo);
    setContentView(R.layout.aliquot_select);

    RelativeLayout aliquotMenuLayout = (RelativeLayout) findViewById(R.id.aliquotSelectBackground);

    //Places background image on layout after theme overriding
    aliquotMenuLayout.setBackground(getResources().getDrawable(R.drawable.background));

    Button aliquotFileSelectButton = (Button) findViewById(R.id.aliquotFileSelectButton);
    aliquotFileSelectButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Opens file picker activity to main menu
            Intent openFilePicker = new Intent("android.intent.action.FILEPICKER");
            openFilePicker.putExtra("Default_Directory", "From_Aliquot_Directory");
            startActivityForResult(openFilePicker, 1); // Opens FilePicker and waits for it to return an Extra (SEE onActivityResult())
        }/*from  w  w  w  .j  av a 2s. c  o  m*/
    });

    aliquotSelectedFileText = (EditText) findViewById(R.id.aliquotFileSelectText); // Contains selected aliquot file name

    // sets the Aliquot file when one has already been selected (through "View Files" menu)
    if (getIntent().hasExtra("AliquotXMLFileName")) {
        String aliquotPath = getIntent().getStringExtra("AliquotXMLFileName");
        aliquotSelectedFileText.setText(splitReportSettingsName(aliquotPath));
    }

    Button aliquotFileSubmitButton = (Button) findViewById(R.id.aliquotFileSubmitButton);
    aliquotFileSubmitButton.setOnClickListener(new View.OnClickListener() {
        // Submits aliquot file to display activity for parsing and displaying in table
        public void onClick(View v) {

            if (aliquotSelectedFileText.getText().length() != 0) {

                // if coming from a previously created table, change the aliquot
                if (getIntent().hasExtra("From_Table")) {
                    if (getIntent().getStringExtra("From_Table").equals("true")) {

                        // if the Aliquot selected is valid, return to the new table
                        if (validateFile(getIntent().getStringExtra("AliquotXMLFileName"))) {
                            Toast.makeText(AliquotMenuActivity.this, "Changing Aliquot...", Toast.LENGTH_LONG)
                                    .show(); // lets user know table is opening
                            Intent returnAliquot = new Intent("android.intent.action.DISPLAY");
                            returnAliquot.putExtra("newAliquot", "true"); // tells if a new Aliquot has been chosen

                            // tells Intent that it is from a previous table that was opened via the History table
                            if (getIntent().hasExtra("fromHistory")) {
                                returnAliquot.putExtra("fromHistory",
                                        getIntent().getStringExtra("fromHistory"));
                                returnAliquot.putExtra("historyAliquot",
                                        getIntent().getStringExtra("AliquotXMLFileName"));

                                if (!getIntent().getStringExtra("fromHistory").equals("true"))
                                    saveCurrentAliquot(); // saves Aliquot if Intent was NOT originally from the History table
                            }

                            else // saves Aliquot if Intent was NOT originally from the History table (and doesn't have extra)
                                saveCurrentAliquot();

                            setResult(RESULT_OK, returnAliquot);
                            finish();

                        } else // if it is not valid, display a message
                            Toast.makeText(AliquotMenuActivity.this, "ERROR: Invalid Aliquot XML file.",
                                    Toast.LENGTH_LONG).show();

                    }

                } else {

                    // if the Aliquot selected is valid, return to the new table
                    if (validateFile(getIntent().getStringExtra("AliquotXMLFileName"))) {
                        // Makes sure there is a file selected
                        Toast.makeText(AliquotMenuActivity.this, "Opening table...", Toast.LENGTH_LONG).show(); // lets user know table is opening
                        Intent openDisplayTable = new Intent("android.intent.action.DISPLAY"); // Opens display table
                        openDisplayTable.putExtra("fromHistory", "false"); // tells Intent that it is not from History table

                        saveCurrentAliquot();

                        startActivity(openDisplayTable); // Starts display activity

                    } else // if it is not valid, display a message
                        Toast.makeText(AliquotMenuActivity.this, "ERROR: Invalid Aliquot XML file.",
                                Toast.LENGTH_LONG).show();

                }

            } else
                // Tells user to select a file for viewing
                Toast.makeText(AliquotMenuActivity.this, "Please select an aliquot file to view.",
                        Toast.LENGTH_LONG).show(); // lets user know table is opening

        }
    });

    igsnText = (EditText) findViewById(R.id.aliquotIGSNText);
    // Checks to see if user profile information has been authenticated for private file access
    // Sets appropriate hint based on if credentials are stored or not
    retrieveCredentials();
    if (!getGeochronUsername().contentEquals("None") && !getGeochronPassword().contentEquals("None"))
        igsnText.setHint("Profile information stored. Private files enabled!");
    else
        igsnText.setHint("No profile information stored. Private files disabled.");

    Button igsnDownloadButton = (Button) findViewById(R.id.aliquotIGSNSubmitButton);
    igsnDownloadButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            // Hides SoftKeyboard When Download Button is Pressed
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(igsnText.getWindowToken(), 0);

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

            if (mobileWifi.isConnected()) {
                if (igsnText.getText().length() != 0) {
                    downloadAliquot();
                    igsnText.setText("");
                }
            } else {//Handles lack of wifi connection
                new AlertDialog.Builder(AliquotMenuActivity.this)
                        .setMessage("You are not connected to WiFi, mobile data rates may apply. "
                                + "Do you wish to continue?")
                        // if user selects yes, continue with validation
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                downloadAliquot();
                                igsnText.setText("");
                            }
                        })
                        // if user selects no, just go back
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        }).show();
            }
        }

    });

    // displays the current Report Settings
    TextView currentReportSettingsLabel = (TextView) findViewById(R.id.aliquotCurrentReportSettingsLabel);
    currentReportSettingsLabel
            .setText("Current Report Settings:\n" + splitReportSettingsName(retrieveReportSettingsFileName()));

    // if no file permissions, asks for them
    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);
    }
}

From source file:com.g_node.gca.abstracts.AbstractContentTabFragment.java

private void getAndUpdateAbstractFiguresBtn() {
    String getFiguresQuery = "SELECT * FROM ABSTRACT_FIGURES WHERE ABSTRACT_UUID = '" + value + "';";
    Cursor absFiguresCursor = DatabaseHelper.database.rawQuery(getFiguresQuery, null);

    if (absFiguresCursor.getCount() > 0) {
        btnOpenAbstractFig.setText("Show Figures" + "  (" + absFiguresCursor.getCount() + ")");

        btnOpenAbstractFig.setOnClickListener(new OnClickListener() {

            @Override/*from   ww w .j a  v  a 2 s.c om*/
            public void onClick(View arg0) {
                //if Internet is connected
                if (isNetworkAvailable()) {

                    //check if interent is WIFI
                    ConnectivityManager connManager = (ConnectivityManager) getActivity()
                            .getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                    NetworkInfo mMobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

                    if (mWifi.isConnected()) {
                        //Toast.makeText(getActivity(), "Connected via WLAN", Toast.LENGTH_SHORT).show();
                        Intent figuresIntent = new Intent(getActivity(), AbstractFiguresActivity.class);
                        figuresIntent.putExtra("abs_uuid", value);
                        startActivity(figuresIntent);

                    } else if (mMobile.isConnected()) {
                        //if connected with mobile data - 2G, 3G, 4G etc
                        //Toast.makeText(getActivity(), "Connected via Mobile Internet", Toast.LENGTH_SHORT).show();

                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                        builder.setTitle("Additional Traffic Warning").setMessage(
                                "Downloading of Figures over Mobile Internet may create additional Traffic. Do you want to Continue ?")
                                .setPositiveButton("Continue", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        // if user Agrees to continue
                                        Intent figuresIntent = new Intent(getActivity(),
                                                AbstractFiguresActivity.class);
                                        figuresIntent.putExtra("abs_uuid", value);
                                        startActivity(figuresIntent);
                                    }
                                }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        // Handle Cancel
                                        dialog.cancel();
                                    }
                                }).setIcon(android.R.drawable.ic_dialog_alert).show();

                    } else {
                        ;
                    } //end if/else of wlan/mobile

                } else {
                    Toast.makeText(getActivity(),
                            "Not Connected to Internet - Please connect to Internet first", Toast.LENGTH_SHORT)
                            .show();
                } //end if/else of isNetworkAvailable

            }
        });

    } else {
        btnOpenAbstractFig.setText("No Figures Found");
        btnOpenAbstractFig.setEnabled(false);
        //btnOpenAbstractFig.setVisibility(View.GONE);
    }
}

From source file:com.appnexus.opensdk.AdRequest.java

private AdRequest(AdRequester adRequester, int httpRetriesLeft, int blankRetriesLeft) {
    owner = adRequester.getOwner();/*from  w  w w.  j  a  v a2  s .c  o m*/
    this.requester = adRequester;
    this.httpRetriesLeft = httpRetriesLeft;
    this.blankRetriesLeft = blankRetriesLeft;
    this.placementId = owner.getPlacementID();
    context = owner.getContext();
    String aid = android.provider.Settings.Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);

    // Do we have access to location?
    if (context.checkCallingOrSelfPermission(
            "android.permission.ACCESS_FINE_LOCATION") == PackageManager.PERMISSION_GRANTED
            || context.checkCallingOrSelfPermission(
                    "android.permission.ACCESS_COARSE_LOCATION") == PackageManager.PERMISSION_GRANTED) {
        // Get lat, long from any GPS information that might be currently
        // available
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Location lastLocation = lm.getLastKnownLocation(lm.getBestProvider(new Criteria(), false));
        if (lastLocation != null) {
            lat = "" + lastLocation.getLatitude();
            lon = "" + lastLocation.getLongitude();
            locDataAge = "" + (System.currentTimeMillis() - lastLocation.getTime());
            locDataPrecision = "" + lastLocation.getAccuracy();
        }
    } else {
        Clog.w(Clog.baseLogTag, Clog.getString(R.string.permissions_missing_location));
    }

    // Do we have permission ACCESS_NETWORK_STATE?
    if (context.checkCallingOrSelfPermission(
            "android.permission.ACCESS_NETWORK_STATE") != PackageManager.PERMISSION_GRANTED) {
        Clog.e(Clog.baseLogTag, Clog.getString(R.string.permissions_missing_network_state));
        fail();
        this.cancel(true);
        return;
    }

    // Get orientation, the current rotation of the device
    orientation = context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE
            ? "h"
            : "v";
    // Get hidmd5, hidsha1, the device ID hashed
    if (Settings.getSettings().hidmd5 == null) {
        Settings.getSettings().hidmd5 = HashingFunctions.md5(aid);
    }
    hidmd5 = Settings.getSettings().hidmd5;
    if (Settings.getSettings().hidsha1 == null) {
        Settings.getSettings().hidsha1 = HashingFunctions.sha1(aid);
    }
    hidsha1 = Settings.getSettings().hidsha1;
    // Get devMake, devModel, the Make and Model of the current device
    devMake = Settings.getSettings().deviceMake;
    devModel = Settings.getSettings().deviceModel;
    // Get carrier
    if (Settings.getSettings().carrierName == null) {
        Settings.getSettings().carrierName = ((TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE)).getNetworkOperatorName();
    }
    carrier = Settings.getSettings().carrierName;
    // Get firstlaunch and convert it to a string
    firstlaunch = Settings.getSettings().first_launch;
    // Get ua, the user agent...
    ua = Settings.getSettings().ua;
    // Get wxh

    if (owner.isBanner()) {
        this.width = ((BannerAdView) owner).getAdWidth();
        this.height = ((BannerAdView) owner).getAdHeight();
    }

    maxHeight = owner.getContainerHeight();
    maxWidth = owner.getContainerWidth();

    if (Settings.getSettings().mcc == null || Settings.getSettings().mnc == null) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String networkOperator = tm.getNetworkOperator();
        if (networkOperator != null && networkOperator.length() >= 6) {
            Settings.getSettings().mcc = networkOperator.substring(0, 3);
            Settings.getSettings().mnc = networkOperator.substring(3);
        }
    }
    mcc = Settings.getSettings().mcc;
    mnc = Settings.getSettings().mnc;

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    connection_type = wifi.isConnected() ? "wifi" : "wan";
    dev_time = "" + System.currentTimeMillis();

    if (owner instanceof InterstitialAdView) {
        // Make string for allowed_sizes
        allowedSizes = "";
        ArrayList<Size> sizes = ((InterstitialAdView) owner).getAllowedSizes();
        for (Size s : sizes) {
            allowedSizes += "" + s.width() + "x" + s.height();
            // If not last size, add a comma
            if (sizes.indexOf(s) != sizes.size() - 1)
                allowedSizes += ",";
        }
    }

    nativeBrowser = owner.getOpensNativeBrowser() ? "1" : "0";

    //Reserve price
    reserve = owner.getReserve();
    if (reserve <= 0) {
        this.psa = owner.shouldServePSAs ? "1" : "0";
    } else {
        this.psa = "0";
    }

    age = owner.getAge();
    if (owner.getGender() != null) {
        if (owner.getGender() == AdView.GENDER.MALE) {
            gender = "m";
        } else if (owner.getGender() == AdView.GENDER.FEMALE) {
            gender = "f";
        } else {
            gender = null;
        }
    }
    customKeywords = owner.getCustomKeywords();

    mcc = Settings.getSettings().mcc;
    mnc = Settings.getSettings().mnc;
    language = Settings.getSettings().language;
}