Bug Fix:
[zxing.git] / android / src / com / google / zxing / client / android / wifi / WifiActivity.java
1 /*
2  * Copyright (C) 2010 ZXing authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.google.zxing.client.android.wifi;
18
19 import java.util.List;
20
21 import android.app.Activity;
22 import android.content.Intent;
23 import android.content.IntentFilter;
24 import android.net.ConnectivityManager;
25 import android.net.wifi.WifiConfiguration;
26 import android.net.wifi.WifiManager;
27 import android.os.Bundle;
28 import android.util.Log;
29 import android.widget.TextView;
30
31 import com.google.zxing.client.android.Intents;
32 import com.google.zxing.client.android.R;
33
34 /**
35  * A new activity showing the progress of Wifi connection
36  *
37  * TODO(viki): Tell the user when the network is not available here
38  * TODO(viki): Incorrect password, could not connect, give an error
39  * 
40  * @author Vikram Aggarwal
41  */
42 public class WifiActivity extends Activity  {
43
44   private static final String TAG = WifiActivity.class.getSimpleName();
45
46   private WifiManager wifiManager;
47   private TextView statusView;
48   private ConnectedReceiver connectedReceiver;
49
50   public enum NetworkType {
51     NETWORK_WEP, NETWORK_WPA, NETWORK_NOPASS, NETWORK_INVALID,
52   }
53
54   private int changeNetwork(NetworkSetting setting) {
55     // All the ways this can be wrong:
56
57     // If the SSID is empty, throw an error and return
58     if (setting.getSsid() == null || setting.getSsid().length() == 0) {
59       return doError(R.string.wifi_ssid_missing);
60     }
61     // If the network type is invalid
62     if (setting.getNetworkType() == NetworkType.NETWORK_INVALID){
63       return doError(R.string.wifi_type_incorrect);
64     }
65
66     // If the password is empty, this is an unencrypted network
67     if (setting.getPassword() == null || setting.getPassword().length() == 0 ||
68         setting.getNetworkType() == null ||
69         setting.getNetworkType() == NetworkType.NETWORK_NOPASS) {
70       return changeNetworkUnEncrypted(setting);
71     }
72     if (setting.getNetworkType() == NetworkType.NETWORK_WPA) {
73       return changeNetworkWPA(setting);
74     } else {
75       return changeNetworkWEP(setting);
76     }
77   }
78
79   private int doError(int resource_string) {
80     statusView.setText(resource_string);
81     return -1;
82   }
83
84   private WifiConfiguration changeNetworkCommon(NetworkSetting input){
85     statusView.setText(R.string.wifi_creating_network);
86     Log.d(TAG, "Adding new configuration: \nSSID: " + input.getSsid() + "\nType: " + input.getNetworkType());
87     WifiConfiguration config = new WifiConfiguration();
88
89     config.allowedAuthAlgorithms.clear();
90     config.allowedGroupCiphers.clear();
91     config.allowedKeyManagement.clear();
92     config.allowedPairwiseCiphers.clear();
93     config.allowedProtocols.clear();
94
95     // Android API insists that an ascii SSID must be quoted to be correctly handled.
96     config.SSID = NetworkUtil.convertToQuotedString(input.getSsid());
97     config.hiddenSSID = true;
98     return config;
99   }
100
101   private int requestNetworkChange(WifiConfiguration config){
102     statusView.setText(R.string.wifi_changing_network);
103     return updateNetwork(config, false);
104   }
105
106   // Adding a WEP network
107   private int changeNetworkWEP(NetworkSetting input) {
108     WifiConfiguration config = changeNetworkCommon(input);
109     if (NetworkUtil.isHexWepKey(input.getPassword())) {
110       config.wepKeys[0] = input.getPassword();
111     } else {
112       config.wepKeys[0] = NetworkUtil.convertToQuotedString(input.getPassword());
113     }
114     config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
115     config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
116     config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
117     config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
118     config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
119     config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
120     config.wepTxKeyIndex = 0;
121     return requestNetworkChange(config);
122   }
123
124   // Adding a WPA or WPA2 network
125   private int changeNetworkWPA(NetworkSetting input) {
126     WifiConfiguration config = changeNetworkCommon(input);
127     final String pass = input.getPassword();
128     // Hex passwords that are 64 bits long are not to be quoted.
129     if (pass.matches("[0-9A-Fa-f]{64}")){
130       Log.d(TAG, "A 64 bit hex password entered.");
131       config.preSharedKey = pass;
132     } else {
133       Log.d(TAG, "A normal password entered: I am quoting it.");
134       config.preSharedKey = NetworkUtil.convertToQuotedString(pass);
135     }
136     config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
137     // For WPA
138     config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
139     // For WPA2
140     config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
141     config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
142     config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
143     config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
144     return requestNetworkChange(config);
145   }
146
147   // Adding an open, unsecured network
148   private int changeNetworkUnEncrypted(NetworkSetting input){
149     WifiConfiguration config = changeNetworkCommon(input);
150     Log.d(TAG, "Empty password prompting a simple account setting");
151     config.wepKeys[0] = "";
152     config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
153     config.wepTxKeyIndex = 0;
154     return requestNetworkChange(config);
155   }
156
157   /**
158    * If the given ssid name exists in the settings, then change its password to the one given here, and save
159    * @param ssid
160    */
161   private WifiConfiguration findNetworkInExistingConfig(String ssid){
162     List <WifiConfiguration> existingConfigs = wifiManager.getConfiguredNetworks();
163     for (WifiConfiguration existingConfig : existingConfigs) {
164       if (existingConfig.SSID.equals(ssid)) {
165         return existingConfig;
166       }
167     }
168     return null;
169   }
170
171   @Override
172   protected void onCreate(Bundle savedInstanceState) {
173     super.onCreate(savedInstanceState);
174
175     Intent intent = getIntent();
176     if (intent == null || (!intent.getAction().equals(Intents.WifiConnect.ACTION))) {
177       finish();
178       return;
179     }
180
181     String ssid = intent.getStringExtra(Intents.WifiConnect.SSID);
182     String password = intent.getStringExtra(Intents.WifiConnect.PASSWORD);
183     String networkType = intent.getStringExtra(Intents.WifiConnect.TYPE);
184     setContentView(R.layout.network);
185     statusView = (TextView) findViewById(R.id.networkStatus);
186
187     // TODO(vikrama): Error checking here, to ensure ssid exists.
188     NetworkType networkT;
189     if (networkType.equals("WPA")) {
190       networkT = NetworkType.NETWORK_WPA;
191     } else if (networkType.equals("WEP")) {
192       networkT = NetworkType.NETWORK_WEP;
193     } else if (networkType.equals("nopass")) {
194      networkT = NetworkType.NETWORK_NOPASS;
195     } else {
196       // Got an incorrect network type.  Give an error
197       doError(R.string.wifi_type_incorrect);
198       return;
199     }
200
201     // This is not available before onCreate
202     wifiManager = (WifiManager) this.getSystemService(WIFI_SERVICE);
203
204     // So we know when the network changes
205     connectedReceiver = new ConnectedReceiver(this, statusView);
206     registerReceiver(connectedReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
207
208     if (password == null) {
209       password = "";
210     }
211     Log.d(TAG, "Adding new configuration: \nSSID: " + ssid + "Type: " + networkT);
212     NetworkSetting setting = new NetworkSetting(ssid, password, networkT);
213     changeNetwork(setting);
214   }
215
216   @Override
217   protected void onDestroy() {
218     if (connectedReceiver != null) {
219       unregisterReceiver(connectedReceiver);
220       connectedReceiver = null;
221     }
222     super.onDestroy();
223   }
224
225   /**
226    * Update the network: either create a new network or modify an existing network
227    * @param config the new network configuration
228    * @param disableOthers true if other networks must be disabled
229    * @return network ID of the connected network.
230    */
231   private int updateNetwork(WifiConfiguration config, boolean disableOthers){
232     int networkId;
233     if (findNetworkInExistingConfig(config.SSID) == null){
234       statusView.setText(R.string.wifi_creating_network);
235       networkId = wifiManager.addNetwork(config);
236     } else {
237       statusView.setText(R.string.wifi_modifying_network);
238       networkId = wifiManager.updateNetwork(config);
239     }
240     if (networkId == -1 || !wifiManager.enableNetwork(networkId, disableOthers)) {
241       return -1;
242     }
243     wifiManager.saveConfiguration();
244     return networkId;
245   }
246 }