Style-related changes
[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  * @author Vikram Aggarwal
38  */
39 public class WifiActivity extends Activity  {
40
41   private static final String TAG = WifiActivity.class.getSimpleName();
42
43   private WifiManager wifiManager;
44   private TextView statusView;
45   private ConnectedReceiver connectedReceiver;
46
47   public enum NetworkType {
48     NETWORK_WEP, NETWORK_WPA,
49   }
50
51   private int changeNetwork(NetworkSetting setting) {
52     // If the password is empty, this is an unencrypted network
53     if (setting.getPassword() == null || setting.getPassword().length() == 0) {
54       return changeNetworkUnEncrypted(setting);
55     }
56     if (setting.getNetworkType() == NetworkType.NETWORK_WPA) {
57       return changeNetworkWPA(setting); 
58     } else {
59       return changeNetworkWEP(setting);
60     }
61   }
62
63   private WifiConfiguration changeNetworkCommon(NetworkSetting input){
64     statusView.setText("Creating settings...");
65     Log.d(TAG, "Adding new configuration: \nSSID: " + input.getSsid() + "\nType: " + input.getNetworkType());
66     WifiConfiguration config = new WifiConfiguration();
67
68     config.allowedAuthAlgorithms.clear();
69     config.allowedGroupCiphers.clear();
70     config.allowedKeyManagement.clear();
71     config.allowedPairwiseCiphers.clear();
72     config.allowedProtocols.clear();
73
74     // Android API insists that an ascii SSID must be quoted to be correctly handled.
75     config.SSID = NetworkUtil.convertToQuotedString(input.getSsid());   
76     config.hiddenSSID = true;
77     return config;
78   }
79
80   private int requestNetworkChange(WifiConfiguration config){
81     statusView.setText("Changing Network...");
82     return updateNetwork(config, false);
83   }
84
85   // Adding a WEP network
86   private int changeNetworkWEP(NetworkSetting input) {
87     WifiConfiguration config = changeNetworkCommon(input);
88     if (NetworkUtil.isHexWepKey(input.getPassword())) {
89       config.wepKeys[0] = input.getPassword();
90     } else {
91       config.wepKeys[0] = NetworkUtil.convertToQuotedString(input.getPassword());
92     }
93     config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
94     config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
95     config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
96     config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
97     config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
98     config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
99     config.wepTxKeyIndex = 0;
100     return requestNetworkChange(config);
101   }
102
103   // Adding a WPA or WPA2 network
104   private int changeNetworkWPA(NetworkSetting input) {
105     WifiConfiguration config = changeNetworkCommon(input);
106     config.preSharedKey = NetworkUtil.convertToQuotedString(input.getPassword());
107     config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
108     config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
109     // For WPA
110     config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
111     // For WPA2
112     config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
113     return requestNetworkChange(config);
114   }
115
116   // Adding an open, unsecured network
117   private int changeNetworkUnEncrypted(NetworkSetting input){
118     WifiConfiguration config = changeNetworkCommon(input);
119     Log.d(TAG, "Empty password prompting a simple account setting");
120     config.wepKeys[0] = "";
121     config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
122     config.wepTxKeyIndex = 0;
123     return requestNetworkChange(config);
124   }
125
126   /**
127    * If the given ssid name exists in the settings, then change its password to the one given here, and save
128    * @param ssid
129    */
130   private WifiConfiguration findNetworkInExistingConfig(String ssid){
131     List <WifiConfiguration> existingConfigs = wifiManager.getConfiguredNetworks();
132     for (WifiConfiguration existingConfig : existingConfigs) {
133       if (existingConfig.SSID.equals(ssid)) {
134         return existingConfig;
135       }
136     }
137     return null;
138   }
139
140   @Override
141   protected void onCreate(Bundle savedInstanceState) {
142     super.onCreate(savedInstanceState);
143
144     Intent intent = getIntent();
145     if (intent == null || (!intent.getAction().equals(Intents.WifiConnect.ACTION))) {
146       finish();
147       return;
148     }
149
150     String ssid = intent.getStringExtra(Intents.WifiConnect.SSID);
151     String password = intent.getStringExtra(Intents.WifiConnect.PASSWORD);
152     String networkType = intent.getStringExtra(Intents.WifiConnect.TYPE);
153
154     // TODO(vikrama): Error checking here, to ensure ssid exists.
155     NetworkType networkT;
156     if (networkType.contains("WPA")) {
157       networkT = NetworkType.NETWORK_WPA;
158     } else if (networkType.contains("WEP")) {
159       networkT = NetworkType.NETWORK_WEP;
160     } else {
161       // Got an incorrect network type
162       finish();
163       return;
164     }
165
166     setContentView(R.layout.network);
167     statusView = (TextView) findViewById(R.id.networkStatus);
168     // This is not available before onCreate
169     wifiManager = (WifiManager) this.getSystemService(WIFI_SERVICE);
170
171     // So we know when the network changes
172     connectedReceiver = new ConnectedReceiver(this, statusView);
173     registerReceiver(connectedReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
174
175     if (password == null) {
176       password = "";
177     }
178     Log.d(TAG, "Adding new configuration: \nSSID: " + ssid + "Type: " + networkT);
179     NetworkSetting setting = new NetworkSetting(ssid, password, networkT);
180     changeNetwork(setting);
181   }
182
183   @Override
184   protected void onDestroy() {
185     if (connectedReceiver != null) {
186       unregisterReceiver(connectedReceiver);
187       connectedReceiver = null;
188     }
189     super.onDestroy();
190   }
191
192   /**
193    * Update the network: either create a new network or modify an existing network
194    * @param config the new network configuration
195    * @param disableOthers true if other networks must be disabled
196    * @return network ID of the connected network.
197    */
198   private int updateNetwork(WifiConfiguration config, boolean disableOthers){
199     int networkId;
200     if (findNetworkInExistingConfig(config.SSID) == null){
201       statusView.setText("Creating network...");
202       networkId = wifiManager.addNetwork(config);
203     } else {
204       statusView.setText("Modifying network...");
205       networkId = wifiManager.updateNetwork(config);
206     }
207     if (networkId == -1 || !wifiManager.enableNetwork(networkId, disableOthers)) {
208       return -1;
209     }
210     wifiManager.saveConfiguration();
211     return networkId;
212   }
213 }