问题描述
我想创建一个应用程序,检测附近可用的Wifi连接,然后连接到他们。我做了什么到现在,是我创建一个ListView,其中列出了可用的WiFi连接,然后我创建了一个LongItemClick对话框,显示SSID和网络的BSSID,并要求输入密码。现在,我希望连接到网络,独立于它是什么样的网络,它可能是WEP,WPA或打开过的一个。我无法得到我应该怎么连接到它们的概述。谁能帮助我?我找遍了所有可用的答案,我没有找到任何答案,这可以帮助我做到这一点!
我尝试下面的方法上面的东西。我创建了附近的所有可用的Wi-Fi网络的列表视图,然后我试图说明在长preSS的连接信息,并给连接到通过点击点击的Wi-Fi网络的选项。
code:
包com.example.random;进口的java.util.ArrayList;
进口的java.util.HashMap;
进口java.util.Iterator的;
进口的java.util.List;进口android.app.Activity;
进口android.app.AlertDialog;
进口android.app.Dialog;
进口android.app.FragmentManager;
进口android.app.ListActivity;
进口android.content.BroadcastReceiver;
进口android.content.Context;
进口android.content.Intent;
进口android.content.IntentFilter;
进口android.net.wifi.ScanResult;
进口android.net.wifi.WifiConfiguration;
进口android.net.wifi.WifiConfiguration.AuthAlgorithm;
进口android.net.wifi.WifiConfiguration.GroupCipher;
进口android.net.wifi.WifiConfiguration.KeyMgmt;
进口android.net.wifi.WifiConfiguration.PairwiseCipher;
进口android.net.wifi.WifiConfiguration.Protocol;
进口android.net.wifi.WifiManager;
进口android.os.Bundle;
进口android.support.v4.app.DialogFragment;
进口android.support.v4.app.FragmentActivity;
进口android.util.Log;
进口android.view.LayoutInflater;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.view.ViewGroup;
进口android.widget.AdapterView;
进口android.widget.AdapterView.OnItemClickListener;
进口android.widget.AdapterView.OnItemLongClickListener;
进口android.widget.AdapterView.OnItemSelectedListener;
进口android.widget.Button;
进口android.widget.EditText;
进口android.widget.ListView;
进口android.widget.SimpleAdapter;
进口android.widget.TextView;
进口android.widget.Toast;公共类MainActivity扩展FragmentActivity实现OnClickListener
{
WifiManager无线网络;
LV的ListView;
// TextView的textStatus;
按钮buttonScan;
INT大小= 0;
清单< ScanResult>结果;
最后上下文的背景下=这;
传递的EditText;
字符串checkPassword = NULL; 字符串ITEM_KEY =钥匙;
ArrayList的<&HashMap的LT;字符串,字符串>> ArrayList的=新的ArrayList<&HashMap的LT;字符串,字符串>>();
SimpleAdapter适配器; / *当第一次创建活动调用。 * /
@覆盖
公共无效的onCreate(捆绑savedInstanceState)
{
super.onCreate(savedInstanceState);
的setContentView(R.layout.main);// textStatus =(的TextView)findViewById(R.id.textStatus);
buttonScan =(按钮)findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(本);
LV =(ListView控件)findViewById(R.id.list);
lv.setOnItemClickListener(新OnItemClickListener(){ @覆盖
公共无效onItemClick(适配器视图<>为arg0,ARG1观,诠释ARG2,
长ARG3){
// TODO自动生成方法存根
connectToWifi(ARG2);
} 私人无效connectToWifi(最终诠释位置)
{
最后对话的对话=新的对话框(背景);
dialog.setContentView(R.layout.connect);
dialog.setTitle(连接到网络);
TextView的textSSID =(TextView中)dialog.findViewById(R.id.textSSID);
TextView的textBSSID =(TextView中)dialog.findViewById(R.id.textBSSID);
TextView的能力=(TextView中)dialog.findViewById(R.id.textCapabilities); 按钮dialogButton =(按钮)dialog.findViewById(R.id.dialogButtonOK);
通=(EditText上)dialog.findViewById(R.id.textPassword);
textSSID.setText(results.get(位置).SSID);
textBSSID.setText(results.get(位置).BSSID);
capabilities.setText(results.get(位置).capabilities);
//
//如果点击按钮,连接到网络;
dialogButton.setOnClickListener(新OnClickListener(){
@覆盖
公共无效的onClick(视图v){
。checkPassword = pass.getText()的toString();
finallyConnect(checkPassword);
dialog.dismiss();
} 私人无效finallyConnect(字符串checkPassword){
字符串networkSSID = results.get(位置).SSID;
字符串networkPass = checkPassword; WifiConfiguration wifiConfig =新WifiConfiguration();
wifiConfig.SSID =的String.format(\\%s \\的networkSSID);
。wifiConfig preSharedKey =的String.format(\\%s \\的networkPass); WifiManager wifiManager =(WifiManager)getSystemService(WIFI_SERVICE);
//记住ID
INT NETID = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(NETID,真);
wifiManager.reconnect(); WifiConfiguration的conf =新WifiConfiguration();
conf.SSID =\\\\+ networkSSID +\\\\;
。CONF preSharedKey =\\+ networkPass +\\;
WifiManager wifiManager1 =(WifiManager)context.getSystemService(Context.WIFI_SERVICE);
wifiManager1.addNetwork(CONF);//列表< WifiConfiguration>清单= wifiManager1.getConfiguredNetworks();
//为(WifiConfiguration我:名单){
//如果(i.SSID = NULL&放大器;!&安培; i.SSID.equals(\\+ networkSSID +\\)){
// wifiManager1.disconnect();
//
// wifiManager1.enableNetwork(i.networkId,真);
//如果(wifiManager1.reconnect()){
//// INT ip地址= wifiManager.getConnectionInfo()getIpAddress()。
//// Toast.makeText(getApplicationContext(),ip地址,Toast.LENGTH_SHORT).show();
// Toast.makeText(getApplicationContext(),networkSSID ++连接成功,Toast.LENGTH_SHORT).show();
//}
//其他{
// Toast.makeText(getApplicationContext(),连接失败,Toast.LENGTH_SHORT).show();
//}
//
//突破;
//
//}
//} }
});
dialog.show();
}
}); lv.setOnItemLongClickListener(新OnItemLongClickListener(){ @覆盖
公共布尔onItemLongClick(适配器视图<>为arg0,ARG1查看,
INT ARG2,长ARG3){
// TODO自动生成方法存根
showWifiSettings(ARG2);
返回true;
} 私人无效showWifiSettings(INT ARG2){
showDialogOfOptions(ARG2);
} 私人无效showDialogOfOptions(INT ARG2){
//创建一个自定义对话框
最后对话的对话=新的对话框(背景);
dialog.setContentView(R.layout.custom);
dialog.setTitle(网络信息);
TextView的textSSID =(TextView中)dialog.findViewById(R.id.textSSID);
TextView的textBSSID =(TextView中)dialog.findViewById(R.id.textBSSID);
按钮dialogButton =(按钮)dialog.findViewById(R.id.dialogButtonOK);
textSSID.setText(results.get(ARG2).SSID);
textBSSID.setText(results.get(ARG2).BSSID);
//如果点击按钮,关闭对话框定制
dialogButton.setOnClickListener(新OnClickListener(){
@覆盖
公共无效的onClick(视图v){
dialog.dismiss();
}
}); dialog.show();
}
}); 无线=(WifiManager)getSystemService(Context.WIFI_SERVICE);
如果(wifi.isWifiEnabled()== FALSE)
{
Toast.makeText(getApplicationContext(),WiFi是disabled..making它启用,Toast.LENGTH_LONG).show();
wifi.setWifiEnabled(真);
} this.adapter =新SimpleAdapter(MainActivity.this,ArrayList中,R.layout.row,新的String [] {} ITEM_KEY,新的INT [] {R.id.list_value});
lv.setAdapter(this.adapter); registerReceiver(新广播接收器()
{
@覆盖
公共无效的onReceive(上下文C,意图意图)
{
结果= wifi.getScanResults();
大小= results.size();
}
},新的IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}//保护无效connectionStatus(字符串密码){
// // TODO自动生成方法存根
//
//
//} 公共无效的onClick(查看视图)
{
arraylist.clear();
wifi.startScan(); Toast.makeText(这一点,扫描......+大小,Toast.LENGTH_SHORT).show();
尝试
{
大小= - 1;
而(大小> = 0)
{
HashMap的<字符串,字符串>项目=新的HashMap<字符串,字符串>();
item.put(ITEM_KEY,results.get(大小).SSID.toString()+ results.get(大小).capabilities.toString()); arraylist.add(项目);
尺寸 - ;
adapter.notifyDataSetChanged();
}
}
赶上(例外五)
{}
}
}
应用程序被罚款运行,但它并没有连接到任何WiFi网络。任何帮助吗?
进口的java.util.ArrayList;
进口的java.util.HashMap;进口的java.util.List;进口android.app.Activity;
进口android.app.Dialog;
进口android.content.BroadcastReceiver;
进口android.content.Context;
进口android.content.Intent;
进口android.content.IntentFilter;
进口android.net.wifi.ScanResult;
进口android.net.wifi.WifiConfiguration;
进口android.net.wifi.WifiManager;
进口android.os.Bundle;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.widget.AdapterView;
进口android.widget.AdapterView.OnItemClickListener;
进口android.widget.AdapterView.OnItemLongClickListener;
进口android.widget.Button;
进口android.widget.EditText;
进口android.widget.ListView;
进口android.widget.SimpleAdapter;
进口android.widget.TextView;
进口android.widget.Toast;公共类MainActivity扩展活动实现OnClickListener {
私人WifiManager无线网络;
私人的ListView LV;
// TextView的textStatus;
私人按钮buttonScan;
私人诠释大小= 0;
私人列表< ScanResult>结果;
私人最终上下文的背景下=这;
私人的EditText通;
私人字符串checkPassword = NULL; 私人字符串ITEM_KEY =钥匙;
私人的ArrayList<&HashMap的LT;字符串,字符串>> ArrayList的=新的ArrayList<&HashMap的LT;字符串,字符串>>();
私人SimpleAdapter适配器;
/ *当第一次创建活动调用。 * /
@覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.main); // textStatus =(的TextView)findViewById(R.id.textStatus);
buttonScan =(按钮)findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(本);
LV =(ListView控件)findViewById(R.id.list);
无线=(WifiManager)getSystemService(Context.WIFI_SERVICE); lv.setOnItemClickListener(新OnItemClickListener(){ @覆盖
公共无效onItemClick(适配器视图<>为arg0,ARG1观,诠释ARG2,
长ARG3){
// TODO自动生成方法存根
connectToWifi(ARG2);
} }); lv.setOnItemLongClickListener(新OnItemLongClickListener(){ @覆盖
公共布尔onItemLongClick(适配器视图<>为arg0,ARG1查看,
INT ARG2,长ARG3){
// TODO自动生成方法存根
showWifiSettings(ARG2);
返回true;
}
}); 如果(wifi.isWifiEnabled()==假){
Toast.makeText(getApplicationContext(),
WiFi是disabled..making它启用,Toast.LENGTH_LONG)
。显示();
wifi.setWifiEnabled(真);
} 适配器=新SimpleAdapter(MainActivity.this,ArrayList中,
R.layout.row,新的String [] {} ITEM_KEY,
新的INT [] {R.id.list_value});
lv.setAdapter(适配器); registerReceiver(新广播接收器(){
@覆盖
公共无效的onReceive(上下文C,意图意图){
结果= wifi.getScanResults();
大小= results.size();
}
},新的IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}//保护无效connectionStatus(字符串密码){
// // TODO自动生成方法存根
//
//
//}
@覆盖
公共无效的onClick(查看视图){ arraylist.clear();
wifi.startScan(); Toast.makeText(这一点,扫描......+大小,Toast.LENGTH_SHORT).show();
尝试{
大小= - 1;
而(大小> = 0){
HashMap的<字符串,字符串>项目=新的HashMap<字符串,字符串>();
item.put(ITEM_KEY,
results.get(大小).SSID.toString()
+ results.get(大小).capabilities.toString()); arraylist.add(项目);
尺寸 - ;
adapter.notifyDataSetChanged();
} }赶上(例外五){
}
}私人无效showWifiSettings(INT ARG2){
showDialogOfOptions(ARG2);
}私人无效showDialogOfOptions(INT ARG2){
//创建一个自定义对话框
最后对话的对话=新的对话框(背景);
dialog.setContentView(R.layout.custom);
dialog.setTitle(网络信息);
TextView的textSSID =(TextView中)dialog.findViewById(R.id.textSSID);
TextView的textBSSID =(TextView中)dialog.findViewById(R.id.textBSSID);
按钮dialogButton =(按钮)dialog.findViewById(R.id.dialogButtonOK);
textSSID.setText(results.get(ARG2).SSID);
textBSSID.setText(results.get(ARG2).BSSID);
//如果点击按钮,关闭对话框定制
dialogButton.setOnClickListener(新OnClickListener(){
@覆盖
公共无效的onClick(视图v){
dialog.dismiss();
}
}); dialog.show();
}私人无效finallyConnect(字符串checkPassword,INT位置){
字符串networkSSID = results.get(位置).SSID;
字符串networkPass = checkPassword; WifiConfiguration wifiConfig =新WifiConfiguration();
wifiConfig.SSID =的String.format(\\%s \\的networkSSID);
。wifiConfig preSharedKey =的String.format(\\%s \\的networkPass); //记住ID
INT NETID = wifi.addNetwork(wifiConfig);
wifi.disconnect();
wifi.enableNetwork(NETID,真);
wifi.reconnect(); WifiConfiguration的conf =新WifiConfiguration();
conf.SSID =\\\\+ networkSSID +\\\\;
。CONF preSharedKey =\\+ networkPass +\\;
wifi.addNetwork(CONF); //列表< WifiConfiguration>清单=
// wifiManager1.getConfiguredNetworks();
//为(WifiConfiguration我:名单){
//如果(i.SSID = NULL&放大器;!&安培; i.SSID.equals(\\+ networkSSID
// +\\)){
// wifiManager1.disconnect();
//
// wifiManager1.enableNetwork(i.networkId,真);
//如果(wifiManager1.reconnect()){
// // INT ip地址=
// wifiManager.getConnectionInfo()getIpAddress()。
// // Toast.makeText(getApplicationContext(),ip地址,
// Toast.LENGTH_SHORT).show();
// Toast.makeText(getApplicationContext(),networkSSID +
//+连接成功,
// Toast.LENGTH_SHORT).show();
//}
//其他{
// Toast.makeText(getApplicationContext(),
//连接失败,Toast.LENGTH_SHORT).show();
//}
//
//突破;
//
//}
//}}私人无效connectToWifi(最终诠释位置){
最后对话的对话=新的对话框(背景);
dialog.setContentView(R.layout.connect);
dialog.setTitle(连接到网络);
TextView的textSSID =(TextView中)dialog.findViewById(R.id.textSSID1);
TextView的textBSSID =(TextView中)dialog.findViewById(R.id.textBSSID1);
TextView的能力=(TextView的)对话
.findViewById(R.id.textCapabilities); 按钮dialogButton =(按钮)dialog.findViewById(R.id.okButton);
通=(EditText上)dialog.findViewById(R.id.textPassword);
textSSID.setText(results.get(位置).SSID);
textBSSID.setText(results.get(位置).BSSID);
capabilities.setText(results.get(位置).capabilities);
//
//如果点击按钮,连接到网络;
dialogButton.setOnClickListener(新OnClickListener(){
@覆盖
公共无效的onClick(视图v){
。checkPassword = pass.getText()的toString();
finallyConnect(checkPassword,位置);
dialog.dismiss();
} });
dialog.show();
}
}
I wish to create an application, that detects the available wifi connections in the vicinity, and then connects to them. What I have done till now, is that I created a ListView that lists the available wifi connections, and then I created a LongItemClick dialog box, that shows the SSID and the BSSID of the network, and asks for the password. Now, I wish to connect to one of the networks, independent of what kind of network it is, it might be WEP, WPA or Open too. I am unable to get an overview of how should I connect to them. Can anyone help me with this ? I searched all available answers, and I didn't find any answer, that could help me do this!
I try the above thing by the below method. I create a list view of all the available wi-fi networks in the vicinity, and then I try to show the connection info on long press, and give an option to connect to the clicked wi-fi network via click.
Code:
package com.example.random;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.FragmentManager;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.AuthAlgorithm;
import android.net.wifi.WifiConfiguration.GroupCipher;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiConfiguration.PairwiseCipher;
import android.net.wifi.WifiConfiguration.Protocol;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements OnClickListener
{
WifiManager wifi;
ListView lv;
// TextView textStatus;
Button buttonScan;
int size = 0;
List<ScanResult> results;
final Context context = this;
EditText pass;
String checkPassword = null;
String ITEM_KEY = "key";
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
SimpleAdapter adapter;
/* Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// textStatus = (TextView) findViewById(R.id.textStatus);
buttonScan = (Button) findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(this);
lv = (ListView)findViewById(R.id.list);
lv.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
connectToWifi(arg2);
}
private void connectToWifi(final int position)
{
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.connect);
dialog.setTitle("Connect to Network");
TextView textSSID = (TextView) dialog.findViewById(R.id.textSSID);
TextView textBSSID = (TextView) dialog.findViewById(R.id.textBSSID);
TextView capabilities = (TextView) dialog.findViewById(R.id.textCapabilities);
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
pass = (EditText) dialog.findViewById(R.id.textPassword);
textSSID.setText(results.get(position).SSID);
textBSSID.setText(results.get(position).BSSID);
capabilities.setText(results.get(position).capabilities);
//
// if button is clicked, connect to the network;
dialogButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
checkPassword = pass.getText().toString();
finallyConnect(checkPassword);
dialog.dismiss();
}
private void finallyConnect(String checkPassword) {
String networkSSID = results.get(position).SSID;
String networkPass = checkPassword;
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", networkSSID);
wifiConfig.preSharedKey = String.format("\"%s\"", networkPass);
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
//remember id
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"\"" + networkSSID + "\"\"";
conf.preSharedKey = "\""+ networkPass +"\"";
WifiManager wifiManager1 = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
wifiManager1.addNetwork(conf);
// List<WifiConfiguration> list = wifiManager1.getConfiguredNetworks();
// for( WifiConfiguration i : list ) {
// if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
// wifiManager1.disconnect();
//
// wifiManager1.enableNetwork(i.networkId, true);
// if(wifiManager1.reconnect()){
//// int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
//// Toast.makeText(getApplicationContext(), ipAddress, Toast.LENGTH_SHORT).show();
// Toast.makeText(getApplicationContext(), networkSSID + " "+ "Connection successful", Toast.LENGTH_SHORT).show();
// }
// else{
// Toast.makeText(getApplicationContext(), "Connection Failed", Toast.LENGTH_SHORT).show();
// }
//
// break;
//
// }
// }
}
});
dialog.show();
}
});
lv.setOnItemLongClickListener(new OnItemLongClickListener(){
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
showWifiSettings(arg2);
return true;
}
private void showWifiSettings(int arg2) {
showDialogOfOptions(arg2);
}
private void showDialogOfOptions(int arg2) {
// Create a custom Dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
dialog.setTitle("Network details");
TextView textSSID = (TextView) dialog.findViewById(R.id.textSSID);
TextView textBSSID = (TextView) dialog.findViewById(R.id.textBSSID);
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
textSSID.setText(results.get(arg2).SSID);
textBSSID.setText(results.get(arg2).BSSID);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled() == false)
{
Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
wifi.setWifiEnabled(true);
}
this.adapter = new SimpleAdapter(MainActivity.this, arraylist, R.layout.row, new String[] { ITEM_KEY }, new int[] { R.id.list_value });
lv.setAdapter(this.adapter);
registerReceiver(new BroadcastReceiver()
{
@Override
public void onReceive(Context c, Intent intent)
{
results = wifi.getScanResults();
size = results.size();
}
}, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}
// protected void connectionStatus(String password) {
// // TODO Auto-generated method stub
//
//
// }
public void onClick(View view)
{
arraylist.clear();
wifi.startScan();
Toast.makeText(this, "Scanning...." + size, Toast.LENGTH_SHORT).show();
try
{
size = size - 1;
while (size >= 0)
{
HashMap<String, String> item = new HashMap<String, String>();
item.put(ITEM_KEY, results.get(size).SSID.toString()+ results.get(size).capabilities.toString());
arraylist.add(item);
size--;
adapter.notifyDataSetChanged();
}
}
catch (Exception e)
{ }
}
}
The application is running fine, but it does not connect to any of the Wifi networks. Any help please ?
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private WifiManager wifi;
private ListView lv;
// TextView textStatus;
private Button buttonScan;
private int size = 0;
private List<ScanResult> results;
private final Context context = this;
private EditText pass;
private String checkPassword = null;
private String ITEM_KEY = "key";
private ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
private SimpleAdapter adapter;
/* Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// textStatus = (TextView) findViewById(R.id.textStatus);
buttonScan = (Button) findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(this);
lv = (ListView) findViewById(R.id.list);
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
connectToWifi(arg2);
}
});
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
showWifiSettings(arg2);
return true;
}
});
if (wifi.isWifiEnabled() == false) {
Toast.makeText(getApplicationContext(),
"wifi is disabled..making it enabled", Toast.LENGTH_LONG)
.show();
wifi.setWifiEnabled(true);
}
adapter = new SimpleAdapter(MainActivity.this, arraylist,
R.layout.row, new String[] { ITEM_KEY },
new int[] { R.id.list_value });
lv.setAdapter(adapter);
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent intent) {
results = wifi.getScanResults();
size = results.size();
}
}, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}
// protected void connectionStatus(String password) {
// // TODO Auto-generated method stub
//
//
// }
@Override
public void onClick(View view) {
arraylist.clear();
wifi.startScan();
Toast.makeText(this, "Scanning...." + size, Toast.LENGTH_SHORT).show();
try {
size = size - 1;
while (size >= 0) {
HashMap<String, String> item = new HashMap<String, String>();
item.put(ITEM_KEY,
results.get(size).SSID.toString()
+ results.get(size).capabilities.toString());
arraylist.add(item);
size--;
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
}
}
private void showWifiSettings(int arg2) {
showDialogOfOptions(arg2);
}
private void showDialogOfOptions(int arg2) {
// Create a custom Dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
dialog.setTitle("Network details");
TextView textSSID = (TextView) dialog.findViewById(R.id.textSSID);
TextView textBSSID = (TextView) dialog.findViewById(R.id.textBSSID);
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
textSSID.setText(results.get(arg2).SSID);
textBSSID.setText(results.get(arg2).BSSID);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
private void finallyConnect(String checkPassword, int position) {
String networkSSID = results.get(position).SSID;
String networkPass = checkPassword;
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", networkSSID);
wifiConfig.preSharedKey = String.format("\"%s\"", networkPass);
// remember id
int netId = wifi.addNetwork(wifiConfig);
wifi.disconnect();
wifi.enableNetwork(netId, true);
wifi.reconnect();
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"\"" + networkSSID + "\"\"";
conf.preSharedKey = "\"" + networkPass + "\"";
wifi.addNetwork(conf);
// List<WifiConfiguration> list =
// wifiManager1.getConfiguredNetworks();
// for( WifiConfiguration i : list ) {
// if(i.SSID != null && i.SSID.equals("\"" + networkSSID
// + "\"")) {
// wifiManager1.disconnect();
//
// wifiManager1.enableNetwork(i.networkId, true);
// if(wifiManager1.reconnect()){
// // int ipAddress =
// wifiManager.getConnectionInfo().getIpAddress();
// // Toast.makeText(getApplicationContext(), ipAddress,
// Toast.LENGTH_SHORT).show();
// Toast.makeText(getApplicationContext(), networkSSID +
// " "+ "Connection successful",
// Toast.LENGTH_SHORT).show();
// }
// else{
// Toast.makeText(getApplicationContext(),
// "Connection Failed", Toast.LENGTH_SHORT).show();
// }
//
// break;
//
// }
// }
}
private void connectToWifi(final int position) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.connect);
dialog.setTitle("Connect to Network");
TextView textSSID = (TextView) dialog.findViewById(R.id.textSSID1);
TextView textBSSID = (TextView) dialog.findViewById(R.id.textBSSID1);
TextView capabilities = (TextView) dialog
.findViewById(R.id.textCapabilities);
Button dialogButton = (Button) dialog.findViewById(R.id.okButton);
pass = (EditText) dialog.findViewById(R.id.textPassword);
textSSID.setText(results.get(position).SSID);
textBSSID.setText(results.get(position).BSSID);
capabilities.setText(results.get(position).capabilities);
//
// if button is clicked, connect to the network;
dialogButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
checkPassword = pass.getText().toString();
finallyConnect(checkPassword, position);
dialog.dismiss();
}
});
dialog.show();
}
}
这篇关于回复:连接到WIFI网络编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!