Example usage for android.content Context WIFI_SERVICE

List of usage examples for android.content Context WIFI_SERVICE

Introduction

In this page you can find the example usage for android.content Context WIFI_SERVICE.

Prototype

String WIFI_SERVICE

To view the source code for android.content Context WIFI_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.net.wifi.WifiManager for handling management of Wi-Fi access.

Usage

From source file:nacho.tfg.blepresencetracker.MyFirebaseInstanceIDService.java

/**
 * Persist token to third-party servers.
 *
 * Modify this method to associate the user's FCM InstanceID token with any server-side account
 * maintained by your application./*from  w  w w  . ja v a  2 s.c o m*/
 *
 * @param token The new token.
 */
private void sendRegistrationToServer(String token) {
    // Add custom implementation, as needed.
    Intent intent = new Intent(ACTION_SHOW_TOKEN);
    intent.putExtra("token", token);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

    AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Boolean doInBackground(String... params) {
            String data = params[0];
            String ip = "192.168.4.1";
            int port = 7777;
            try {
                Socket socket = new Socket(ip, port);
                while (!socket.isConnected()) {

                }

                OutputStream out = socket.getOutputStream();
                PrintWriter output = new PrintWriter(out);

                output.println(data);
                output.flush();
                out.close();
                output.close();

                socket.close();
            } catch (SocketException e) {
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            if (result) {
                SharedPreferences settings = PreferenceManager
                        .getDefaultSharedPreferences(MyFirebaseInstanceIDService.this);
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean(getString(R.string.registration_id_sent), true);
                editor.commit();
            } else {
                SharedPreferences settings = PreferenceManager
                        .getDefaultSharedPreferences(MyFirebaseInstanceIDService.this);
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean(getString(R.string.registration_id_sent), false);
                editor.commit();
            }
        }
    };

    // Change wifi network to "NodeMCU WiFi"

    String ssid = "";
    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    if (WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState()) == NetworkInfo.DetailedState.CONNECTED) {
        ssid = wifiInfo.getSSID();
    }

    if (!ssid.equals("NodeMCU WiFi")) {
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), getString(R.string.toast_connect_NodeMCU),
                        Toast.LENGTH_LONG).show();

            }
        });

    }
}

From source file:com.zegoggles.smssync.service.ServiceBase.java

protected WifiManager getWifiManager() {
    return (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
}

From source file:com.vinexs.tool.NetworkManager.java

public static String getMacAddress(Context context) {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WifiInfo wInfo = wifiManager.getConnectionInfo();
    return wInfo.getMacAddress();
}

From source file:eu.faircode.netguard.Util.java

public static String getWifiSSID(Context context) {
    WifiManager wm = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    String ssid = (wm == null ? null : wm.getConnectionInfo().getSSID());
    return (ssid == null ? "NULL" : ssid);
}

From source file:de.taxilof.UulmLoginAgent.java

/**
 * fetch the ssid of the wifi network//from   ww w .j ava 2  s  . c o m
 * 
 * @return ip
 */
private String getSsid() {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    String ssid = null;
    if (wifiInfo != null) {
        ssid = wifiInfo.getSSID();
    }
    if (ssid != null) {
        return ssid.replace("\"", ""); // because .getSSID() sucks...
    } else {
        return "";
    }
}

From source file:com.wiyun.engine.network.Network.java

static boolean isWifiConnected() {
    Context context = Director.getInstance().getContext();
    if (context.checkCallingOrSelfPermission(
            android.Manifest.permission.ACCESS_WIFI_STATE) == PackageManager.PERMISSION_GRANTED) {
        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (wm != null) {
            WifiInfo info = wm.getConnectionInfo();
            return info != null && info.getSupplicantState() == SupplicantState.COMPLETED;
        } else {/*from  w w w. j ava2  s.  c  o m*/
            return false;
        }
    } else {
        Log.w("libwiengine", "you need add ACCESS_WIFI_STATE permission");
        return false;
    }
}

From source file:be.ppareit.swiftp.gui.PreferenceFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    Resources resources = getResources();

    TwoStatePreference runningPref = findPref("running_switch");
    updateRunningState();/*w  w  w  .j a va2  s  .  c  o  m*/
    runningPref.setOnPreferenceChangeListener((preference, newValue) -> {
        if ((Boolean) newValue) {
            startServer();
        } else {
            stopServer();
        }
        return true;
    });

    PreferenceScreen prefScreen = findPref("preference_screen");
    Preference marketVersionPref = findPref("market_version");
    marketVersionPref.setOnPreferenceClickListener(preference -> {
        // start the market at our application
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setData(Uri.parse("market://details?id=be.ppareit.swiftp"));
        try {
            // this can fail if there is no market installed
            startActivity(intent);
        } catch (Exception e) {
            Cat.e("Failed to launch the market.");
            e.printStackTrace();
        }
        return false;
    });
    if (!App.isFreeVersion()) {
        prefScreen.removePreference(marketVersionPref);
    }

    updateLoginInfo();

    EditTextPreference usernamePref = findPref("username");
    usernamePref.setOnPreferenceChangeListener((preference, newValue) -> {
        String newUsername = (String) newValue;
        if (preference.getSummary().equals(newUsername))
            return false;
        if (!newUsername.matches("[a-zA-Z0-9]+")) {
            Toast.makeText(getActivity(), R.string.username_validation_error, Toast.LENGTH_LONG).show();
            return false;
        }
        stopServer();
        return true;
    });

    mPassWordPref = findPref("password");
    mPassWordPref.setOnPreferenceChangeListener((preference, newValue) -> {
        stopServer();
        return true;
    });
    mAutoconnectListPref = findPref("autoconnect_preference");
    mAutoconnectListPref.setOnPopulateListener(pref -> {
        Cat.d("autoconnect populate listener");

        WifiManager wifiManager = (WifiManager) getActivity().getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
        if (configs == null) {
            Cat.e("Unable to receive wifi configurations, bark at user and bail");
            Toast.makeText(getActivity(), R.string.autoconnect_error_enable_wifi_for_access_points,
                    Toast.LENGTH_LONG).show();
            return;
        }
        CharSequence[] ssids = new CharSequence[configs.size()];
        CharSequence[] niceSsids = new CharSequence[configs.size()];
        for (int i = 0; i < configs.size(); ++i) {
            ssids[i] = configs.get(i).SSID;
            String ssid = configs.get(i).SSID;
            if (ssid.length() > 2 && ssid.startsWith("\"") && ssid.endsWith("\"")) {
                ssid = ssid.substring(1, ssid.length() - 1);
            }
            niceSsids[i] = ssid;
        }
        pref.setEntries(niceSsids);
        pref.setEntryValues(ssids);
    });
    mAutoconnectListPref.setOnPreferenceClickListener(preference -> {
        Cat.d("Clicked");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                        Manifest.permission.ACCESS_COARSE_LOCATION)) {
                    new AlertDialog.Builder(getContext()).setTitle(R.string.request_coarse_location_dlg_title)
                            .setMessage(R.string.request_coarse_location_dlg_message)
                            .setPositiveButton(android.R.string.ok, (dialog, which) -> {
                                requestPermissions(new String[] { Manifest.permission.ACCESS_COARSE_LOCATION },
                                        ACCESS_COARSE_LOCATION_REQUEST_CODE);
                            }).setOnCancelListener(dialog -> {
                                mAutoconnectListPref.getDialog().cancel();
                            }).create().show();
                } else {
                    requestPermissions(new String[] { Manifest.permission.ACCESS_COARSE_LOCATION },
                            ACCESS_COARSE_LOCATION_REQUEST_CODE);
                }
            }
        }
        return false;
    });

    EditTextPreference portnum_pref = findPref("portNum");
    portnum_pref.setSummary(sp.getString("portNum", resources.getString(R.string.portnumber_default)));
    portnum_pref.setOnPreferenceChangeListener((preference, newValue) -> {
        String newPortnumString = (String) newValue;
        if (preference.getSummary().equals(newPortnumString))
            return false;
        int portnum = 0;
        try {
            portnum = Integer.parseInt(newPortnumString);
        } catch (Exception e) {
            Cat.d("Error parsing port number! Moving on...");
        }
        if (portnum <= 0 || 65535 < portnum) {
            Toast.makeText(getActivity(), R.string.port_validation_error, Toast.LENGTH_LONG).show();
            return false;
        }
        preference.setSummary(newPortnumString);
        stopServer();
        return true;
    });

    Preference chroot_pref = findPref("chrootDir");
    chroot_pref.setSummary(FsSettings.getChrootDirAsString());
    chroot_pref.setOnPreferenceClickListener(preference -> {
        AlertDialog folderPicker = new FolderPickerDialogBuilder(getActivity(), FsSettings.getChrootDir())
                .setSelectedButton(R.string.select, path -> {
                    if (preference.getSummary().equals(path))
                        return;
                    if (!FsSettings.setChrootDir(path))
                        return;
                    // TODO: this is a hotfix, create correct resources, improve UI/UX
                    final File root = new File(path);
                    if (!root.canRead()) {
                        Toast.makeText(getActivity(), "Notice that we can't read/write in this folder.",
                                Toast.LENGTH_LONG).show();
                    } else if (!root.canWrite()) {
                        Toast.makeText(getActivity(),
                                "Notice that we can't write in this folder, reading will work. Writing in sub folders might work.",
                                Toast.LENGTH_LONG).show();
                    }

                    preference.setSummary(path);
                    stopServer();
                }).setNegativeButton(R.string.cancel, null).create();
        folderPicker.show();
        return true;
    });

    final CheckBoxPreference wakelock_pref = findPref("stayAwake");
    wakelock_pref.setOnPreferenceChangeListener((preference, newValue) -> {
        stopServer();
        return true;
    });

    final CheckBoxPreference writeExternalStorage_pref = findPref("writeExternalStorage");
    String externalStorageUri = FsSettings.getExternalStorageUri();
    if (externalStorageUri == null) {
        writeExternalStorage_pref.setChecked(false);
    }
    writeExternalStorage_pref.setOnPreferenceChangeListener((preference, newValue) -> {
        if ((boolean) newValue) {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
            startActivityForResult(intent, ACTION_OPEN_DOCUMENT_TREE);
            return false;
        } else {
            FsSettings.setExternalStorageUri(null);
            return true;
        }
    });

    ListPreference theme = findPref("theme");
    theme.setSummary(theme.getEntry());
    theme.setOnPreferenceChangeListener((preference, newValue) -> {
        theme.setSummary(theme.getEntry());
        getActivity().recreate();
        return true;
    });

    Preference help = findPref("help");
    help.setOnPreferenceClickListener(preference -> {
        Cat.v("On preference help clicked");
        Context context = getActivity();
        AlertDialog ad = new AlertDialog.Builder(context).setTitle(R.string.help_dlg_title)
                .setMessage(R.string.help_dlg_message).setPositiveButton(android.R.string.ok, null).create();
        ad.show();
        Linkify.addLinks((TextView) ad.findViewById(android.R.id.message), Linkify.ALL);
        return true;
    });

    Preference about = findPref("about");
    about.setOnPreferenceClickListener(preference -> {
        startActivity(new Intent(getActivity(), AboutActivity.class));
        return true;
    });

}

From source file:fm.feed.android.SampleApp.fragment.TestFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    mBtnTune.setOnClickListener(tune);/*from  w w w .ja va 2  s  .co  m*/
    mBtnPlay.setOnClickListener(play);
    mBtnPause.setOnClickListener(pause);
    mBtnSkip.setOnClickListener(skip);
    mBtnLike.setOnClickListener(like);
    mBtnUnlike.setOnClickListener(unlike);
    mBtnDislike.setOnClickListener(dislike);
    mBtnHistory.setOnClickListener(history);

    mStationsView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);

    mBtnToggleWifi.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ConnectivityManager cm = (ConnectivityManager) getActivity()
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

            WifiManager wifi = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
            wifi.setWifiEnabled(!isConnected); // true or false to activate/deactivate wifi

            mBtnToggleWifi.setText(!isConnected ? "Wifi ON" : "Wifi OFF");
        }
    });

    resetTrackInfo();

    if (mPlayer.hasPlay()) {
        updateTrackInfo(mPlayer.getPlay());
    }
    if (mPlayer.hasStationList()) {
        updateStations(mPlayer.getStationList());
    }
}

From source file:com.prey.PreyPhone.java

private void updateWifi() {
    wifi = new Wifi();
    try {//from   www.ja  va2  s .c o  m
        WifiManager wifiMgr = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiMgr.getConnectionInfo();

        wifi.setWifiEnabled(wifiMgr.isWifiEnabled());

        int ipAddress = wifiInfo.getIpAddress();
        wifi.setIpAddress(formatterIp(ipAddress));
        wifi.setMacAddress(wifiInfo.getMacAddress());
        DhcpInfo dhcpInfo = wifiMgr.getDhcpInfo();
        wifi.setNetmask(formatterIp(dhcpInfo.netmask));
        wifi.setGatewayIp(formatterIp(dhcpInfo.serverAddress));
        if (ipAddress != 0) {
            wifi.setInterfaceType("Wireless");
        } else {
            if (PreyConnectivityManager.getInstance(ctx).isMobileConnected()) {
                wifi.setInterfaceType("Mobile");
            } else {
                wifi.setInterfaceType("");
            }
        }
        wifi.setName("eth0");
        String ssid = wifiInfo.getSSID();
        try {
            ssid = ssid.replaceAll("\"", "");
        } catch (Exception e) {

        }
        wifi.setSsid(ssid);

        for (int i = 0; listWifi != null && i < listWifi.size(); i++) {
            Wifi _wifi = listWifi.get(i);
            ssid = _wifi.getSsid();
            try {
                ssid = ssid.replaceAll("\"", "");
            } catch (Exception e) {

            }
            if (ssid.equals(wifi.getSsid())) {
                wifi.setSecurity(_wifi.getSecurity());
                wifi.setSignalStrength(_wifi.getSignalStrength());
                wifi.setChannel(_wifi.getChannel());
                break;
            }
        }
    } catch (Exception e) {
    }
}

From source file:net.fluidnexus.FluidNexusAndroid.services.NexusServiceThread.java

/**
 * Constructor for the thread that does nexus
 *//*w  w  w  . j  a v  a  2s.  c o m*/
public NexusServiceThread(Context ctx, ArrayList<Messenger> givenClients, String gkey, String gsecret,
        String gtoken, String gtoken_secret) {

    super(ctx, givenClients);
    key = gkey;
    secret = gsecret;
    token = gtoken;
    token_secret = gtoken_secret;

    setName("NexusServiceThread");
    wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

    setServiceState(STATE_NONE);
}