无法连接到新的无线网络 [英] Unable to connect to new wifi network

查看:223
本文介绍了无法连接到新的无线网络的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用的应用程序,而不是与下面code Android的无线网络设置连接到一个新的WIFI网络,但似乎有关Android SDK中的类只让你连接已经存储在Android和不向任何网络新的网络。我是不是正确的思维是什么?

下面是我的code

清单XML:

 < XML版本=1.0编码=UTF-8&GT?;
<舱单的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
包=unitedspark.testapp>
<使用-权限的Andr​​oid:名称=android.permission.CHANGE_WIFI_STATE/>
<使用-权限的Andr​​oid:名称=android.permission.INTERNET对/>
<使用-权限的Andr​​oid:名称=android.permission.ACCESS_WIFI_STATE/>
<使用-权限的Andr​​oid:名称=android.permission.ACCESS_NETWORK_STATE/>
<应用
    机器人:allowBackup =真
    机器人:图标=@纹理映射/ ic_launcher
    机器人:标签=@字符串/ APP_NAME
    机器人:主题=@风格/ AppTheme>
    <活动
        机器人:名称=。WiFiConnect
        机器人:标签=@字符串/ APP_NAME>
        <意向滤光器>
            <作用机器人:名称=android.intent.action.MAIN/>
            <类机器人:名称=android.intent.category.LAUNCHER/>
        &所述; /意图滤光器>
    < /活性GT;
< /用途>
<接收机器人:名称=。WiFiChangeReciever>
    <意向滤光器>
        <作用机器人:名称=android.net.wifi.STATE_CHANGE/>
        <作用机器人:名称=android.net.conn.CONNECTIVITY_CHANGE/>
    &所述; /意图滤光器>
< /接收器>
< /舱单>
 

活动的XML:

 < RelativeLayout的的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
的xmlns:工具=htt​​p://schemas.android.com/tool​​s机器人:layout_width =match_parent
机器人:layout_height =match_parent机器人:以下属性来=@扪/ activity_horizo​​ntal_margin
机器人:paddingRight =@扪/ activity_horizo​​ntal_margin
机器人:paddingTop =@扪/ activity_vertical_margin
机器人:paddingBottom会=@扪/ activity_vertical_margin工具:上下文=。WiFiConnect
机器人:ID =@ + ID / WiFiConnectLayout>

<的TextView
    机器人:ID =@ + ID /连接
    机器人:layout_width =WRAP_CONTENT
    机器人:layout_height =WRAP_CONTENT
    机器人:文本=连接到
    机器人:textAppearance =机器人:ATTR / textAppearanceLarge
    机器人:layout_marginTop =63dp
    机器人:layout_alignParentTop =真
    机器人:layout_centerHorizo​​ntal =真/>

<按钮
    机器人:layout_width =WRAP_CONTENT
    机器人:layout_height =WRAP_CONTENT
    机器人:文本=新的WiFi网络
    机器人:ID =@ + ID / btnConnectNetwork1
    机器人:layout_alignTop =@ + ID / btnDisconnect
    机器人:layout_alignParentLeft =真
    机器人:layout_alignParentStart =真/>

<按钮
    机器人:layout_width =WRAP_CONTENT
    机器人:layout_height =WRAP_CONTENT
    机器人:文本=断开
    机器人:ID =@ + ID / btnDisconnect
    机器人:layout_marginTop =108dp
    机器人:layout_below =@ + ID / btnConnectNetwork1
    机器人:layout_toRightOf =@ + ID / btnConnectNetwork1
    机器人:layout_toEndOf =@ + ID / btnConnectNetwork1/>

<的TextView
    机器人:ID =@ + ID / txtStatus
    机器人:layout_width =WRAP_CONTENT
    机器人:layout_height =WRAP_CONTENT
    机器人:文本=无线状态
    机器人:textAppearance =机器人:ATTR / textAppearanceLarge
    机器人:layout_marginTop =67dp
    机器人:layout_below =@ + ID / btnDisconnect
    机器人:layout_centerHorizo​​ntal =真/>
 

Java文件:

 包unitedspark.testapp;

进口android.content.BroadcastReceiver;
进口android.content.Context;
进口android.content.Intent;
进口android.content.IntentFilter;
进口android.net.ConnectivityManager;
进口android.net.NetworkInfo;
进口android.net.wifi.WifiConfiguration;
进口android.net.wifi.WifiInfo;
进口android.net.wifi.WifiManager;
进口android.support.v7.app.ActionBarActivity;
进口android.os.Bundle;
进口android.view.Menu;
进口android.view.MenuItem;
进口android.view.View;
进口android.widget.Button;
进口android.widget.TextView;
进口android.widget.Toast;

进口java.util.Arrays中;
进口的java.util.List;


公共类WiFiConnect扩展ActionBarActivity {

@覆盖
保护无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_wi_fi_connect);

    this.registerReceiver(this.mConnReceiver,新的IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

    按钮btnConnectNetwork1 =(按钮)findViewById(R.id.btnConnectNetwork1);
    btnConnectNetwork1.setOnClickListener(新View.OnClickListener(){
        公共无效的onClick(视图v){
            //执行上的点击动作
            TextView的txtStatus =(TextView中)findViewById(R.id.txtStatus);

            WifiManager无线=(WifiManager)getSystemService(Context.WIFI_SERVICE);
            如果(!wifi.isWifiEnabled()){
                wifi.setWifiEnabled(真正的);
            }

            txtStatus.setText(尝试连接......);

            ConnectToNetworkWEP(SSID1,密码1);
        }
    });

    按钮btnDisconnect =(按钮)findViewById(R.id.btnDisconnect);
    btnDisconnect.setOnClickListener(新View.OnClickListener(){
        公共无效的onClick(视图v){
            //执行上的点击动作
            TextView的txtStatus =(TextView中)findViewById(R.id.txtStatus);
            txtStatus.setText(试图断开......);

            WifiManager wifiManager =(WifiManager)getSystemService(Context.WIFI_SERVICE);
            wifiManager.disconnect();
            wifiManager.setWifiEnabled(假);
            txtStatus.setText(断开连接!);
        }
    });


}

私人的BroadcastReceiver mConnReceiver =新的BroadcastReceiver(){
    公共无效的onReceive(上下文的背景下,意图意图){

        的NetworkInfo currentNetworkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

        如果(currentNetworkInfo.isConnected()){
            WifiManager wifiManager =(WifiManager)context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();

            Toast.makeText(getApplicationContext(),广播连接:+ wifiInfo.getSSID(),Toast.LENGTH_LONG).show();
        } 其他 {
            Toast.makeText(getApplicationContext(),广播未连接,Toast.LENGTH_LONG).show();
        }
    }
};


@覆盖
公共布尔onCreateOptionsMenu(功能菜单){
    //充气菜单;这增加了项目操作栏,如果它是present。
    。getMenuInflater()膨胀(R.menu.menu_wi_fi_connect,菜单);
    返回true;
}

@覆盖
公共布尔onOptionsItemSelected(菜单项项){
    //处理动作栏项目点击这里。将操作栏
    //自动在主/向上按钮操作的点击,只要
    //你在AndroidManifest.xml中指定一个父活动。
    INT的id = item.getItemId();

    // noinspection SimplifiableIfStatement
    如果(ID == R.id.action_settings){
        返回true;
    }

    返回super.onOptionsItemSelected(项目);
}

公共布尔ConnectToNetworkWEP(字符串networkSSID,字符串密码)
{
    尝试 {
        WifiConfiguration的conf =新WifiConfiguration();
        conf.SSID =\+ networkSSID +\; //请注意引号。字符串应包含SSID在引号
        conf.wepKeys [0] =密码; // WEP的密码是十六进制,我们并不需要用引号括起来。
        conf.wepTxKeyIndex = 0;
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);

        WifiManager wifiManager =(WifiManager)this.getApplicationContext()getSystemService(Context.WIFI_SERVICE)。
        wifiManager.addNetwork(CONF);

        名单< WifiConfiguration>表= wifiManager.getConfiguredNetworks();
        对于(WifiConfiguration我:名单){
            如果(i.SSID = NULL和放大器;!&安培; i.SSID.equals(\+ networkSSID +\)){
                wifiManager.disconnect();
                wifiManager.enableNetwork(i.networkId,真正的);
                wifiManager.reconnect();

                    打破;
            }
        }

        // WiFi连接成功,返回true
        返回true;
    }赶上(例外前){
        的System.out.println(Arrays.toString(ex.getStackTrace()));
        返回false;
    }
}
}
 

解决方案

我刚拿到这与我的家庭WiFi网络,WPA2认证工作。

您断开code工作正常原样。我能够反复连接和断开的按钮。

有关您的WEP网络,试试这个:

 公共布尔ConnectToNetworkWEP(字符串networkSSID,字符串密码)
{
    尝试 {
        WifiConfiguration的conf =新WifiConfiguration();
        conf.SSID =\+ networkSSID +\; //请注意引号。字符串应包含SSID在引号
        conf.wepKeys [0] =\+密码+\; //用引号首先尝试

        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        conf.allowedGroupCiphers.set(WifiConfiguration.AuthAlgorithm.OPEN);
        conf.allowedGroupCiphers.set(WifiConfiguration.AuthAlgorithm.SHARED);


        WifiManager wifiManager =(WifiManager)this.getApplicationContext()getSystemService(Context.WIFI_SERVICE)。
        INT networkId = wifiManager.addNetwork(CONF);

        如果(networkId == -1){
            //不带引号再试一次的情况下十六进制密码
            conf.wepKeys [0] =密码;
            networkId = wifiManager.addNetwork(CONF);
        }

        名单< WifiConfiguration>表= wifiManager.getConfiguredNetworks();
        对于(WifiConfiguration我:名单){
            如果(i.SSID = NULL和放大器;!&安培; i.SSID.equals(\+ networkSSID +\)){
                wifiManager.disconnect();
                wifiManager.enableNetwork(i.networkId,真正的);
                wifiManager.reconnect();
                打破;
            }
        }

        // WiFi连接成功,返回true
        返回true;
    }赶上(例外前){
        的System.out.println(Arrays.toString(ex.getStackTrace()));
        返回false;
    }
}
 

下面是为我工作在WPA2的code:

 公共布尔ConnectToNetworkWPA(字符串networkSSID,字符串密码)
    {
        尝试 {
            WifiConfiguration的conf =新WifiConfiguration();
            conf.SSID =\+ networkSSID +\; //请注意引号。字符串应包含SSID在引号

            。CONF preSharedKey =\+密码+\;

            conf.status = WifiConfiguration.Status.ENABLED;
            conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);

            Log.d(连接,conf.SSID ++的conf preSharedKey。);

            WifiManager wifiManager =(WifiManager)this.getApplicationContext()getSystemService(Context.WIFI_SERVICE)。
            wifiManager.addNetwork(CONF);

            Log.d(连接后,conf.SSID ++的conf preSharedKey。);



            名单< WifiConfiguration>表= wifiManager.getConfiguredNetworks();
            对于(WifiConfiguration我:名单){
                如果(i.SSID = NULL和放大器;!&安培; i.SSID.equals(\+ networkSSID +\)){
                    wifiManager.disconnect();
                    wifiManager.enableNetwork(i.networkId,真正的);
                    wifiManager.reconnect();
                    Log.d(重新连接,i.SSID ++的conf preSharedKey。);

                    打破;
                }
            }


            // WiFi连接成功,返回true
            返回true;
        }赶上(例外前){
            的System.out.println(Arrays.toString(ex.getStackTrace()));
            返回false;
        }
    }
 

I am trying to connect to a new wifi network using an app and not android wifi settings with following code, but it seems that relevant android sdk classes only let you connect to network already stored in android and not to any new network. Am i being correct in thinking that?

Here's my code

Manifest XML:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="unitedspark.testapp" >
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".WiFiConnect"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
<receiver android:name=".WiFiChangeReciever" >
    <intent-filter>
        <action android:name="android.net.wifi.STATE_CHANGE" />
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>
</manifest>

Activity XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".WiFiConnect"
android:id="@+id/WiFiConnectLayout">

<TextView
    android:id="@+id/Connect"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Connect To"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:layout_marginTop="63dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New WiFi Network"
    android:id="@+id/btnConnectNetwork1"
    android:layout_alignTop="@+id/btnDisconnect"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Disconnect"
    android:id="@+id/btnDisconnect"
    android:layout_marginTop="108dp"
    android:layout_below="@+id/btnConnectNetwork1"
    android:layout_toRightOf="@+id/btnConnectNetwork1"
    android:layout_toEndOf="@+id/btnConnectNetwork1" />

<TextView
    android:id="@+id/txtStatus"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="WiFi Status"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:layout_marginTop="67dp"
    android:layout_below="@+id/btnDisconnect"
    android:layout_centerHorizontal="true" />

The java file:

package unitedspark.testapp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Arrays;
import java.util.List;


public class WiFiConnect extends ActionBarActivity {

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

    this.registerReceiver(this.mConnReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

    Button btnConnectNetwork1 = (Button) findViewById(R.id.btnConnectNetwork1);
    btnConnectNetwork1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Perform action on click
            TextView txtStatus = (TextView)findViewById(R.id.txtStatus);

            WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            if(!wifi.isWifiEnabled()) {
                wifi.setWifiEnabled(true);
            }

            txtStatus.setText("Trying to connect...");

            ConnectToNetworkWEP("SSID1", "Password1");
        }
    });

    Button btnDisconnect = (Button) findViewById(R.id.btnDisconnect);
    btnDisconnect.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Perform action on click
            TextView txtStatus = (TextView)findViewById(R.id.txtStatus);
            txtStatus.setText("Trying to disconnect...");

            WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            wifiManager.disconnect();
            wifiManager.setWifiEnabled(false);
            txtStatus.setText("Disconnected!");
        }
    });


}

private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {

        NetworkInfo currentNetworkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

        if (currentNetworkInfo.isConnected()) {
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();

            Toast.makeText(getApplicationContext(), "Broadcast Connected:" +  wifiInfo.getSSID(), Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(), "Broadcast Not Connected", Toast.LENGTH_LONG).show();
        }
    }
};


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_wi_fi_connect, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public boolean ConnectToNetworkWEP( String networkSSID, String password )
{
    try {
        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + networkSSID + "\"";   // Please note the quotes. String should contain SSID in quotes
        conf.wepKeys[0] = password;  //WEP password is in hex, we do not need to surround it with quotes.
        conf.wepTxKeyIndex = 0;
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);

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

        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;
            }
        }

        //WiFi Connection success, return true
        return true;
    } catch (Exception ex) {
        System.out.println(Arrays.toString(ex.getStackTrace()));
        return false;
    }
}
}

解决方案

I just got this working with my home WiFi network with WPA2 authentication.

Your disconnect code works fine as is. I was able to repeatedly connect and disconnect with the buttons.

For your WEP network, try this:

public boolean ConnectToNetworkWEP( String networkSSID, String password )
{
    try {
        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + networkSSID + "\"";   // Please note the quotes. String should contain SSID in quotes
        conf.wepKeys[0] = "\"" + password + "\""; //Try it with quotes first

        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        conf.allowedGroupCiphers.set(WifiConfiguration.AuthAlgorithm.OPEN);
        conf.allowedGroupCiphers.set(WifiConfiguration.AuthAlgorithm.SHARED);


        WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        int networkId = wifiManager.addNetwork(conf);

        if (networkId == -1){
            //Try it again with no quotes in case of hex password
            conf.wepKeys[0] = password;
            networkId = wifiManager.addNetwork(conf);
        }

        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;
            }
        }

        //WiFi Connection success, return true
        return true;
    } catch (Exception ex) {
        System.out.println(Arrays.toString(ex.getStackTrace()));
        return false;
    }
}

Here is the code that worked for me on WPA2:

public boolean ConnectToNetworkWPA( String networkSSID, String password )
    {
        try {
            WifiConfiguration conf = new WifiConfiguration();
            conf.SSID = "\"" + networkSSID + "\"";   // Please note the quotes. String should contain SSID in quotes

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

            conf.status = WifiConfiguration.Status.ENABLED;
            conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);

            Log.d("connecting", conf.SSID + " " + conf.preSharedKey);

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

            Log.d("after connecting", conf.SSID + " " + conf.preSharedKey);



            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();
                    Log.d("re connecting", i.SSID + " " + conf.preSharedKey);

                    break;
                }
            }


            //WiFi Connection success, return true
            return true;
        } catch (Exception ex) {
            System.out.println(Arrays.toString(ex.getStackTrace()));
            return false;
        }
    }

这篇关于无法连接到新的无线网络的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆