Small style things
[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("Creating settings...");
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     config.preSharedKey = NetworkUtil.convertToQuotedString(input.getPassword());
128     config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
129     config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
130     // For WPA
131     config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
132     // For WPA2
133     config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
134     return requestNetworkChange(config);
135   }
136
137   // Adding an open, unsecured network
138   private int changeNetworkUnEncrypted(NetworkSetting input){
139     WifiConfiguration config = changeNetworkCommon(input);
140     Log.d(TAG, "Empty password prompting a simple account setting");
141     config.wepKeys[0] = "";
142     config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
143     config.wepTxKeyIndex = 0;
144     return requestNetworkChange(config);
145   }
146
147   /**
148    * If the given ssid name exists in the settings, then change its password to the one given here, and save
149    * @param ssid
150    */
151   private WifiConfiguration findNetworkInExistingConfig(String ssid){
152     List <WifiConfiguration> existingConfigs = wifiManager.getConfiguredNetworks();
153     for (WifiConfiguration existingConfig : existingConfigs) {
154       if (existingConfig.SSID.equals(ssid)) {
155         return existingConfig;
156       }
157     }
158     return null;
159   }
160
161   @Override
162   protected void onCreate(Bundle savedInstanceState) {
163     super.onCreate(savedInstanceState);
164
165     Intent intent = getIntent();
166     if (intent == null || (!intent.getAction().equals(Intents.WifiConnect.ACTION))) {
167       finish();
168       return;
169     }
170
171     String ssid = intent.getStringExtra(Intents.WifiConnect.SSID);
172     String password = intent.getStringExtra(Intents.WifiConnect.PASSWORD);
173     String networkType = intent.getStringExtra(Intents.WifiConnect.TYPE);
174     setContentView(R.layout.network);
175     statusView = (TextView) findViewById(R.id.networkStatus);
176
177     // TODO(vikrama): Error checking here, to ensure ssid exists.
178     NetworkType networkT;
179     if (networkType.equals("WPA")) {
180       networkT = NetworkType.NETWORK_WPA;
181     } else if (networkType.equals("WEP")) {
182       networkT = NetworkType.NETWORK_WEP;
183     } else if (networkType.equals("nopass")) {
184      networkT = NetworkType.NETWORK_NOPASS;
185     } else {
186       // Got an incorrect network type.  Give an error
187       doError(R.string.wifi_type_incorrect);
188       return;
189     }
190
191     // This is not available before onCreate
192     wifiManager = (WifiManager) this.getSystemService(WIFI_SERVICE);
193
194     // So we know when the network changes
195     connectedReceiver = new ConnectedReceiver(this, statusView);
196     registerReceiver(connectedReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
197
198     if (password == null) {
199       password = "";
200     }
201     Log.d(TAG, "Adding new configuration: \nSSID: " + ssid + "Type: " + networkT);
202     NetworkSetting setting = new NetworkSetting(ssid, password, networkT);
203     changeNetwork(setting);
204   }
205
206   @Override
207   protected void onDestroy() {
208     if (connectedReceiver != null) {
209       unregisterReceiver(connectedReceiver);
210       connectedReceiver = null;
211     }
212     super.onDestroy();
213   }
214
215   /**
216    * Update the network: either create a new network or modify an existing network
217    * @param config the new network configuration
218    * @param disableOthers true if other networks must be disabled
219    * @return network ID of the connected network.
220    */
221   private int updateNetwork(WifiConfiguration config, boolean disableOthers){
222     int networkId;
223     if (findNetworkInExistingConfig(config.SSID) == null){
224       statusView.setText(R.string.wifi_creating_network);
225       networkId = wifiManager.addNetwork(config);
226     } else {
227       statusView.setText(R.string.wifi_modifying_network);
228       networkId = wifiManager.updateNetwork(config);
229     }
230     if (networkId == -1 || !wifiManager.enableNetwork(networkId, disableOthers)) {
231       return -1;
232     }
233     wifiManager.saveConfiguration();
234     return networkId;
235   }
236 }