Example usage for android.net ConnectivityManager TYPE_WIFI

List of usage examples for android.net ConnectivityManager TYPE_WIFI

Introduction

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

Prototype

int TYPE_WIFI

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

Click Source Link

Document

A WIFI data connection.

Usage

From source file:com.tonyodev.fetch.Utils.java

static boolean isOnWiFi(Context context) {

    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();

    if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
        return activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI;
    }/*from  w ww  .j a  v  a2  s.c  om*/

    return false;
}

From source file:devbox.com.br.minercompanion.ProfileActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);


    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (networkInfo.isConnected()) {
        final WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
        final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
        if (connectionInfo != null && !(connectionInfo.getSSID().equals(""))) {
            //if (connectionInfo != null && !StringUtil.isBlank(connectionInfo.getSSID())) {
            routerName = connectionInfo.getSSID();
        }/*from  w ww.java 2s .  co  m*/
    }

    sensorCounter = new SensorCounter(3000, 3000);
    sensorCounter.start();

    Intent intent = getIntent();

    if(intent != null) {
        matricula = intent.getStringExtra("MATRICULA");

        TextView textView = (TextView) findViewById(R.id.textView);

        textView.setText("Matrcula: " + matricula);

        sensors = new Sensors(matricula, routerName.replace("\"",""));
    }

    /* Get a SensorManager instance */
    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

    ListView listView = (ListView) findViewById(R.id.listView);
    profileListAdapter = new ProfileListAdapter(this, strings);
    listView.setAdapter(profileListAdapter);

    profileListAdapter.addItem("Conectado ao servidor!");
}

From source file:org.openhab.habdroid.ui.OpenHABStartupActivity.java

private void initPage() {

    if (!tryManualUrl()) {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
                Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetworkInfo != null) {
            Log.i(TAG, "Network is connected");
            if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI
                    || activeNetworkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
                Log.i(TAG, "Network is WiFi or Ethernet");
                AsyncServiceResolver serviceResolver = new AsyncServiceResolver(this, openHABServiceType);
                if (!this.isFinishing())
                    progressDialog = ProgressDialog.show(OpenHABStartupActivity.this, "",
                            "Discovering openHAB. Please wait...", true);
                serviceResolver.start();
            } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                Log.i(TAG, "Network is Mobile (" + activeNetworkInfo.getSubtypeName() + ")");
                onAlternativeUrl();//from   ww w .j  a  va2s.  c o m
            } else {
                Log.i(TAG, "Network type (" + activeNetworkInfo.getTypeName() + ") is unsupported");
            }
        } else {
            Log.i(TAG, "Network is not available");
            Toast.makeText(getApplicationContext(), "@string/error_network_not_available", Toast.LENGTH_LONG)
                    .show();
        }
    }

}

From source file:com.nearnotes.NoteLocation.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the Builder class for convenient dialog construction
    Bundle extras = getArguments();// w w w  .jav  a2  s . c  o  m
    mTypeFrag = extras.getInt("TypeFrag");

    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
    Boolean gpsPref = sharedPref.getBoolean("pref_key_ignore_gps", false);
    mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    mCriteria = new Criteria();
    if (gpsPref) {
        mCriteria.setPowerRequirement(Criteria.POWER_HIGH);
    } else
        mCriteria.setPowerRequirement(Criteria.POWER_MEDIUM);
    mProvider = mLocationManager.getBestProvider(mCriteria, true);
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    boolean oldApi = false;
    int locationMode = 4;
    Log.e("mProvider", mProvider);

    ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    boolean networkAvailable = true;

    TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
    boolean networkType = true;
    if (tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_UNKNOWN && !networkInfo.isConnected()) {
        networkType = false;
    }

    Log.d("Phone state before if statement", "Phone State: " + mServiceState);
    Log.e("network isavailable", String.valueOf(networkInfo.isAvailable()));
    if (!networkType || !mLocationManager.isProviderEnabled("network")) {
        networkAvailable = false;
    }

    try {
        Log.e("Location_mode", String.valueOf(
                Settings.Secure.getInt(getActivity().getContentResolver(), Settings.Secure.LOCATION_MODE)));
        locationMode = Settings.Secure.getInt(getActivity().getContentResolver(),
                Settings.Secure.LOCATION_MODE);
    } catch (SettingNotFoundException e) {
        oldApi = true;
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if ((oldApi && mProvider.matches("passive")) || locationMode == LOCATION_MODE_OFF || (!networkAvailable
            && (mProvider.matches("network") || (!gpsPref && mProvider.matches("gps"))))) {
        builder.setTitle(getString(R.string.dialog_location_no_location_services_title));
        builder.setMessage(getString(R.string.dialog_location_no_location_services_message));
        builder.setNeutralButton(R.string.dialog_location_button_settings, noNetworkButton);
        mAbortRequest = true;
    } else if ((oldApi && mProvider.matches("gps") && gpsPref) || (mProvider.matches("gps") && gpsPref
            && (locationMode == LOCATION_MODE_SENSORS_ONLY || locationMode == LOCATION_MODE_HIGH_ACCURACY))) {
        if (mTypeFrag == NOTE_EDIT) {
            builder.setTitle(getString(R.string.dialog_location_finding_note_gps));
        } else if (mTypeFrag == NOTE_LIST) {
            builder.setTitle(getString(R.string.dialog_location_updating_note_gps));
        }
        if (locationMode == LOCATION_MODE_SENSORS_ONLY || (oldApi && mProvider.matches("gps"))
                || !networkAvailable) {
            builder.setMessage(getString(R.string.dialog_location_only_gps_message));
            builder.setNeutralButton(R.string.dialog_location_button_settings, noNetworkButton);

        } else
            builder.setPositiveButton(R.string.dialog_location_use_network, null);

        builder.setView(getActivity().getLayoutInflater().inflate(R.layout.dialogue_location, null));

    } else if ((oldApi && mProvider.matches("network")) || (mProvider.matches("network")
            && (locationMode == LOCATION_MODE_BATTERY_SAVING || locationMode == LOCATION_MODE_HIGH_ACCURACY))) {
        builder.setView(getActivity().getLayoutInflater().inflate(R.layout.dialogue_location, null));
        if (mTypeFrag == NOTE_EDIT) {
            builder.setTitle(getString(R.string.dialog_location_finding_note_network));
        } else if (mTypeFrag == NOTE_LIST) {
            builder.setTitle(getString(R.string.dialog_location_updating_note_network));
        }

    }
    builder.setNegativeButton(R.string.cancel, cancelListener);
    // Create the AlertDialog object and return it

    // builder.create();

    builder.setOnKeyListener(new DialogInterface.OnKeyListener() {

        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                mCallback.onLocationFound(null, mTypeFrag);
                mLocationManager.removeUpdates(NoteLocation.this);
                Toast.makeText(getActivity(), "Location request cancelled", Toast.LENGTH_SHORT).show();
                dialog.cancel();
                return true;
            }

            return false;
        }
    });

    mRealDialog = builder.create();
    // final LocationListener getFragment() = this.;

    mRealDialog.setOnShowListener(usingNetwork);
    mRealDialog.setCanceledOnTouchOutside(false);
    // mRealDialog.setCancelable(false);
    return mRealDialog;

}

From source file:org.ohthehumanity.carrie.CarrieActivity.java

/** Called when the activity is first created. */
@Override//  w  ww.  j ava 2 s.  com
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mServerName = "";
    setContentView(R.layout.main);

    // instantiate our preferences backend
    mPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    // set callback function when settings change
    mPreferences.registerOnSharedPreferenceChangeListener(this);

    if (mPreferences.getString("server", null) == null) {
        setStatus("Server not set");
    } else if (mPreferences.getString("port", null) == null) {
        setStatus("Port not configured");
    }

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm.getActiveNetworkInfo().getType() != ConnectivityManager.TYPE_WIFI) {

        AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
        dlgAlert.setTitle("WiFi not active");
        dlgAlert.setMessage(
                "This application is usually used on a local network over a WiFi. Open WiFi settings?");
        dlgAlert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                case DialogInterface.BUTTON_POSITIVE:
                    //Yes button clicked
                    final Intent intent = new Intent(Intent.ACTION_MAIN, null);
                    intent.addCategory(Intent.CATEGORY_LAUNCHER);
                    final ComponentName cn = new ComponentName("com.android.settings",
                            "com.android.settings.wifi.WifiSettings");
                    intent.setComponent(cn);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    break;

                case DialogInterface.BUTTON_NEGATIVE:
                    //Log.i(TAG, "Not opening wifi");
                    //No button clicked
                    break;
                }
            }
        });

        dlgAlert.setNegativeButton("No", null);
        dlgAlert.setCancelable(true);
        dlgAlert.create().show();
    }

    updateTitle();
    updateSkipLabels();
    updateServerName();
}

From source file:com.dmbstream.android.util.Util.java

public static boolean isWifiConnected(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    return wifi != null && wifi.isConnected();
}

From source file:osu.crowd_ml.BackgroundDataSend.java

private boolean isDataConnected() {
    try {//  www .  j  a va  2  s . com
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();

        //TODO: See if making sure it's not a metered connection would be better? Consult: https://developer.android.com/reference/android/net/ConnectivityManager.html#isActiveNetworkMetered
        if (info.getType() == ConnectivityManager.TYPE_WIFI) {
            return cm.getActiveNetworkInfo().isConnectedOrConnecting();
        } else {
            return false;
        }
    } catch (Exception e) {
        return false;
    }
}

From source file:com.licubeclub.zionhs.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Calendar Cal = Calendar.getInstance();
    AMorPM = Cal.get(Calendar.AM_PM);
    DAYofWEEK = Cal.get(Calendar.DAY_OF_WEEK);
    DAYofMONTH = Cal.get(Calendar.DAY_OF_MONTH);

    Log.d("DAYofMONTH", String.valueOf(Cal.get(Calendar.DAY_OF_MONTH)));

    cManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    mobile = cManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    wifi = cManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    setContentView(R.layout.activity_main);

    /*/*  www.  ja v  a2s.com*/
    * TODO - ?    (/?/?)
    * */
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    MEAL = (TextView) findViewById(R.id.mealdata);
    SCHEDULE = (TextView) findViewById(R.id.schedata);
    NOTIPARNTS = (TextView) findViewById(R.id.notiparentdata);
    NOTICES = (TextView) findViewById(R.id.notidata);

    View notices = findViewById(R.id.notices);
    View meal = findViewById(R.id.meal);
    View schedule = findViewById(R.id.schedule);
    View notices_parents = findViewById(R.id.notices_parents);

    notices.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent0 = new Intent(MainActivity.this, Notices.class);
            intent0.putExtra("url",
                    "http://www.zion.hs.kr/main.php?menugrp=110100&master=bbs&act=list&master_sid=58");
            intent0.putExtra("title", getResources().getString(R.string.notices));
            startActivity(intent0);
        }
    });

    meal.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, MealActivity.class);
            startActivity(intent);
        }
    });

    schedule.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, Schedule.class);
            startActivity(intent);
        }
    });

    notices_parents.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, Notices.class);
            intent.putExtra("url",
                    "http://www.zion.hs.kr/main.php?menugrp=110200&master=bbs&act=list&master_sid=59");
            intent.putExtra("title", getResources().getString(R.string.title_activity_notices__parents));
            startActivity(intent);
        }
    });

    //Navigation Drawer
    DrawerArray = new ArrayList<String>();
    DrawerArray.add(getString(R.string.meal));
    DrawerArray.add(getString(R.string.schedule));
    DrawerArray.add(getString(R.string.title_activity_notices__parents));
    DrawerArray.add(getString(R.string.notices));
    DrawerArray.add(getString(R.string.schoolintro));
    DrawerArray.add(getString(R.string.schoolinfo));
    DrawerArray.add(getString(R.string.appsettings_apinfo_title));

    IconArray = new ArrayList<Drawable>();
    IconArray.add(getResources().getDrawable(R.drawable.ic_meal));
    IconArray.add(getResources().getDrawable(R.drawable.ic_event_black_24dp));
    IconArray.add(getResources().getDrawable(R.drawable.ic_insert_drive_file_black_24dp));
    IconArray.add(getResources().getDrawable(R.drawable.ic_speaker_notes_black_24dp));
    IconArray.add(getResources().getDrawable(R.drawable.ic_intro));
    IconArray.add(getResources().getDrawable(R.drawable.ic_school));
    IconArray.add(getResources().getDrawable(R.drawable.ic_info_black_24dp));

    NavigationDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    DrawerList = (ListView) findViewById(R.id.left_drawer);

    Adapter = new DrawerListAdapter(this, DrawerArray, IconArray);
    DrawerList.setAdapter(Adapter);

    //Listen for Navigation Drawer State
    DrawerToggle = new ActionBarDrawerToggle(this, NavigationDrawer, R.string.drawer_open,
            R.string.drawer_close) {
        /** Called when a drawer has settled in a completely closed state. */
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
            isNavDrawerOpen = false;
        }

        /** Called when a drawer has settled in a completely open state. */
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            //                getSupportActionBar().setBackgroundDrawable(Darkblue);
            isNavDrawerOpen = true;
        }

    };
    NavigationDrawer.setDrawerListener(DrawerToggle);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    //Drawer Item Click action
    DrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position) {
            case 0:
                startActivity(new Intent(MainActivity.this, MealActivity.class));
                break;
            case 1:
                startActivity(new Intent(MainActivity.this, Schedule.class));
                break;
            case 2:
                Intent intent = new Intent(MainActivity.this, Notices.class);
                intent.putExtra("url",
                        "http://www.zion.hs.kr/main.php?menugrp=110200&master=bbs&act=list&master_sid=59");
                intent.putExtra("title", getResources().getString(R.string.title_activity_notices__parents));
                startActivity(intent);
                break;
            case 3:
                Intent intent0 = new Intent(MainActivity.this, Notices.class);
                intent0.putExtra("url",
                        "http://www.zion.hs.kr/main.php?menugrp=110100&master=bbs&act=list&master_sid=58");
                intent0.putExtra("title", getResources().getString(R.string.notices));
                startActivity(intent0);
                break;
            case 4:
                startActivity(new Intent(MainActivity.this, Schoolintro.class));
                break;
            case 5:
                startActivity(new Intent(MainActivity.this, Schoolinfo.class));
                break;
            case 6:
                startActivity(new Intent(MainActivity.this, Appinfo.class));
                break;
            }
        }
    });

    SRL = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
    if (mobile.isConnected() || wifi.isConnected()) {
        networkTask();
    } else {

        Toast toast = Toast.makeText(getApplicationContext(),
                getResources().getString(R.string.network_connection_warning), Toast.LENGTH_LONG);
        toast.setGravity(Gravity.BOTTOM, 0, 0);
        toast.show();
    }
    SRL.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            cManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            mobile = cManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            wifi = cManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (mobile.isConnected() || wifi.isConnected()) {
                networkTask();
            } else {

                Toast toast = Toast.makeText(getApplicationContext(),
                        getResources().getString(R.string.network_connection_warning), Toast.LENGTH_LONG);
                toast.setGravity(Gravity.BOTTOM, 0, 0);
                toast.show();
                SRL.setRefreshing(false);
            }
        }
    });

}

From source file:org.exobel.routerkeygen.AutoConnectService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent == null) {
        stopSelf();/*from  www.j ava  2s . 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:de.geeksfactory.opacclient.reminder.ReminderCheckService.java

@Override
public int onStartCommand(Intent intent, int flags, int startid) {
    if (ACTION_SNOOZE.equals(intent.getAction())) {
        Intent i = new Intent(ReminderCheckService.this, ReminderAlarmReceiver.class);
        PendingIntent sender = PendingIntent.getBroadcast(ReminderCheckService.this,
                OpacClient.BROADCAST_REMINDER, i, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        Log.i("ReminderCheckService", "Opac App Service: Quick repeat");
        // Run again in 1 day
        am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (1000 * 3600 * 24), sender);

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancel(OpacClient.NOTIF_ID);
    } else {//from   w  ww  .jav  a2  s.  c  om
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(ReminderCheckService.this);
        notification_on = sp.getBoolean("notification_service", false);
        long waittime = (1000 * 3600 * 5);
        boolean executed = false;

        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null) {
            if (!sp.getBoolean("notification_service_wifionly", false)
                    || networkInfo.getType() == ConnectivityManager.TYPE_WIFI
                    || networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
                executed = true;
                new CheckTask().execute();
            } else {
                waittime = (1000 * 1800);
            }
        } else {
            waittime = (1000 * 1800);
        }

        if (!notification_on) {
            waittime = (1000 * 3600 * 12);
        }

        Intent i = new Intent(ReminderCheckService.this, ReminderAlarmReceiver.class);
        PendingIntent sender = PendingIntent.getBroadcast(ReminderCheckService.this,
                OpacClient.BROADCAST_REMINDER, i, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + waittime, sender);

        if (!executed) {
            stopSelf();
        }
    }

    return START_NOT_STICKY;
}