AP 목록
채널
신호세기
암호방식
package com.welgate.wificonnector;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.NetworkInfo.DetailedState;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class WifiConnectorActivity extends Activity {
/* This App's Log Tag */
public static final String TAG = "myLog";
WifiManager mWifiManager;
List<WifiConfiguration> wifiConfigurationList;
List<ScanResult> scanResult;
AccessPointAdapter accessPointAdapter;
ListView listView;
// Receiver
WifiStateChangedReceiver wifiStateChangedReceiver = new WifiStateChangedReceiver();
Button mConnectBtn;
// Component
TextView txtState;
Button btnWifiOn, btnClose;
ProgressBar progressBar;
AlertDialog.Builder mAdialog = null;
boolean isFirst = true;
boolean isConnected = false;
boolean isAutoConneted = false;
/* Handler */
private Handler mHandler = new Handler() {};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wifi);
scanResult = new ArrayList<ScanResult>();
accessPointAdapter = new AccessPointAdapter(this);
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(wifiStateChangedReceiver, filter);
mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
txtState = (TextView)findViewById(R.id.nowState);
btnWifiOn = (Button)findViewById(R.id.turn_on_wifi);
btnClose = (Button)findViewById(R.id.close_wifi_setting);
btnClose.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
finish();
}
});
progressBar = (ProgressBar)findViewById(R.id.progress_small);
listView = (ListView)findViewById(R.id.ac_list);
stateWifi();
wifiConfigurationList = mWifiManager.getConfiguredNetworks();
Button btnOnHospot = (Button)findViewById(R.id.turn_on_hotspot);
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT){//유심이 없는경우
btnOnHospot.setEnabled(false);
}
if(mWifiManager.isWifiEnabled()){
txtState.setText("Wi-Fi ENABLED");
accessPointScan();
}
listView.setAdapter(accessPointAdapter);
TextView emptyView = (TextView)findViewById(R.id.ac_no);
listView.setEmptyView(emptyView);
}
@Override
public void onDestroy(){
super.onDestroy();
unregisterReceiver(wifiStateChangedReceiver);
}
private void connect(WifiConfiguration wc){
int networkID = mWifiManager.addNetwork(wc);
boolean bEnableNetwork = mWifiManager.enableNetwork(networkID, true);
if(bEnableNetwork){
Log.d(TAG, "Connected!");
}else{
Log.d(TAG, "Disconnected!");
}
}
Comparator<ScanResult> compare = new Comparator<ScanResult>(){
@Override
public int compare(ScanResult object1, ScanResult object2) {
int p1 = object1.level;
int p2 = object2.level;
int aa = 1;
if(p1 > p2) aa = -1;
else if(p1 == p2) aa = 0;
return aa;
}
};
private void accessPointScan(){
boolean bScan = mWifiManager.startScan();
if(bScan){
wifiConfigurationList = mWifiManager.getConfiguredNetworks();
progressBar.setVisibility(View.VISIBLE);
scanResult.clear();
//중복 검색된 AP는 제외한다.
List<ScanResult> scanResultTmp = mWifiManager.getScanResults();
if(scanResultTmp.size() == 0){
accessPointScan();
accessPointAdapter.notifyDataSetChanged();
return;
}
for(ScanResult sr : scanResultTmp){
int i=0;
for(ScanResult sr2 : scanResult){
if(sr.SSID.equals(sr2.SSID)){
i +=1;
}
}
if(i==0)scanResult.add(sr);
}
Collections.sort(scanResult, compare);
}else{
Toast.makeText(this, R.string.wifi_fail_scan, Toast.LENGTH_SHORT);
}
}
private int getSignalResId(int signal, boolean key) {
switch (WifiManager.calculateSignalLevel(signal, 4)) {
case 0: {
if(key) return R.drawable.ap_lock_connection_wifi_01;
else return R.drawable.ap_connection_wifi_01;
}
case 1: {
if(key) return R.drawable.ap_lock_connection_wifi_02;
else return R.drawable.ap_connection_wifi_02;
}
case 2: {
if(key) return R.drawable.ap_lock_connection_wifi_03;
else return R.drawable.ap_connection_wifi_03;
}
case 3: {
if(key) return R.drawable.ap_lock_connection_wifi_04;
else return R.drawable.ap_connection_wifi_04;
}
default: {
if(key) return R.drawable.ap_lock_connection_wifi_00;
else return R.drawable.ap_connection_wifi_00;
}
}
}
private int getChannel(int frequency) {
int channel = -1;
switch(frequency) {
case 2412: channel = 1; break;
case 2417: channel = 2; break;
case 2422: channel = 3; break;
case 2427: channel = 4; break;
case 2432: channel = 5; break;
case 2437: channel = 6; break;
case 2442: channel = 7; break;
case 2447: channel = 8; break;
case 2452: channel = 9; break;
case 2457: channel = 10; break;
case 2462: channel = 11; break;
case 2467: channel = 12; break;
case 2472: channel = 13; break;
case 2484: channel = 14; break;
}
return channel;
}
public class AccessPointAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
public AccessPointAdapter(Context context){
this.mContext = context;
mInflater = LayoutInflater.from(mContext);
}
@Override
public int getCount() {
return scanResult.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ScanResult sr = scanResult.get(position);
String capa = sr.capabilities;
String nowSSID = mWifiManager.getConnectionInfo().getSSID();
LinearLayout row = (LinearLayout)mInflater.inflate(R.layout.simple_list_item_1, null);
final TextView title = (TextView)row.findViewById(R.id.title);
TextView summary = (TextView)row.findViewById(R.id.summary);
ImageView level = (ImageView)row.findViewById(R.id.widget_frame);
if(!capa.equals("")){
level.setImageResource(getSignalResId(sr.level, true));
}else{
level.setImageResource(getSignalResId(sr.level, false));
}
title.setText(sr.SSID);
summary.setText((getChannel(sr.frequency)!=-1?getChannel(sr.frequency)+"ch ":"")+ capa);
row.setTag(sr);
if(sr.SSID.equals(nowSSID) /*&& isConnected*/){
title.setTextColor(0xff8cba63);
title.setText(Html.fromHtml("<b>" + sr.SSID + "</b>"));
}
row.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
txtState.setText("CONNECTING");
ScanResult sr = (ScanResult)v.getTag();
String selectedSSID = sr.SSID;
int networkID = -1;
for(WifiConfiguration w : wifiConfigurationList){
if(w.SSID.equals("\""+selectedSSID+"\"")){
networkID = w.networkId;
}
}
if(networkID == -1){
final WifiConfiguration wfc = new WifiConfiguration();
wfc.SSID = "\"".concat(selectedSSID).concat("\"");
wfc.status = WifiConfiguration.Status.DISABLED;
if(sr.capabilities.equals("")){//오픈 네트워크일때
wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wfc.allowedAuthAlgorithms.clear();
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
connect(wfc);
}else if(sr.capabilities.contains("WEP")){ //WEP 패스워드가 요구될때
LayoutInflater factory = LayoutInflater.from(WifiConnectorActivity.this);
final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
if(mAdialog == null){
mAdialog = new AlertDialog.Builder(WifiConnectorActivity.this);
mAdialog.setTitle(R.string.wifi_need_password);
mAdialog.setView(textEntryView);
mAdialog.setCancelable(false);
mAdialog.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String password = ((EditText)textEntryView.findViewById(R.id.password)).getText().toString();
wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wfc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
wfc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
int length = password.length();
if ((length == 10 || length == 26 || length == 58) &&
password.matches("[0-9A-Fa-f]*")) {
wfc.wepKeys[0] = password;
} else {
wfc.wepKeys[0] = '"' + password + '"';
}
connect(wfc);
mAdialog = null;
}
});
mAdialog.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mAdialog = null;
}
});
AlertDialog d = mAdialog.show();
mConnectBtn = d.getButton(DialogInterface.BUTTON_POSITIVE);
mConnectBtn.setEnabled(false);
EditText et = (EditText)textEntryView.findViewById(R.id.password);
et.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
int nLen = s.toString().length();
if( 1 <= nLen && nLen <= 26){
if(mConnectBtn != null)
mConnectBtn.setEnabled(true);
} else {
if(mConnectBtn != null)
mConnectBtn.setEnabled(false);
}
}
});
}
}else{ // WPA, WPA2 일때
LayoutInflater factory = LayoutInflater.from(WifiConnectorActivity.this);
final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
if(mAdialog == null){
mAdialog = new AlertDialog.Builder(WifiConnectorActivity.this);
mAdialog.setTitle(R.string.wifi_need_password);
mAdialog.setView(textEntryView);
mAdialog.setCancelable(false);
mAdialog.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String password = ((EditText)textEntryView.findViewById(R.id.password)).getText().toString();
wfc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wfc.preSharedKey = "\"".concat(password).concat("\"");
connect(wfc);
mAdialog = null;
}
});
mAdialog.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mAdialog = null;
}
});
AlertDialog d = mAdialog.show();
mConnectBtn = d.getButton(DialogInterface.BUTTON_POSITIVE);
mConnectBtn.setEnabled(false);
EditText et = (EditText)textEntryView.findViewById(R.id.password);
et.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
int nLen = s.toString().length();
if(8 <= nLen && nLen <= 63){
if(mConnectBtn != null)
mConnectBtn.setEnabled(true);
} else {
if(mConnectBtn != null)
mConnectBtn.setEnabled(false);
}
}
});
}
}
}else{
boolean bEnableNetwork = mWifiManager.enableNetwork(networkID, true);
if(bEnableNetwork){
Log.d(TAG, "Connected!");
}else{
Log.d(TAG, "Disconnected!");
}
}
}
});
return row;
}
}
private class WifiStateChangedReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)){
progressBar.setVisibility(View.INVISIBLE);
new Handler().postDelayed(new Runnable(){
@Override
public void run() {
accessPointScan();
accessPointAdapter.notifyDataSetChanged();
}
}, 7000);
return;
}else if(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
DetailedState state = info.getDetailedState();
if(isFirst){
isFirst = false;
switch (state) {
case CONNECTED:
isConnected = true;
break;
case FAILED:
break;
case DISCONNECTING:
break;
case DISCONNECTED:
break;
}
}else{
Log.d(TAG, "STATE : "+state);
txtState.setText(state.toString());
switch (state) {
case CONNECTED:
/*if(MainActivity.initWifiState == 0 && !isAutoConneted){
isConnected = true;
isAutoConneted = true;
}else{
finish();
}*/
txtState.setText(state.toString()+" to "+mWifiManager.getConnectionInfo().getSSID());
break;
case FAILED:
break;
case DISCONNECTING:
break;
case DISCONNECTED:
String ssid = mWifiManager.getConnectionInfo().getSSID();
for(WifiConfiguration w : wifiConfigurationList){
if(w.SSID.equals("\""+ssid+"\"")){
mWifiManager.removeNetwork(w.networkId);
}
}
break;
default:
isConnected = false;
}
}
}
switch(mWifiManager.getWifiState()){
//=========================================================
case WifiManager.WIFI_STATE_DISABLED:
stateWifi();
scanResult.clear();
accessPointAdapter.notifyDataSetChanged();
break;
case WifiManager.WIFI_STATE_ENABLING:
break;
case WifiManager.WIFI_STATE_ENABLED:
accessPointScan();
accessPointAdapter.notifyDataSetChanged();
stateWifi();
break;
case WifiManager.WIFI_STATE_DISABLING:
break;
case WifiManager.WIFI_STATE_UNKNOWN:
//error
break;
}
}
}
private void stateWifi(){
switch(mWifiManager.getWifiState()){
case WifiManager.WIFI_STATE_ENABLED:
findViewById(R.id.turn_on_hotspot).setVisibility(View.VISIBLE);
findViewById(R.id.turn_on_wifi).setVisibility(View.GONE);
btnWifiOn.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
progressBar.setVisibility(View.INVISIBLE);
mWifiManager.setWifiEnabled(false);
}
});
break;
case WifiManager.WIFI_STATE_DISABLED:
findViewById(R.id.turn_on_hotspot).setVisibility(View.GONE);
findViewById(R.id.turn_on_wifi).setVisibility(View.VISIBLE);
btnWifiOn.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
mWifiManager.setWifiEnabled(true);
listView.setAdapter(accessPointAdapter);
}
});
progressBar.setVisibility(View.INVISIBLE);
break;
}
}
}