[SCM] Multi-format 1D/2D barcode image processing library branch, upstream, updated. 24d4480bc48cf9eabf7b2bd2f528248b0e458809

vikrama vikrama at 59b500cc-1b3d-0410-9834-0bbf25fbcc57
Wed Aug 4 01:32:02 UTC 2010


The following commit has been merged in the upstream branch:
commit 4cbbf3bf20e39925ade3611213d757f5b3ff65f5
Author: vikrama <vikrama at 59b500cc-1b3d-0410-9834-0bbf25fbcc57>
Date:   Tue Jun 15 03:49:49 2010 +0000

    Android activity to add a network, and all associated code for dealing
    with WIFI: schemes on the Android side.
    
     Things to be done:
    1. Much more testing.
    2. Implement SB and test it well.
    3. Clean up the UI to make it beautiful.
    4. Figure out what to do when the network is connected: exit the
       Barcode Scanner?  Currently, the activity kills itself, restoring
       camera capture.
    5. Publicize the WIFI: scheme.
    
    
    
    git-svn-id: http://zxing.googlecode.com/svn/trunk@1425 59b500cc-1b3d-0410-9834-0bbf25fbcc57

diff --git a/android/AndroidManifest.xml b/android/AndroidManifest.xml
index 501a15a..2c28e2c 100755
--- a/android/AndroidManifest.xml
+++ b/android/AndroidManifest.xml
@@ -95,6 +95,15 @@ versionName is 2.31, 2.4, or 3.0. -->
         <category android:name="android.intent.category.DEFAULT"/>
       </intent-filter>
     </activity>
+    <activity android:name=".wifi.WifiActivity"
+              android:label="@string/wa_name"
+              android:screenOrientation="landscape"
+              android:configChanges="orientation|keyboardHidden">
+      <intent-filter>
+        <action android:name="com.google.zxing.client.android.WIFI_CONNECT"/>
+        <category android:name="android.intent.category.DEFAULT"/>
+      </intent-filter>
+    </activity>
     <activity android:name=".share.ShareActivity"
               android:label="@string/share_name"
               android:screenOrientation="user">
@@ -133,4 +142,11 @@ versionName is 2.31, 2.4, or 3.0. -->
   <uses-permission android:name="android.permission.VIBRATE"/>
   <uses-permission android:name="android.permission.FLASHLIGHT"/>
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
+
+  <!-- Wifi related  -->
+  <uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>
+  <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
+  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
+  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
+
 </manifest>
diff --git a/android/res/layout/network.xml b/android/res/layout/network.xml
new file mode 100644
index 0000000..8ca7665
--- /dev/null
+++ b/android/res/layout/network.xml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="utf-8"?>
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+	android:orientation="vertical" android:layout_width="fill_parent"
+	android:layout_height="fill_parent">
+<!--	<ImageView android:id="@+id/imageStatus"-->
+<!--		android:layout_width="wrap_content" android:layout_height="wrap_content"-->
+<!--		android:layout_gravity="center_horizontal" android:padding="10dip"-->
+<!--		android:src="@drawable/up" />-->
+		
+			<TextView android:layout_width="wrap_content"
+		android:layout_height="wrap_content" android:id="@+id/networkStatus"
+		android:text="Status" android:textSize="20dip"  android:padding="8dip"
+		android:layout_gravity="center_horizontal|bottom" />
+</LinearLayout>
diff --git a/android/res/values-de/strings.xml b/android/res/values-de/strings.xml
index 7bcc6e9..5d0cf9a 100644
--- a/android/res/values-de/strings.xml
+++ b/android/res/values-de/strings.xml
@@ -105,6 +105,7 @@
   <string name="result_sms">SMS Addresse gefunden</string>
   <string name="result_tel">Telefonnummer gefunden</string>
   <string name="result_text">Text gefunden</string>
+  <string name="result_wifi">Wifi konfiguration gefunden</string>
   <string name="result_uri">URL gefunden</string>
   <string name="history_title">Historie</string>
   <string name="history_clear_text">Historie löschen</string>
@@ -114,4 +115,4 @@
   <string name="share_name">Weitergabe mittels Barcode</string>
   <string name="title_about">Barcode Scanner v</string>
   <string name="zxing_url">http://code.google.com/p/zxing</string>
-</resources>
\ No newline at end of file
+</resources>
diff --git a/android/res/values-es/strings.xml b/android/res/values-es/strings.xml
index 2812cff..ab490c5 100644
--- a/android/res/values-es/strings.xml
+++ b/android/res/values-es/strings.xml
@@ -105,6 +105,7 @@
   <string name="result_sms">Dirección de SMS encontrado</string>
   <string name="result_tel">Número de teléfono encontrado</string>
   <string name="result_text">Texto encontrado</string>
+  <string name="result_wifi">Wifi configuración encontrado</string>
   <string name="result_uri">URL encontrado</string>
   <string name="history_title">Historia</string>
   <string name="history_clear_text">Borrar historial</string>
@@ -114,4 +115,4 @@
   <string name="share_name">Compartir por códigos de barras</string>
   <string name="title_about">Escáner de código de barras v</string>
   <string name="zxing_url">http://code.google.com/p/zxing</string>
-</resources>
\ No newline at end of file
+</resources>
diff --git a/android/res/values/strings.xml b/android/res/values/strings.xml
index a6dca4f..26ae112 100755
--- a/android/res/values/strings.xml
+++ b/android/res/values/strings.xml
@@ -44,6 +44,7 @@
   <string name="button_share_contact">Contact</string>
   <string name="button_show_map">Show map</string>
   <string name="button_sms">Send SMS</string>
+  <string name="button_wifi">Connect to Network</string>
   <string name="button_web_search">Web search</string>
   <string name="contents_contact">Contact info</string>
   <string name="contents_email">Email address</string>
@@ -104,14 +105,17 @@
   <string name="result_product">Found product</string>
   <string name="result_sms">Found SMS address</string>
   <string name="result_tel">Found phone number</string>
-  <string name="result_text">Found plain text</string>
   <string name="result_uri">Found URL</string>
+  <string name="result_wifi">Found Wifi Configuration</string>
+  <string name="result_text">Found plain text</string>
   <string name="history_title">History</string>
   <string name="history_clear_text">Clear history</string>
   <string name="history_send">Send history</string>
   <string name="history_email_title">Barcode Scanner history</string>
+  
+  <string name="wa_name">Wifi Connection</string>
   <string name="sbc_name">Google Book Search</string>
   <string name="share_name">Share via barcode</string>
   <string name="title_about">Barcode Scanner v</string>
   <string name="zxing_url">http://code.google.com/p/zxing</string>
-</resources>
\ No newline at end of file
+</resources>
diff --git a/android/src/com/google/zxing/client/android/Intents.java b/android/src/com/google/zxing/client/android/Intents.java
index 0830ba4..30ef043 100755
--- a/android/src/com/google/zxing/client/android/Intents.java
+++ b/android/src/com/google/zxing/client/android/Intents.java
@@ -148,6 +148,32 @@ public final class Intents {
     }
   }
 
+  public static final class WifiConnect {
+	    /**
+	     * Use Google Book Search to search the contents of the book provided.
+	     */
+	    public static final String ACTION = "com.google.zxing.client.android.WIFI_CONNECT";
+
+	    /**
+	     * The network to connect to, all the configuration provided here.
+	     */
+	    public static final String SSID = "SSID";
+
+	    /**
+	     * The network to connect to, all the configuration provided here.
+	     */
+	    public static final String TYPE = "TYPE";
+
+	    /**
+	     * The network to connect to, all the configuration provided here.
+	     */
+	    public static final String PASSWORD = "PASSWORD";
+
+	    private WifiConnect() {
+	    }
+	  }
+
+
   public static final class Share {
     /**
      * Give the user a choice of items to encode as a barcode, then render it as a QR Code and
diff --git a/android/src/com/google/zxing/client/android/result/ResultHandler.java b/android/src/com/google/zxing/client/android/result/ResultHandler.java
index 97e57e1..5f0f28f 100644
--- a/android/src/com/google/zxing/client/android/result/ResultHandler.java
+++ b/android/src/com/google/zxing/client/android/result/ResultHandler.java
@@ -22,8 +22,10 @@ import com.google.zxing.client.android.LocaleManager;
 import com.google.zxing.client.android.PreferencesActivity;
 import com.google.zxing.client.android.R;
 import com.google.zxing.client.android.book.SearchBookContentsActivity;
+import com.google.zxing.client.android.wifi.WifiActivity;
 import com.google.zxing.client.result.ParsedResult;
 import com.google.zxing.client.result.ParsedResultType;
+import com.google.zxing.client.result.WifiParsedResult;
 
 import android.app.Activity;
 import android.app.AlertDialog;
@@ -321,6 +323,15 @@ public abstract class ResultHandler {
     launchIntent(intent);
   }
 
+  final void wifiConnect(WifiParsedResult wifiResult) {
+    Intent intent = new Intent(Intents.WifiConnect.ACTION);
+    intent.setClassName(activity, WifiActivity.class.getName());
+    putExtra(intent, Intents.WifiConnect.SSID, wifiResult.getSsid());
+    putExtra(intent, Intents.WifiConnect.TYPE, wifiResult.getNetworkEncryption());
+    putExtra(intent, Intents.WifiConnect.PASSWORD, wifiResult.getPassword());
+    launchIntent(intent);
+  }
+
   final void openURL(String url) {
     launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
   }
@@ -395,5 +406,4 @@ public abstract class ResultHandler {
     }
     return customProductSearch;
   }
-
-}
+}
\ No newline at end of file
diff --git a/android/src/com/google/zxing/client/android/result/ResultHandlerFactory.java b/android/src/com/google/zxing/client/android/result/ResultHandlerFactory.java
index eeaacca..933ac6a 100644
--- a/android/src/com/google/zxing/client/android/result/ResultHandlerFactory.java
+++ b/android/src/com/google/zxing/client/android/result/ResultHandlerFactory.java
@@ -43,6 +43,8 @@ public final class ResultHandlerFactory {
       return new ProductResultHandler(activity, result);
     } else if (type.equals(ParsedResultType.URI)) {
       return new URIResultHandler(activity, result);
+    } else if (type.equals(ParsedResultType.WIFI)) {
+      return new WifiResultHandler(activity, result);
     } else if (type.equals(ParsedResultType.TEXT)) {
       return new TextResultHandler(activity, result);
     } else if (type.equals(ParsedResultType.GEO)) {
diff --git a/android/src/com/google/zxing/client/android/result/WifiResultHandler.java b/android/src/com/google/zxing/client/android/result/WifiResultHandler.java
new file mode 100644
index 0000000..ef6fbaa
--- /dev/null
+++ b/android/src/com/google/zxing/client/android/result/WifiResultHandler.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2008 ZXing authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.zxing.client.android.result;
+
+import android.app.Activity;
+
+import com.google.zxing.client.android.R;
+import com.google.zxing.client.result.ParsedResult;
+import com.google.zxing.client.result.WifiParsedResult;
+
+/**
+ * Handles address book entries.
+ *
+ * @author viki at google.com (Vikram Aggarwal)
+ */
+public final class WifiResultHandler extends ResultHandler {
+	Activity parentActivity = null;
+	public WifiResultHandler(Activity activity, ParsedResult result) {
+		super(activity, result);
+		parentActivity = activity;
+	}
+
+	@Override
+	public int getButtonCount() {
+		// We just need one button, and that is to configure the wireless.  This could change in the future.
+		return 1;
+	}
+
+	@Override
+	public int getButtonText(int index) {
+		switch (index) {
+		case 0:
+			return R.string.button_wifi;
+		default:
+			throw new ArrayIndexOutOfBoundsException();
+		}
+	}
+
+	@Override
+	public void handleButtonPress(int index) {
+		// Get the underlying wifi config
+		WifiParsedResult wifiResult = (WifiParsedResult) getResult();
+		switch (index) {
+		case 0:
+			wifiConnect(wifiResult);
+			break;
+		default:
+			break;
+		}
+	}
+
+	// Display the name of the network and the network type to the user.
+	@Override
+	public CharSequence getDisplayContents() {
+		WifiParsedResult wifiResult = (WifiParsedResult) getResult();
+		StringBuffer contents = new StringBuffer();
+		ParsedResult.maybeAppend(wifiResult.getSsid(), contents);
+		ParsedResult.maybeAppend(wifiResult.getNetworkEncryption(), contents);
+		return contents.toString();
+	}
+
+	@Override
+	public int getDisplayTitle() {
+		return R.string.result_wifi;
+	}
+}
\ No newline at end of file
diff --git a/android/src/com/google/zxing/client/android/wifi/Killer.java b/android/src/com/google/zxing/client/android/wifi/Killer.java
new file mode 100644
index 0000000..8eba9cc
--- /dev/null
+++ b/android/src/com/google/zxing/client/android/wifi/Killer.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2010 ZXing authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.zxing.client.android.wifi;
+
+import java.util.Timer;
+import java.util.TimerTask;
+
+import android.app.Activity;
+import android.os.Handler;
+
+/**
+ * Close the parent after a delay.
+ * @author Vikram Aggarwal
+ *
+ */
+class Killer implements Runnable {
+  // Three full seconds
+  final int delay_millis = 3 * 1000;
+  Activity parent = null;
+  public Killer(Activity parent) {
+    this.parent = parent;
+  }
+  @Override
+  public void run() {
+    final Handler handler = new Handler();
+    Timer t = new Timer();
+    t.schedule(new TimerTask() {
+      @Override
+      public void run() {
+        handler.post(new Runnable() {
+          public void run() {
+            parent.finish();
+          }
+        });
+      }
+    }, delay_millis);
+  }
+}
diff --git a/android/src/com/google/zxing/client/android/wifi/NetworkSetting.java b/android/src/com/google/zxing/client/android/wifi/NetworkSetting.java
new file mode 100644
index 0000000..955088e
--- /dev/null
+++ b/android/src/com/google/zxing/client/android/wifi/NetworkSetting.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2010 ZXing authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.zxing.client.android.wifi;
+
+import java.util.Vector;
+
+import com.google.zxing.client.android.wifi.WifiActivity.NetworkType;
+
+/**
+ * Everything we could get from the barcode is to be here
+ * @author Vikram Aggarwal
+ *
+ */
+class NetworkSetting {
+  // The ancillary network setting from the barcode
+  private NetworkType mNetworkType;
+  // The password this ssid has
+  private String mPassword;
+  // The ssid we read from the barcode
+  private String mSsid;
+
+  static String[] toStringArray(Vector<String> strings) {
+    int size = strings.size();
+    String[] result = new String[size];
+    for (int j = 0; j < size; j++) {
+      result[j] = (String) strings.elementAt(j);
+    }
+    return result;
+  }
+  /**
+   * Create a new NetworkSetting object.
+   * @param ssid: The SSID
+   * @param password: Password for the setting, blank if unsecured network
+   * @param networkType: WPA for WPA/WPA2, or WEP for WEP or unsecured
+   */
+  public NetworkSetting(String ssid, String password, NetworkType networkType){
+    mSsid = ssid;
+    mPassword = password;
+    mNetworkType = networkType;
+  }
+
+  public NetworkType getNetworkType() {
+    return mNetworkType;
+  }
+  public String getPassword() {
+    return mPassword;
+  }
+
+  public String getSsid() {
+    return mSsid;
+  }
+}
\ No newline at end of file
diff --git a/android/src/com/google/zxing/client/android/wifi/NetworkUtil.java b/android/src/com/google/zxing/client/android/wifi/NetworkUtil.java
new file mode 100644
index 0000000..0fbad03
--- /dev/null
+++ b/android/src/com/google/zxing/client/android/wifi/NetworkUtil.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2010 ZXing authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.zxing.client.android.wifi;
+
+import android.text.TextUtils;
+
+/**
+ * Try with:
+ * http://chart.apis.google.com/chart?cht=qr&chs=240x240&chl=WIFI:S:linksys;P:mypass;T:WPA;;
+ * @author Vikram Aggarwal
+ *
+ * TODO(vikrama): Test with binary ssid or password.
+ */
+public final class NetworkUtil {
+  /**
+   * Encloses the incoming string inside double quotes, if it isn't already quoted.
+   * @param string: the input string
+   * @return a quoted string, of the form "input".  If the input string is null, it returns null as well.
+   */
+  public static String convertToQuotedString(String string) {
+    if (string == null){
+      return null;
+    }
+    if (TextUtils.isEmpty(string)) {
+      return "";
+    }
+    final int lastPos = string.length() - 1;
+    if (lastPos < 0 || (string.charAt(0) == '"' && string.charAt(lastPos) == '"')) {
+      return string;
+    }        
+    return "\"" + string + "\"";
+  }
+
+  private static boolean isHex(String key) {
+    if (key == null){
+      return false;
+    }
+    for (int i = key.length() - 1; i >= 0; i--) {
+      final char c = key.charAt(i);
+      if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f')) {
+        return false;
+      }
+    }        
+    return true;
+  }
+
+  /**
+   * Check if wepKey is a valid hexadecimal string.
+   * @param wepKey the input to be checked
+   * @return true if the input string is indeed hex or empty.  False if the input string is non-hex or null.
+   */
+  public static boolean isHexWepKey(String wepKey) {
+    if (wepKey == null)
+      return false;
+    final int len = wepKey.length();
+    // WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?)
+    if (len != 10 && len != 26 && len != 58) {
+      return false;
+    }
+    return isHex(wepKey);
+  }	
+}
diff --git a/android/src/com/google/zxing/client/android/wifi/WifiActivity.java b/android/src/com/google/zxing/client/android/wifi/WifiActivity.java
new file mode 100644
index 0000000..ae8dc64
--- /dev/null
+++ b/android/src/com/google/zxing/client/android/wifi/WifiActivity.java
@@ -0,0 +1,260 @@
+/*
+ * Copyright (C) 2010 ZXing authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.zxing.client.android.wifi;
+
+import java.util.List;
+
+import android.app.Activity;
+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.WifiManager;
+import android.os.Bundle;
+import android.util.Log;
+import android.widget.ImageView;
+import android.widget.TextView;
+
+import com.google.zxing.client.android.Intents;
+import com.google.zxing.client.android.R;
+import com.google.zxing.client.android.wifi.Killer;
+import com.google.zxing.client.android.wifi.NetworkUtil;
+import com.google.zxing.client.android.wifi.NetworkSetting;
+
+/**
+ * A new activity showing the progress of Wifi connection
+ * @author Vikram Aggarwal
+ *
+ */
+public class WifiActivity extends Activity  {
+  public static enum NetworkType {
+    NETWORK_WEP, NETWORK_WPA,
+  }
+
+  /**
+   * Get a broadcast when the network is connected, and kill the activity.
+   */
+  class ConnectedReceiver extends BroadcastReceiver {
+    Activity parent = null;
+    public ConnectedReceiver(WifiActivity wifiActivity) {
+      parent = wifiActivity;
+    }
+
+    @Override
+    public void onReceive(Context context, Intent intent) {
+      if (intent.getAction().equals(android.net.ConnectivityManager.CONNECTIVITY_ACTION)){
+        ConnectivityManager con = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
+        NetworkInfo[] s = con.getAllNetworkInfo();
+        for (NetworkInfo i : s){
+          if (i.getTypeName().contentEquals("WIFI")){
+            NetworkInfo.State state = i.getState();
+            if (state == NetworkInfo.State.CONNECTED){
+              statusT.setText("Connected!");
+              Killer delay_kill = new Killer(parent);
+              delay_kill.run();
+            }
+          }
+        }
+      }
+    }
+  }
+
+  private static final String tag = "NetworkActivity";
+  WifiManager mWifiManager = null;
+  TextView statusT = null;
+  ImageView statusI = null;
+  ConnectedReceiver rec = null;
+  boolean debug = true;
+
+  private int changeNetwork(NetworkSetting setting) {
+    // If the password is empty, this is an unencrypted network
+    if (setting.getPassword() == null || setting.getPassword() == "") {
+      return changeNetworkUnEncrypted(setting);
+    }
+    if (setting.getNetworkType() == NetworkType.NETWORK_WPA) {
+      return changeNetworkWPA(setting); 
+    } else {
+      return changeNetworkWEP(setting);
+    }
+  }
+
+  private WifiConfiguration changeNetworkCommon(NetworkSetting input){
+    statusT.setText("Creating settings...");
+    if (debug) {
+      Log.d(tag, "adding new configuration: \nSSID: " + input.getSsid() + "\nPassword: \""
+          + input.getPassword() + "\"\nType: " + input.getNetworkType());
+    }
+    WifiConfiguration config = new WifiConfiguration();
+
+    config.allowedAuthAlgorithms.clear();
+    config.allowedGroupCiphers.clear();
+    config.allowedKeyManagement.clear();
+    config.allowedPairwiseCiphers.clear();
+    config.allowedProtocols.clear();
+
+    // Android API insists that an ascii SSID must be quoted to be correctly handled.
+    config.SSID = NetworkUtil.convertToQuotedString(input.getSsid());	
+    config.hiddenSSID = true;
+    return config;
+  }
+
+  private int requestNetworkChange(WifiConfiguration config){		
+    boolean disableOthers = false;
+    statusT.setText("Changing Network...");
+    return updateNetwork(config, disableOthers);
+  }
+
+  // Adding a WEP network
+  private int changeNetworkWEP(NetworkSetting input) {
+    WifiConfiguration config = changeNetworkCommon(input);
+    if (NetworkUtil.isHexWepKey(input.getPassword())) {
+      config.wepKeys[0] = input.getPassword();
+    } else {
+      config.wepKeys[0] = NetworkUtil.convertToQuotedString(input.getPassword());
+    }
+    config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
+    config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
+    config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
+    config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
+    config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
+    config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
+    config.wepTxKeyIndex = 0;
+    return requestNetworkChange(config);
+  }
+
+  // Adding a WPA or WPA2 network
+  private int changeNetworkWPA(NetworkSetting input) {
+    WifiConfiguration config = changeNetworkCommon(input);
+    config.preSharedKey = NetworkUtil.convertToQuotedString(input.getPassword());
+    config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
+    config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
+    // For WPA
+    config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
+    // For WPA2
+    config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
+    return requestNetworkChange(config);
+  }
+
+  // Adding an open, unsecured network
+  private int changeNetworkUnEncrypted(NetworkSetting input){
+    WifiConfiguration config = changeNetworkCommon(input);
+    if (debug){
+      Log.d(tag, "Empty password prompting a simple account setting");
+    }
+    config.wepKeys[0] = "";
+    config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
+    config.wepTxKeyIndex = 0;
+    return requestNetworkChange(config);
+  }
+
+  /**
+   * If the given ssid name exists in the settings, then change its password to the one given here, and save
+   * @param ssid
+   */
+  private WifiConfiguration findNetworkInExistingConfig(String ssid){
+    List <WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
+    for (int i = 0; i < existingConfigs.size(); i++){
+      if (existingConfigs.get(i).SSID.compareTo(ssid) == 0){
+        return existingConfigs.get(i);
+      }
+    }
+    return null;
+  }
+
+  @Override
+  protected void onCreate(Bundle savedInstanceState) {
+    super.onCreate(savedInstanceState);
+
+    Intent intent = getIntent();
+    if (intent == null || (!intent.getAction().equals(Intents.WifiConnect.ACTION))) {
+      finish();
+      return;
+    }
+
+    String ssid = intent.getStringExtra(Intents.WifiConnect.SSID);
+    String password = intent.getStringExtra(Intents.WifiConnect.PASSWORD);
+    String networkType = intent.getStringExtra(Intents.WifiConnect.TYPE);
+
+    // TODO(vikrama): Error checking here, to ensure ssid exists.
+    NetworkType networkT = null;
+    if (networkType.contains("WPA")) {
+      networkT = NetworkType.NETWORK_WPA;
+    }
+    else if (networkType.contains("WEP")) {
+      networkT = NetworkType.NETWORK_WEP;
+    }
+    else {
+      // Got an incorrect network type
+      finish();
+      return;
+    }
+
+    setContentView(R.layout.network);
+    statusT = (TextView) findViewById(R.id.networkStatus);
+    // This is not available before onCreate
+    mWifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
+
+    // So we know when the network changes
+    rec = new ConnectedReceiver(this);
+    registerReceiver(rec, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
+
+    if (password == null)
+      password = "";
+    if (debug) {
+      Log.d(tag, "adding new configuration: \nSSID: " + ssid + "\nPassword: \"" + password + "\"\nType: " + networkT);
+    }
+    NetworkSetting setting = new NetworkSetting(ssid, password, networkT);
+    changeNetwork(setting);
+  }
+
+  @Override
+  protected void onDestroy() {
+    super.onDestroy();
+    if (rec != null)
+      unregisterReceiver(rec);
+    rec = null;
+  }
+
+  /**
+   * Update the network: either create a new network or modify an existing network
+   * @param config: the new network configuration
+   * @param disableOthers: true if other networks must be disabled
+   * @return network ID of the connected network.
+   */
+  private int updateNetwork(WifiConfiguration config, boolean disableOthers){
+    WifiConfiguration existing = findNetworkInExistingConfig(config.SSID);
+    int networkId;
+    if (existing == null){
+      statusT.setText("Creating network...");
+      networkId = mWifiManager.addNetwork(config);
+    } else {
+      statusT.setText("Modifying network...");
+      networkId = mWifiManager.updateNetwork(config);
+    }
+    if (networkId == -1){
+      return networkId;
+    }
+    if (!mWifiManager.enableNetwork(networkId, disableOthers)) {
+      return -1;
+    }
+    mWifiManager.saveConfiguration();
+    return networkId;
+  }
+}
\ No newline at end of file

-- 
Multi-format 1D/2D barcode image processing library



More information about the Pkg-google-commits mailing list