Java android wifi connect

How to connect wifi in android

I’m new student for android app developing, Currently I did the Android Wifi connection code in order to make the connectivity.The app is showing the available connections but I cannot possible to connect in to specific wifi connections. Below is the one connectivity when i get from searching and i can see lot of these type of connections in my university premises. Ex: capabilities [WPA2-PSK CCMP][WPS][ESS],level:-37,freequency 2412 timestamp: 9103895476 could you please help me to overcome this problem and connect correctly to available connections. Also i have decide to implement Wifi ON/OFF button and didnt have clear idea for this implementation.. Below is my Java code

TextView mainText; WifiManager mainWifi; WifiReceiver receiverWifi; List wifiList; StringBuilder sb = new StringBuilder(); public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_wifi_connections); mainText = (TextView) findViewById(R.id.mainText); // Initiate wifi service manager mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); // Check for wifi is disabled if (mainWifi.isWifiEnabled() == false) < // If wifi disabled then enable it Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show(); mainWifi.setWifiEnabled(true); >// wifi scaned value broadcast receiver receiverWifi = new WifiReceiver(); // Register broadcast receiver // Broacast receiver will automatically call when number of wifi connections changed registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); mainWifi.startScan(); mainText.setText("Starting Scan. "); > public boolean onCreateOptionsMenu(Menu menu) < menu.add(0, 0, 0, "Refresh"); return super.onCreateOptionsMenu(menu); >public boolean onMenuItemSelected(int featureId, MenuItem item) < mainWifi.startScan(); mainText.setText("Starting Scan"); return super.onMenuItemSelected(featureId, item); >protected void onPause() < unregisterReceiver(receiverWifi); super.onPause(); >protected void onResume() < registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); super.onResume(); >// Broadcast receiver class called its receive method // when number of wifi connections changed class WifiReceiver extends BroadcastReceiver < // This method call when number of wifi connections changed public void onReceive(Context c, Intent intent) < sb = new StringBuilder(); wifiList = mainWifi.getScanResults(); sb.append("\n Number Of Wifi connections :"+wifiList.size()+"\n\n"); for(int i = 0; i < wifiList.size(); i++)< sb.append(new Integer(i+1).toString() + ". "); sb.append((wifiList.get(i)).toString()); sb.append("\n\n"); >mainText.setText(sb); > > 

Источник

crearo / WiFiConnector.java

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

package com . tonbo . streamer . network ;
import android . content . Context ;
import android . content . IntentFilter ;
import android . net . NetworkInfo ;
import android . net . wifi . ScanResult ;
import android . net . wifi . WifiConfiguration ;
import android . net . wifi . WifiInfo ;
import android . net . wifi . WifiManager ;
import android . support . annotation . CheckResult ;
import android . util . Log ;
import java . util . ArrayList ;
import java . util . List ;
/**
* Created by rish on 4/8/17.
*/
public class WiFiConnector implements WiFiBroadcastReceiver . WiFiBroadcastListener
private static final String TAG = WiFiConnector . class . getSimpleName ();
public static final String NO_WIFI = quoted ( «» );
private Context mContext ;
private boolean mIsWifiBroadcastRegistered ;
private IntentFilter mWifiIntentFilter ;
private WifiManager mWifiManager ;
private WiFiBroadcastReceiver mWiFiBroadcastReceiver ;
private WiFiConnectorListener mWifiConnectorListener ;
public WiFiConnector ( Context context , WiFiConnectorListener wifiConnectorListener )
mContext = context ;
mWifiIntentFilter = new IntentFilter ();
mWifiIntentFilter . addAction ( WifiManager . NETWORK_STATE_CHANGED_ACTION );
mWifiIntentFilter . addAction ( WifiManager . RSSI_CHANGED_ACTION );
mWifiIntentFilter . addAction ( WifiManager . RSSI_CHANGED_ACTION );
mWifiIntentFilter . addAction ( WifiManager . SCAN_RESULTS_AVAILABLE_ACTION );
mWifiManager = ( WifiManager ) context . getSystemService ( Context . WIFI_SERVICE );
if ( mWiFiBroadcastReceiver == null )
this . mWiFiBroadcastReceiver = new WiFiBroadcastReceiver ();
mWiFiBroadcastReceiver . setOnWiFiBroadcastListener ( this );
mWifiConnectorListener = wifiConnectorListener ;
>
public NetworkInfo . DetailedState connectToWiFi ( int securityType , String ssid , String key )
Log . d ( TAG , «connectToWiFi() called with: securityType = [» + securityType + «], ssid = [» + ssid + «], key = [» + key + «]» );
/* Check if already connected to that wifi */
String currentSsid = getActiveConnection (). getSSID ();
Log . d ( TAG , «Current Ssid » + currentSsid );
NetworkInfo . DetailedState currentState = WifiInfo . getDetailedStateOf ( getActiveConnection (). getSupplicantState ()); //todo check this
if ( currentState == NetworkInfo . DetailedState . CONNECTED && currentSsid . equals ( quoted ( ssid )))
Log . d ( TAG , «Already connected» );
mWifiConnectorListener . onWiFiStateUpdate ( getActiveConnection (), NetworkInfo . DetailedState . CONNECTED );
return NetworkInfo . DetailedState . CONNECTED ;
>
int highestPriorityNumber = 0 ;
WifiConfiguration selectedConfig = null ;
/* Check if not connected but has connected to that wifi in the past */
for ( WifiConfiguration config : mWifiManager . getConfiguredNetworks ())
if ( config . priority > highestPriorityNumber ) highestPriorityNumber = config . priority ;
if ( config . SSID . equals ( quoted ( ssid )) && config . allowedKeyManagement . get ( securityType ))
Log . d ( TAG , «Saved preshared key is » + config . preSharedKey );
if ( securityType == WifiConfiguration . KeyMgmt . WPA_PSK
&& config . preSharedKey != null && config . preSharedKey . equals ( key ))
selectedConfig = config ;
else if ( securityType == WifiConfiguration . KeyMgmt . NONE )
selectedConfig = config ;
>
>
if ( selectedConfig != null )
selectedConfig . priority = highestPriorityNumber + 1 ;
mWifiManager . updateNetwork ( selectedConfig );
// mWifiManager.disconnect(); /* disconnect from whichever wifi you’re connected to */
mWifiManager . enableNetwork ( selectedConfig . networkId , true );
mWifiManager . reconnect ();
Log . d ( TAG , «Connection exists in past, enabling and connecting priority = » + highestPriorityNumber );
return NetworkInfo . DetailedState . CONNECTING ;
>
/* Make new connection */
WifiConfiguration config = new WifiConfiguration ();
config . SSID = quoted ( ssid );
config . priority = highestPriorityNumber + 1 ;
config . status = WifiConfiguration . Status . ENABLED ;
if ( securityType == WifiConfiguration . KeyMgmt . WPA_PSK )
config . preSharedKey = quoted ( key );
config . allowedKeyManagement . set ( WifiConfiguration . KeyMgmt . WPA_PSK );
config . allowedGroupCiphers . set ( WifiConfiguration . GroupCipher . TKIP );
config . allowedGroupCiphers . set ( WifiConfiguration . GroupCipher . CCMP );
config . allowedPairwiseCiphers . set ( WifiConfiguration . PairwiseCipher . TKIP );
config . allowedPairwiseCiphers . set ( WifiConfiguration . PairwiseCipher . CCMP );
config . allowedProtocols . set ( WifiConfiguration . Protocol . RSN );
config . allowedProtocols . set ( WifiConfiguration . Protocol . WPA );
> else
config . allowedKeyManagement . set ( WifiConfiguration . KeyMgmt . NONE );
>
Log . d ( TAG , «Attempting new wifi connection, setting priority number to, connecting » + config . priority );
int netId = mWifiManager . addNetwork ( config );
// mWifiManager.disconnect(); /* disconnect from whichever wifi you’re connected to */
mWifiManager . enableNetwork ( netId , true );
mWifiManager . reconnect (); // todo?
return NetworkInfo . DetailedState . CONNECTING ;
>
@ CheckResult
public boolean startScan ()
return mWifiManager . startScan ();
>
public WifiInfo getActiveConnection ()
WifiInfo currentInfo = mWifiManager . getConnectionInfo ();
return currentInfo ;
>
@ Override
public void onStateUpdate ( NetworkInfo . DetailedState detailedState )
mWifiConnectorListener . onWiFiStateUpdate ( getActiveConnection (), detailedState );
>
@ Override
public void onRssiChanged ( int rssi )
mWifiConnectorListener . onWiFiRssiChanged ( rssi );
>
@ Override
public void onScanResultsAvailable ()
List < ScanResult >scanResults = mWifiManager . getScanResults ();
ArrayList < BriefWiFiInfo >wiFiList = new ArrayList <>();
for ( ScanResult scanResult : scanResults )
BriefWiFiInfo briefWiFiInfo = new BriefWiFiInfo ();
briefWiFiInfo . setSsid ( scanResult . SSID );
int rssiPercentage = WifiManager . calculateSignalLevel ( scanResult . level , 100 );
briefWiFiInfo . setRssi ( rssiPercentage );
wiFiList . add ( briefWiFiInfo );
>
mWifiConnectorListener . onWiFiScanResults ( wiFiList );
>
public void setup ()
registerReceiver ( mContext );
>
public void destroy ()
unregisterReceiver ();
>
private void registerReceiver ( Context context )
context . getApplicationContext (). registerReceiver ( mWiFiBroadcastReceiver , mWifiIntentFilter );
mIsWifiBroadcastRegistered = true ;
>
private void unregisterReceiver ()
if ( mContext != null && mWiFiBroadcastReceiver != null && mIsWifiBroadcastRegistered )
try
mContext
. getApplicationContext ()
. unregisterReceiver ( mWiFiBroadcastReceiver );
mIsWifiBroadcastRegistered = false ;
> catch ( IllegalArgumentException e )
Log . d ( TAG , «Unable to unregister receiver» );
>
>
>
public static String quoted ( String s )
return » \» » + s + » \» » ;
>
public interface WiFiConnectorListener
void onWiFiStateUpdate ( WifiInfo wifiInfo , NetworkInfo . DetailedState detailedState );
void onWiFiRssiChanged ( int rssi );
/**
* list contains SSID and RSSI only
*/
void onWiFiScanResults ( ArrayList < BriefWiFiInfo >wiFiList );
>
>

Источник

Android — connect to wifi programmatically

When I have wifi enabled on my phone, it works as expected, but the problem is, when wifi is disabled. In this case the only result is enabling wifi adapter, but not connecting to the network. It seems like enabling takes to long so it won’t get connected. Another strange thing to me is that wifiManager.getConfiguredNetworks() returns null. Do you know how to fix that? Thank you

2 Answers 2

It seems like enabling takes to long so it won’t get connected.

Yes. This is because enabling of the network is done async, it happens in parallel, and doesn’t occur immediately. Here are two possible solutions to your problem:

1) This is the easiest solution, but not the best. Loop as described by another user checking for the scan results to come in. However, you should add a sleep of some sort between every cycle of the loop. I.E. you want to wait for 1ms, so as to not eat up all the CPU resources. I am not sure how to do this in Android off the top of my head. There is another problem with this method. If u are in the GUI thread, you will block all GUI events this way, as you wait for the connection to be established.

2) This is the proper solution. You can register for broadcast events after the network connection has been established. Then you will get an event when it finishes. From this event you can finish performing whatever operations are needed.

Sorry for the rushed answer. I am not an Android pro, so I can’t explain the details as to how to do this off the top of my head, but I thought I would at least point you in the right direction.

Источник

Читайте также:  Контроль пропускной способности wi fi
Оцените статью
Adblock
detector