<uses-sdk android:minSdkVersion="14" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
**//My Activity class**
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btnScan,btnSend;
ListView lvPeers ;
ArrayList<String> listWifi ;
WifiManager wifiManager ;
BroadcastReceiveWifi receiveWifi;
List<ScanResult> listResult;
public ArrayAdapter<String> adapter;
public TextView txtState ;
private void AnhXa()
{
btnScan = (Button)findViewById(R.id.btnScan);
lvPeers = (ListView)findViewById(R.id.lvPeers);
txtState = (TextView)findViewById(R.id.txtTest);
btnSend = (Button)findViewById(R.id.btnSend);
listWifi = new ArrayList<>();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AnhXa();
btnSend.setOnClickListener(this);
btnScan.setOnClickListener(this);
wifiManager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
if(wifiManager.isWifiEnabled()==true)
{
ScanWifi();
}
}
public void ScanWifi()
{
receiveWifi = new BroadcastReceiveWifi();
registerReceiver(this.receiveWifi,new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifiManager.startScan();
}
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.btnScan:
if (wifiManager.isWifiEnabled() == true) {
wifiManager.setWifiEnabled(false);
}
else
if(wifiManager.isWifiEnabled()==false)
{
wifiManager.setWifiEnabled(true);
ScanWifi();
}
break;
case R.id.btnSend:
HospotWifi("DataTransfer","12345678");
break;
}
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiveWifi);
}
@Override
protected void onResume() {
registerReceiver(receiveWifi,new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
super.onResume();
}
class BroadcastReceiveWifi extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
listResult = wifiManager.getScanResults();
for (int i =0; i<listResult.size();i++)
{
listWifi.add(listResult.get(i).SSID);
}
adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,listWifi);
lvPeers.setAdapter(adapter);
adapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this,listResult.size()+"",Toast.LENGTH_LONG).show();
}
}