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:com.swisscom.safeconnect.fragment.InfoFragment.java

private String getConnectedSSID() {
    String ssid = null;/*from   w w w.j av a2  s  .c o m*/
    ConnectivityManager connManager = (ConnectivityManager) getActivity()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (networkInfo.isConnected()) {
        final WifiManager wifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
        final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
        if (connectionInfo != null && !TextUtils.isEmpty(connectionInfo.getSSID())) {
            ssid = connectionInfo.getSSID();
        }
    }
    return ssid;
}

From source file:com.jesjimher.bicipalma.MesProperesActivity.java

/** Called when the activity is first created. */
@Override/*from   w w  w. java  2s . c  o m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mesproperes);
    this.prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Si s'ha d'activar el wifi en inici, fer-ho
    WifiManager wm = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
    // Guardar el estado actual para restaurarlo al salir
    this.estatWifi = wm.isWifiEnabled();
    if (prefs.getBoolean("activarWifiPref", false))
        wm.setWifiEnabled(true);

    // Cargamos la versin cacheada de las estaciones
    leerCacheEstaciones();

    actualizarListado();

    // Iniciamos la descarga de las estaciones y su estado desde la web (en un thread aparte)
    descargaEstaciones = new RecuperarEstacionesTask(this);
    descargaEstaciones.execute();

    // Inicialmente se busca por red (ms rpido)
    //       dBuscaUbic=ProgressDialog.show(c, "",getString(R.string.buscandoubica),true,true);
    //        Toast.makeText(getApplicationContext(), "Activando", Toast.LENGTH_SHORT).show();
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    providerCoarse = locationManager.getBestProvider(criteria, true);

    if (providerCoarse == null) {
        Toast.makeText(getApplicationContext(), "No hay forma de posicionarse", Toast.LENGTH_SHORT).show();
        return;
    }
    locationManager.requestLocationUpdates(providerCoarse, 10, 0, (LocationListener) this);

    // Usar ltima ubicacin conocida de red para empezar y recibir futuras actualizaciones
    lBest = locationManager.getLastKnownLocation(providerCoarse);

    // Guardar el inicio de bsqueda de ubicacin para no pasarse de tiempo
    //tIni=new Date().getTime();
    tIni = System.currentTimeMillis();

    // Crear listeners para mostrar estacin en mapa, o abrir men con clic largo
    ListView lv = (ListView) findViewById(R.id.listado);
    lv.setOnItemClickListener((OnItemClickListener) this);
    lv.setOnItemLongClickListener((OnItemLongClickListener) this);
}

From source file:com.harshad.linconnectclient.SettingsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Show changelog if needed
    ChangeLog cl = new ChangeLog(this);
    if (cl.isFirstRun()) {
        cl.getLogDialog().show();//ww w.ja  v  a  2 s. co m
    }
    mWifiManager = (android.net.wifi.WifiManager) getSystemService(android.content.Context.WIFI_SERVICE);
}

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

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

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

            try {
                isWifiAPenabled = (boolean) method.invoke(managerWifi);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();//  w  w w. j av  a 2 s .  com
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

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

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

    if (!isWifiAPenabled) {

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

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

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

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

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

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

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

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

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

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

        }
    });

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

    hometraquad.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

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

}

From source file:ca.farrelltonsolar.classic.MonitorApplication.java

public void onCreate() {
    super.onCreate();

    MonitorApplication.context = getApplicationContext();
    if (Constants.DEVELOPER_MODE) {
        StrictMode.enableDefaults();/*from w  ww. j a  v  a  2  s. c  om*/
    }
    InitializeChargeStateLookup();
    InitializeChargeStateTitleLookup();
    InitializeMessageLookup();
    try {
        configuration = ComplexPreferences.getComplexPreferences(this, null, Context.MODE_PRIVATE);
        chargeControllers = configuration.getObject("devices", ChargeControllers.class);
    } catch (Exception ex) {
        Log.w(getClass().getName(), "getComplexPreferences failed to load");
        chargeControllers = null;
    }
    if (chargeControllers == null) { // save empty collection
        chargeControllers = new ChargeControllers(context);
    }
    if (chargeControllers.uploadToPVOutput()) {
        startService(new Intent(this, PVOutputService.class)); // start PVOutputService intent service
    }
    this.registerActivityLifecycleCallbacks(this);
    bindService(new Intent(this, UDPListener.class), UDPListenerServiceConnection, Context.BIND_AUTO_CREATE);
    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    if (wifi != null) {
        wifiLock = wifi.createWifiLock("ClassicMonitor");
    }
    Log.d(getClass().getName(), "onCreate complete");
}

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

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

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

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

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

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

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

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

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

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

    return true;
}

From source file:cz.babi.android.remoteme.service.ConnectionService.java

@Override
public void onCreate() {
    if (Common.DEBUG)
        Log.d(TAG_CLASS_NAME, "[onCreate]");

    preferences = PreferenceManager.getDefaultSharedPreferences(this);

    /* Lock Wi-Fi, if need so. */
    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "WiFiLockTag");
    if (preferences.getBoolean(getString(R.string.pref_name_keep_wifi_alive), true))
        lockWiFi();//from   w w  w.j  av a2  s.  c o m

    /* Display a notification about us starting. */
    if (preferences.getBoolean(getString(R.string.pref_name_show_notification), true)) {
        showNotification();
    }
}

From source file:com.conferenceengineer.android.iosched.util.WiFiUtils.java

public static boolean isWiFiApConfigured(final Context context) {
    final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    final List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();

    if (configs == null)
        return false;

    // Check for existing APs.
    final String conferenceSSID = String.format("\"%s\"", Config.WIFI_SSID);
    for (WifiConfiguration config : configs) {
        if (conferenceSSID.equalsIgnoreCase(config.SSID))
            return true;
    }//from  ww  w . j a  v a  2  s  . c o m
    return false;
}

From source file:com.smedic.tubtub.BackgroundAudioService.java

@Override
public void onCreate() {
    super.onCreate();
    videoItem = new YouTubeVideo();

    network = new NetworkConf(getApplicationContext());

    mWifiLock = ((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE))
            .createWifiLock(WifiManager.WIFI_MODE_FULL, "tub_wifi_lock");

    mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setOnCompletionListener(this);
    mMediaPlayer.setOnPreparedListener(this);
    mMediaPlayer.setOnErrorListener(this);

    initMediaSessions();/*from   w  w  w  .j a v  a2  s  .c om*/
    initPhoneCallListener();
}

From source file:app.wz.MainActivity.java

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

    self = this;//ww  w .  j  a  v a 2s  .  co  m

    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setProgressBarIndeterminateVisibility(false);

    setContentView(R.layout.layout_main);

    // initialize your android device sensor capabilities
    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

    powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");

    wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    lock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "LockTag");

    prefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());

    textScroll = (ScrollView) findViewById(R.id.textScroll);
    textRead = (TextView) findViewById(R.id.textRead);

    commStatus = (TextView) findViewById(R.id.commStatus);
    pingStatus = (TextView) findViewById(R.id.pingStatus);
    inputCmd = (EditText) findViewById(R.id.inputCmd);
    inputVal = (EditText) findViewById(R.id.inputVal);

    gb = (GlobalApp) getApplication();

    gb.bt = new BluetoothSPP(this);
    bt = gb.bt;
    gb.arduino = new ArduinoFirmata(this, bt);
    arduino = gb.arduino;

    gb.neuro = new NeuroInterface(prefs, gb);

    neuro = gb.neuro;

    if (prefs.getBoolean("autoload", false)) {
        if (neuro.loadWeights(prefs.getString("last_save", ""))) {
            textRead.append("Restored Weights at Step " + neuro.count + "\n");
            textScroll.fullScroll(View.FOCUS_DOWN);
        }
    }

    if (!bt.isBluetoothAvailable()) {
        Toast.makeText(getApplicationContext(), "Bluetooth is not available", Toast.LENGTH_SHORT).show();
        finish();
    }

    bt.setOnDataReceivedListener(new OnDataReceivedListener() {
        public void onDataReceived(byte[] data, String message) {
            gb.lastResponseBT = System.currentTimeMillis();
            arduino.processInput(data);
        }
    });

    bt.setBluetoothConnectionListener(new BluetoothConnectionListener() {
        public void onDeviceDisconnected() {

            haltNeuro();

            commStatus.setText("Status : Not Connected");
            menu.clear();
            getMenuInflater().inflate(R.menu.connection, menu);
        }

        public void onDeviceConnectionFailed() {
            commStatus.setText("Status : Connection Failed");
        }

        public void onDeviceConnected(String name, String address) {
            commStatus.setText("Status : Connected to " + name);
            menu.clear();
            getMenuInflater().inflate(R.menu.disconnection, menu);
        }
    });

    //        bt.setAutoConnectionListener(new BluetoothSPP.AutoConnectionListener() {
    //            public void onNewConnection(String name, String address) {
    //                Log.i("Check", "New Connection - " + name + " - " + address);
    //            }
    //
    //            public void onAutoConnectionStarted() {
    //                Log.i("Check", "Auto connection started");
    //            }
    //        });

    if (!bt.isBluetoothEnabled()) {
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(intent, BluetoothState.REQUEST_ENABLE_BT);
    } else {
        if (!bt.isServiceAvailable()) {
            bt.setupService();
            bt.startService(BluetoothState.DEVICE_ANDROID);
            setup();
        }
    }

    refreshPing.start();
    neuroThread.start();

    new Thread() {
        public void run() {
            while (true) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (neuro.count > neuro.lastDisplay) {
                    neuro.lastDisplay = neuro.count;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (!neuro.halt) {
                                textRead.append(
                                        "P err:  " + (new DecimalFormat("0.000E0")).format(neuro.avg_error)
                                                + "    O err:  "
                                                + (new DecimalFormat("0.000E0")).format(neuro.avg_obj_error)
                                                + "    stp:  " + neuro.count + "\n");

                                textScroll.fullScroll(View.FOCUS_DOWN);
                            }
                        }
                    });
                }
            }
        }
    }.start();

    new Thread() {
        public void run() {
            while (true) {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (textRead.length() > 20000)
                            textRead.setText("");
                    }
                });
            }
        }
    }.start();

}