2013-10-28 75 views
-1

我正在開發一個應用程序,首先我們必須搜索並連接可用的wifi網絡。我已經顯示無線網絡列表。所以,我想從那個列表連接那個特定的wifi。如何連接到Android的特定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; 
}} 

佈局:

activity_main:

<?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" /> 

DEVICE_NAME:

<?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" /> 

password_layout:

<?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" /> 

print_dialog:

<?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" /> 

回答

1

試試這個代碼。

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

      } 
     }); 
    } 
} 
+0

從目前的無線網絡斷開連接,但無法重新選擇的無線網絡連接.... –

+0

把你的代碼,因爲這個代碼是爲我工作。 – Hemant

+0

看我的代碼,告訴我有什麼問題! –