如何连接到android中的特定wifi连接?

如何连接到android中的特定wifi连接?,android,Android,我正在开发一个应用程序,首先我们必须搜索并连接可用的wifi网络。我已经显示了wifi网络的列表。所以,我想连接列表中的特定wifi 我的代码如下所示 public class MainActivity extends Activity { private ArrayAdapter<String> mPairedDevicesArrayAdapter; ListView mPairedListView = null; WifiConfiguration conf; WifiMana

我正在开发一个应用程序,首先我们必须搜索并连接可用的wifi网络。我已经显示了wifi网络的列表。所以,我想连接列表中的特定wifi

我的代码如下所示

public class MainActivity extends Activity {

private ArrayAdapter<String> mPairedDevicesArrayAdapter;
ListView mPairedListView = null;
WifiConfiguration conf;
WifiManager wifiManager;

// /// ------------------------------------ NETWORK CREDENTIALS

String networkSSID = "your SSID";
String networkPass = "password";

// /// ------------------------------------ NETWORK CREDENTIALS

Button btn_refresh;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    conf = new WifiConfiguration();
    wifiManager = (WifiManager) getApplicationContext().getSystemService(
            Context.WIFI_SERVICE);

    // Connected Wifi information ......................

    // WifiManager wifiManager = (WifiManager)
    // getSystemService(WIFI_SERVICE);
    // WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    // Log.d("wifiInfo", wifiInfo.toString());
    // Log.d("SSID", wifiInfo.getSSID());

    mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this,
            R.layout.device_name);

    mPairedListView = (ListView) findViewById(R.id.paired_devices);

    btn_refresh = (Button) findViewById(R.id.btn_refresh);
    btn_refresh.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(MainActivity.this, MainActivity.class);
            startActivity(i);
        }
    });

    mPairedListView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1,
                final int position, long arg3) {

            LayoutInflater factory = LayoutInflater.from(MainActivity.this);
            final View textEntryView = factory.inflate(
                    R.layout.password_layout, null);

            AlertDialog.Builder alert = new AlertDialog.Builder(
                    MainActivity.this);

            alert.setTitle("Enter your data");
            alert.setView(textEntryView);

            final EditText edt_pass = (EditText) textEntryView
                    .findViewById(R.id.edt_pass);

            edt_pass.setText("");

            alert.setPositiveButton("Ok",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int whichButton) {
                            dialog.cancel();

                            String SSID[] = mPairedListView
                                    .getItemAtPosition(position).toString()
                                    .split("\n");
                            networkSSID = SSID[1];

                            Log.i("networkSSID == ", "" + networkSSID);

                            conf.SSID = "\"" + networkSSID + "\"";

                            // conf.preSharedKey = "\"" +
                            // edt_pass.getText().toString() + "\"";

                            wifiManager.addNetwork(conf);

                            List<WifiConfiguration> list = wifiManager
                                    .getConfiguredNetworks();

                            Log.i("List : ", "" + list);

                            for (WifiConfiguration i : list) {
                                if (i.SSID != null
                                        && i.SSID.equals("\"" + networkSSID
                                                + "\"")) {
                                    wifiManager.disconnect();
                                    Log.i("i.networkId : ", ""
                                            + i.networkId);
                                    wifiManager.enableNetwork(i.networkId,
                                            true);
                                    wifiManager.reconnect();

                                    break;
                                }
                            }

                        }
                    });

            alert.setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int whichButton) {
                            dialog.cancel();

                            String path = "/mnt/sdcard/testpdf.pdf";
                            File f = new File(path); //
                            Uri imageUri = Uri.fromFile(f);

                            Intent printIntent = new Intent(
                                    MainActivity.this,
                                    PrintDialogActivity.class);
                            printIntent.setDataAndType(imageUri,
                                    "application/pdf");
                            printIntent.putExtra("title", "Mitul Doc");
                            startActivity(printIntent);
                        }
                    });

            alert.show();

        }
    });

    WifiScan();

}

private void WifiScan() {
    if (wifiManager.isWifiEnabled() == true) {
        getCurrentSsid(MainActivity.this);
        mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
    } else {
        AlertDialog.Builder builder = new AlertDialog.Builder(
                MainActivity.this);
        builder.setMessage("Not Connected..Do you want to enable it?")
                .setCancelable(false)
                .setPositiveButton("YES",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int id) {
                                dialog.cancel();

                                new Get_Wifi().execute("");
                            }
                        })
                .setNegativeButton("No",
                        new DialogInterface.OnClickListener() {
                            public void onClick(
                                    final DialogInterface dialog,
                                    final int id) {
                                dialog.cancel();
                            }
                        });

        AlertDialog alert = builder.create();
        alert.show();
    }
}

private class Get_Wifi extends AsyncTask<String, Void, Boolean> {
    ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        dialog = ProgressDialog.show(MainActivity.this, "Wi-Fi",
                "Loading...", true, false);
    }

    @Override
    protected Boolean doInBackground(String... params) {
        Boolean success = false;

        try {
            wifiManager.setWifiEnabled(true);

            long timeStarted = System.currentTimeMillis();
            while (System.currentTimeMillis() - timeStarted < 10000) {
                try {
                    Thread.sleep(100);
                    getCurrentSsid(MainActivity.this);
                } catch (InterruptedException e) {
                    Log.e("", "thread interrupted", e);
                }
            }

        } catch (Exception e) {

            e.printStackTrace();
        }

        return success;
    }

    @Override
    protected void onPostExecute(Boolean success) {
        dialog.dismiss();

        super.onPostExecute(success);

        try {
            mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

public String getCurrentSsid(Context context) {

    String ssid = null;
    ConnectivityManager connManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connManager
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (networkInfo.isConnected()) {
        final WifiManager wifiManager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
        if (connectionInfo != null
                && !(connectionInfo.getSSID().equals(""))) {
            // if (connectionInfo != null &&
            // !StringUtil.isBlank(connectionInfo.getSSID())) {
            ssid = connectionInfo.getSSID();
        }
        // Get WiFi status MARAKANA
        WifiInfo info = wifiManager.getConnectionInfo();
        String textStatus = "";
        textStatus += "\n\nWiFi Status: " + info.toString();

        String BSSID = info.getBSSID();
        String MAC = info.getMacAddress();

        List<ScanResult> results = wifiManager.getScanResults();
        ScanResult bestSignal = null;
        int count = 1;
        String etWifiList = "";
        for (ScanResult result : results) {
            etWifiList += count++ + ". " + result.SSID + " : "
                    + result.level + "\n" + result.BSSID + "\n"
                    + result.capabilities + "\n"
                    + "\n=======================\n";
            mPairedDevicesArrayAdapter.add(result.SSID + "\n"
                    + result.BSSID);
        }

        Log.v("", "from SO: \n" + etWifiList);

        // List stored networks
        List<WifiConfiguration> configs = wifiManager
                .getConfiguredNetworks();
        for (WifiConfiguration config : configs) {
            textStatus += "\n\n" + config.toString();
        }
        Log.v("", "from marakana: \n" + textStatus);
    }
    return ssid;
}}
公共类MainActivity扩展活动{
专用阵列适配器MPairedevicesArrayaAdapter;
ListView mPairedListView=null;
WifiConfiguration;
WifiManager WifiManager;
////-------------------------------网络凭据
字符串networkSSID=“您的SSID”;
字符串networkPass=“password”;
////-------------------------------网络凭据
按钮btn_刷新;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
conf=新的WifiConfiguration();
wifiManager=(wifiManager)getApplicationContext().getSystemService(
无线上网服务);
//连接的Wifi信息。。。。。。。。。。。。。。。。。。。。。。
//WifiManager WifiManager=(WifiManager)
//getSystemService(WIFI_服务);
//WifiInfo WifiInfo=wifiManager.getConnectionInfo();
//Log.d(“wifiInfo”,wifiInfo.toString());
//Log.d(“SSID”,wifiInfo.getSSID());
MPairedDeviceArrayaAdapter=新阵列适配器(此,
R.布局、装置名称);
mPairedListView=(ListView)findViewById(R.id.paired_设备);
btn_刷新=(按钮)findViewById(R.id.btn_刷新);
btn_refresh.setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
意图i=新意图(MainActivity.this,MainActivity.class);
星触觉(i);
}
});
mPairedListView.setOnItemClickListener(新的OnItemClickListener(){
@凌驾
公共链接(AdapterView arg0、视图arg1、,
最终整数位置,长arg3){
LayoutFlater工厂=LayoutFlater.from(MainActivity.this);
最终视图文本EntryView=factory.inflate(
R.layout.password_布局,空);
AlertDialog.Builder alert=新建AlertDialog.Builder(
主要活动(本);
alert.setTitle(“输入数据”);
alert.setView(textEntryView);
最终EditText edt_pass=(EditText)textEntryView
.findviewbyd(R.id.edt_通行证);
edt_pass.setText(“”);
alert.setPositiveButton(“确定”,
新建DialogInterface.OnClickListener(){
公共void onClick(对话框接口对话框,
int(按钮){
dialog.cancel();
字符串SSID[]=mPairedListView
.getItemAtPosition(position).toString()
.split(“\n”);
networkSSID=SSID[1];
Log.i(“networkSSID==”,“”+networkSSID);
conf.SSID=“\”+网络SSID+“\”;
//conf.preSharedKey=“\”“+
//edt\u pass.getText().toString()+“\”;
wifiManager.addNetwork(conf);
List=wifiManager
.getConfiguredNetworks();
Log.i(“列表:”、“+List”);
用于(无线配置i:列表){
如果(i.SSID!=null
&&i.SSID.等于(“\”+网络SSID
+ "\"")) {
wifiManager.disconnect();
Log.i(“i.networkId:”
+i.网络ID);
wifiManager.enableNetwork(即networkId,
正确的);
wifiManager.reconnect();
打破
}
}
}
});
alert.setNegativeButton(“取消”,
新建DialogInterface.OnClickListener(){
公共void onClick(对话框接口对话框,
int(按钮){
dialog.cancel();
字符串路径=“/mnt/sdcard/testpdf.pdf”;
文件f=新文件(路径)//
Uri imageUri=Uri.fromFile(f);
意向打印意向=新意向(
这个,,
PrintDialogActivity.class);
printIntent.setDataAndType(imageUri,
"申请表格(pdf格式);;
printIntent.putExtra(“标题”、“Mitul文件”);
startActivity(printIntent);
}
});
alert.show();
}
});
WifiScan();
}
私有void WifiScan(){
if(wifiManager.isWifiEnabled()==true){
getCurrentSsid(MainActivity.this);
设置适配器(MPairedDeviceArrayaAdapter);
}否则{
AlertDialog.Builder=新建AlertDialog.Builder(
主要活动(本);
setMessage(“未连接..是否要启用它?”)
.setCancelable(错误)
.setPositiveButton(“是”,
新建DialogInterface.OnClickListener(){
公共void onClick(对话框接口对话框,
int id){
dialog.cancel();
新建Get_Wifi()。执行(“”);
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<Button
    android:id="@+id/btn_refresh"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Refresh" />

<ListView
    android:id="@+id/paired_devices"
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_margin="10dp"
    android:layout_marginBottom="10dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_weight="1"
    android:smoothScrollbar="true" />
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/title_paired_devices"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:padding="5dip"
android:textSize="18dip" />
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<EditText
    android:id="@+id/edt_pass"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:gravity="center_vertical"
    android:hint="Wifi password"
    android:inputType="text"
    android:padding="5dp"
    android:singleLine="true"
    android:textSize="15sp" />
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<WebView
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />
public class MainActivity extends Activity {
    WifiManager wifi;
    Button buttonScan;
    Button buttonConnect;
    int size = 0;
    String ITEM_KEY = "key";
    List<ScanResult> results;

    ///// ------------------------------------ NETWORK CREDENTIALS

    String networkSSID = "your SSID";
    String networkPass = "password";
    WifiManager wifiManager ;


    ///// ------------------------------------ NETWORK CREDENTIALS

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        buttonScan = (Button) findViewById(R.id.button_Scan);
        buttonConnect = (Button)findViewById(R.id.button_Connect);

        if (wifi.isWifiEnabled() == false) {
            Toast.makeText(getApplicationContext(),
                    "wifi is disabled..making it enabled", Toast.LENGTH_LONG)
                    .show();
            wifi.setWifiEnabled(true);
        }

        ///// ---------------------------- Connecting Code

        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + networkSSID + "\""; 

        conf.preSharedKey = "\""+ networkPass +"\"";

        wifiManager = (WifiManager)MainActivity.this.getSystemService(Context.WIFI_SERVICE); 
        wifiManager.addNetwork(conf);

        ///// ---------------------------- Connecting Code

        buttonScan.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                wifi.startScan();
                for (ScanResult sx : wifi.getScanResults()) {
                    System.out.println("Point - " + sx);
                }

            }
        });


        buttonConnect.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
                for( WifiConfiguration i : list ) {
                    if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
                         wifiManager.disconnect();
                         wifiManager.enableNetwork(i.networkId, true);
                         wifiManager.reconnect();               

                         break;
                    }           
                 }

            }
        });
    }
}