Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Add logout button

  • Loading branch information...
commit eb812cf07dc17049493655e70f18dc1eace94e99 1 parent e820ff9
@pawitp authored
View
10 res/values-th/string.xml
@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="pref_login_now">เข้าสู่ระบบเดี๋ยวนี้!</string>
+ <string name="pref_logout_now">ออกจากระบบเดี๋ยวนี้!</string>
<string name="pref_preferences">การตั้งค่า</string>
<string name="pref_username">ชื่อผู้ใช้</string>
<string name="pref_username_summary">กดเพื่อเปลี่ยนชื่อผู้ใช้</string>
@@ -26,11 +27,14 @@
<string name="wifi_disabled">สัญญาณอินเตอร์เน็ตไร้สายถูกปิดอยู่ เปิดก่อนใช้งาน</string>
<string name="no_login_required">เซิฟเวอร์ไม่ร้องขอการเข้าสู่ระบบ</string>
<string name="login_successful">การเข้าสู่ระบบสมบูรณ์</string>
+ <string name="logout_successful">การออกจากระบบสมบูรณ์</string>
<string name="ticker_login_error">ไม่สามารถเข้าสู่ระบบ MU-WiFi ได้</string>
- <string name="notify_login_ongoing_title">กำลังเข้าสู่ระบบ MU-WiFi...</string>
- <string name="notify_login_ongoing_text_determine_requirement">ตรวจสอบสถานะการเชื่อมต่อ...</string>
- <string name="notify_login_ongoing_text_logging_in">กำลังเข้าสู่ระบบ...</string>
+ <string name="notify_login_ongoing_title">กำลังเข้าสู่ระบบ MU-WiFi…</string>
+ <string name="notify_login_ongoing_text_determine_requirement">ตรวจสอบสถานะการเชื่อมต่อ…</string>
+ <string name="notify_login_ongoing_text_logging_in">กำลังเข้าสู่ระบบ…</string>
+ <string name="notify_logout_ongoing_text">กำลังออกจากระบบ…</string>
<string name="notify_login_error_title">ไม่สามารถเข้าสู่ระบบ MU-WiFi ได้</string>
+ <string name="notify_logout_error_title">ไม่สามารถออกจากระบบ MU-WiFi ได้</string>
<string name="notify_login_error_text">กดเพื่อลองอีกครั้ง</string>
<string name="notify_login_error_invalid_credentials_text">ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง</string>
</resources>
View
8 res/values/strings.xml
@@ -2,6 +2,7 @@
<resources>
<string name="app_name">MU-WiFi Autologin</string>
<string name="pref_login_now">Login Now!</string>
+ <string name="pref_logout_now">Logout Now!</string>
<string name="pref_preferences">Preferences</string>
<string name="pref_username">Username</string>
<string name="pref_username_summary">Click to set username</string>
@@ -29,11 +30,14 @@
<string name="wifi_disabled">WiFi needs to be enabled to use autologin.</string>
<string name="no_login_required">No login required.</string>
<string name="login_successful">Automatic login to MU-WiFi successful.</string>
+ <string name="logout_successful">Logout successful.</string>
<string name="ticker_login_error">Unable to login to MU-WiFi.</string>
<string name="notify_login_ongoing_title">MU-WiFi Autologin</string>
- <string name="notify_login_ongoing_text_determine_requirement">Determining if login is required...</string>
- <string name="notify_login_ongoing_text_logging_in">Logging in...</string>
+ <string name="notify_login_ongoing_text_determine_requirement">Determining if login is required…</string>
+ <string name="notify_login_ongoing_text_logging_in">Logging in…</string>
+ <string name="notify_logout_ongoing_text">Logging out…</string>
<string name="notify_login_error_title">Unable to login to MU-WiFi</string>
+ <string name="notify_logout_error_title">Unable to logout from MU-WiFi</string>
<string name="notify_login_error_text">Click to retry.</string>
<string name="notify_login_error_invalid_credentials_text">Invalid username or password.</string>
</resources>
View
1  res/xml/preferences.xml
@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<Preference android:title="@string/pref_login_now" android:key="login_now"></Preference>
+ <Preference android:title="@string/pref_logout_now" android:key="logout_now"></Preference>
<PreferenceCategory android:title="@string/pref_preferences">
<CheckBoxPreference
android:defaultValue="false"
View
8 src/org/dyndns/pawitp/muwifiautologin/LoginException.java
@@ -2,9 +2,9 @@
public class LoginException extends Exception {
- private static final long serialVersionUID = 1L;
+ private static final long serialVersionUID = 1L;
- public LoginException(String strRes) {
- super(strRes);
- }
+ public LoginException(String strRes) {
+ super(strRes);
+ }
}
View
203 src/org/dyndns/pawitp/muwifiautologin/MuWifiClient.java
@@ -1,16 +1,8 @@
package org.dyndns.pawitp.muwifiautologin;
-import java.io.IOException;
-import java.net.ConnectException;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLHandshakeException;
-
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
+import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
@@ -22,84 +14,121 @@
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
+import java.io.IOException;
+import java.net.ConnectException;
+import java.net.URISyntaxException;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.net.ssl.SSLException;
+import javax.net.ssl.SSLHandshakeException;
+
public class MuWifiClient {
- // These are not regex
- static final String LOGIN_SUCCESSFUL_PATTERN = "External Welcome Page";
-
- static final String FORM_USERNAME = "user";
- static final String FORM_PASSWORD = "password";
- static final String FORM_URL = "https://securelogin.arubanetworks.com/auth/index.html/u";
- static final int CONNECTION_TIMEOUT = 2000;
- static final int SOCKET_TIMEOUT = 2000;
- static final int RETRY_COUNT = 2;
-
- private String mUsername;
- private String mPassword;
- private DefaultHttpClient mHttpClient;
-
- public MuWifiClient(String username, String password) {
- mUsername = username;
- mPassword = password;
-
- mHttpClient = new DefaultHttpClient();
- HttpParams params = mHttpClient.getParams();
- HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
- HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT);
-
- // Also retry POST requests (normally not retried because it is not regarded idempotent)
- mHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
- @Override
- public boolean retryRequest(IOException exception, int executionCount,
- HttpContext context) {
- if (executionCount >= RETRY_COUNT) {
- // Do not retry if over max retry count
- return false;
- }
- if (exception instanceof UnknownHostException) {
- // Unknown host
- return false;
- }
- if (exception instanceof ConnectException) {
- // Connection refused
- return false;
- }
- if (exception instanceof SSLHandshakeException) {
- // SSL handshake exception
- return false;
- }
-
- return true;
- }
- });
- }
-
- public boolean loginRequired() throws IOException {
- try {
- HttpGet httpget = new HttpGet("https://www.google.com/");
- mHttpClient.execute(httpget);
- }
- catch (SSLException e) {
- return true; // If login is required, the certificate sent will be securelogin.arubanetworks.com
- }
- return false;
- }
-
- public void login() throws IOException, LoginException {
- List<NameValuePair> formparams = new ArrayList<NameValuePair>();
- formparams.add(new BasicNameValuePair(FORM_USERNAME, mUsername));
- formparams.add(new BasicNameValuePair(FORM_PASSWORD, mPassword));
- UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
- HttpPost httppost = new HttpPost(FORM_URL);
- httppost.setEntity(entity);
- HttpResponse response = mHttpClient.execute(httppost);
- String strRes = EntityUtils.toString(response.getEntity());
-
- if (strRes.contains(LOGIN_SUCCESSFUL_PATTERN)) {
- // login successful
- } else {
- throw new LoginException(strRes);
- }
- }
-
+ // These are not regex
+ static final String LOGIN_SUCCESSFUL_PATTERN = "External Welcome Page";
+ static final String LOGOUT_SUCCESSFUL_PATTERN = "Logout Successful";
+
+ static final String FORM_USERNAME = "user";
+ static final String FORM_PASSWORD = "password";
+ static final String FORM_URL = "https://securelogin.arubanetworks.com/auth/index.html/u";
+ static final String LOGOUT_URL = "https://securelogin.arubanetworks.com/auth/logout.html";
+ static final int CONNECTION_TIMEOUT = 2000;
+ static final int SOCKET_TIMEOUT = 2000;
+ static final int RETRY_COUNT = 2;
+
+ private String mUsername;
+ private String mPassword;
+ private DefaultHttpClient mHttpClient;
+
+ public MuWifiClient(String username, String password) {
+ mUsername = username;
+ mPassword = password;
+
+ mHttpClient = new DefaultHttpClient();
+ HttpParams params = mHttpClient.getParams();
+ HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
+ HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT);
+
+ // Also retry POST requests (normally not retried because it is not regarded idempotent)
+ mHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
+ @Override
+ public boolean retryRequest(IOException exception, int executionCount,
+ HttpContext context) {
+ if (executionCount >= RETRY_COUNT) {
+ // Do not retry if over max retry count
+ return false;
+ }
+ if (exception instanceof UnknownHostException) {
+ // Unknown host
+ return false;
+ }
+ if (exception instanceof ConnectException) {
+ // Connection refused
+ return false;
+ }
+ if (exception instanceof SSLHandshakeException) {
+ // SSL handshake exception
+ return false;
+ }
+
+ return true;
+ }
+ });
+ }
+
+ public boolean loginRequired() throws IOException {
+ try {
+ HttpGet httpget = new HttpGet("https://www.google.com/");
+ mHttpClient.execute(httpget);
+ }
+ catch (SSLException e) {
+ return true; // If login is required, the certificate sent will be securelogin.arubanetworks.com
+ }
+ return false;
+ }
+
+ public void login() throws IOException, LoginException {
+ try {
+ List<NameValuePair> formparams = new ArrayList<NameValuePair>();
+ formparams.add(new BasicNameValuePair(FORM_USERNAME, mUsername));
+ formparams.add(new BasicNameValuePair(FORM_PASSWORD, mPassword));
+ UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
+ HttpPost httppost = new HttpPost(FORM_URL);
+ httppost.setEntity(entity);
+ HttpResponse response = mHttpClient.execute(httppost);
+ String strRes = EntityUtils.toString(response.getEntity());
+
+ if (strRes.contains(LOGIN_SUCCESSFUL_PATTERN)) {
+ // login successful
+ } else {
+ throw new LoginException("Unexpected reply from server.");
+ }
+ } catch (ClientProtocolException e) {
+ // If there is an error, the server will send an illegal reply (containing space)
+ if (e.getCause() == null || e.getCause().getCause() == null ||
+ !(e.getCause().getCause() instanceof URISyntaxException)) {
+ throw new LoginException("Unknown error.");
+ }
+ URISyntaxException orig = (URISyntaxException) e.getCause().getCause();
+ String url = orig.getInput();
+ String message = url.substring(url.indexOf("errmsg=") + "errmsg=".length());
+ throw new LoginException(message);
+ }
+ }
+
+ public void logout() throws IOException, LoginException {
+ HttpGet httpget = new HttpGet(LOGOUT_URL);
+ HttpResponse response = mHttpClient.execute(httpget);
+ String strRes = EntityUtils.toString(response.getEntity());
+
+ if (strRes.contains(LOGOUT_SUCCESSFUL_PATTERN)) {
+ // logout successful
+ } else {
+ // TODO
+ throw new LoginException("Unexpected reply from server.");
+ }
+ }
+
}
View
276 src/org/dyndns/pawitp/muwifiautologin/MuWifiLogin.java
@@ -18,134 +18,150 @@
public class MuWifiLogin extends IntentService {
- static final String TAG = "MuWifiLogin";
- static final int LOGIN_ERROR_ID = 1;
- static final int LOGIN_ONGOING_ID = 2;
-
- private Handler mHandler;
- private SharedPreferences mPrefs;
- private NotificationManager mNotifMan;
- private Notification mNotification;
-
- public MuWifiLogin() {
- super(TAG);
- }
-
- @Override
- public void onCreate() {
- super.onCreate();
- Utils.loadLocale(this);
-
- mHandler = new Handler();
- mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
- mNotifMan = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
-
- mNotification = new Notification(R.drawable.ic_stat_notify_key, null, System.currentTimeMillis());
- updateOngoingNotification(null, false); // Foreground service requires a valid notification
- startForeground(LOGIN_ONGOING_ID, mNotification); // Stopped automatically when onHandleIntent returns
- }
-
- @Override
- protected void onHandleIntent(Intent intent) {
- mNotifMan.cancel(LOGIN_ERROR_ID); // clear any old notification
-
- MuWifiClient loginClient = new MuWifiClient(mPrefs.getString(Preferences.KEY_USERNAME, null), mPrefs.getString(Preferences.KEY_PASSWORD, null));
-
- try {
- updateOngoingNotification(getString(R.string.notify_login_ongoing_text_determine_requirement), true);
- if (loginClient.loginRequired()) {
- try {
- Log.v(TAG, "Login required");
-
- updateOngoingNotification(getString(R.string.notify_login_ongoing_text_logging_in), true);
- loginClient.login();
-
- if (mPrefs.getBoolean(Preferences.KEY_TOAST_NOTIFY_SUCCESS, true)) {
- createToastNotification(R.string.login_successful, Toast.LENGTH_SHORT);
- }
-
- Log.v(TAG, "Login successful");
- } catch (SocketTimeoutException e) {
- // A socket timeout here means invalid crendentials!
- Log.v(TAG, "Invalid credentials");
-
- Intent notificationIntent = new Intent(this, Preferences.class);
- notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
- PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
- createErrorNotification(contentIntent, getString(R.string.notify_login_error_invalid_credentials_text));
- }
- } else {
- if (mPrefs.getBoolean(Preferences.KEY_TOAST_NOTIFY_NOT_REQUIRED, true)) {
- createToastNotification(R.string.no_login_required, Toast.LENGTH_SHORT);
- }
-
- Log.v(TAG, "No login required");
- }
- } catch (LoginException e) {
- Log.v(TAG, "Login failed: LoginException");
- Log.v(TAG, Utils.stackTraceToString(e));
-
- createRetryNotification();
- } catch (IOException e) {
- Log.v(TAG, "Login failed: IOException");
- Log.v(TAG, Utils.stackTraceToString(e));
-
- createRetryNotification();
- } catch (NullPointerException e) {
- // a bug in HttpClient library
- // thrown when there is a connection failure when handling a redirect
- Log.v(TAG, "Login failed: NullPointerException");
- Log.v(TAG, Utils.stackTraceToString(e));
-
- createRetryNotification();
- }
- }
-
- private void updateOngoingNotification(String message, boolean notify) {
- PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent() , 0);
- mNotification.setLatestEventInfo(this, getString(R.string.notify_login_ongoing_title), message, contentIntent);
-
- if (notify) {
- mNotifMan.notify(LOGIN_ONGOING_ID, mNotification);
- }
- }
-
- private void createRetryNotification() {
- Intent notificationIntent = new Intent(this, MuWifiLogin.class);
- PendingIntent contentIntent = PendingIntent.getService(this, 0, notificationIntent, 0);
- createErrorNotification(contentIntent, getString(R.string.notify_login_error_text));
- }
-
- private void createErrorNotification(PendingIntent contentIntent, String errorText) {
- WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
- if (!wifi.isWifiEnabled()) {
- // Don't show errors if wifi is disabled
- return;
- }
-
- Notification notification = new Notification(R.drawable.ic_stat_notify_key, getString(R.string.ticker_login_error), System.currentTimeMillis());
- notification.setLatestEventInfo(this, getString(R.string.notify_login_error_title), errorText, contentIntent);
- notification.flags = Notification.FLAG_AUTO_CANCEL;
-
- if (mPrefs.getBoolean(Preferences.KEY_ERROR_NOTIFY_SOUND, false)) {
- notification.defaults |= Notification.DEFAULT_SOUND;
- }
- if (mPrefs.getBoolean(Preferences.KEY_ERROR_NOTIFY_VIBRATE, false)) {
- notification.defaults |= Notification.DEFAULT_VIBRATE;
- }
- if (mPrefs.getBoolean(Preferences.KEY_ERROR_NOTIFY_LIGHTS, false)) {
- notification.defaults |= Notification.DEFAULT_LIGHTS;
- }
-
- mNotifMan.notify(LOGIN_ERROR_ID, notification);
- }
-
- private void createToastNotification(final int message, final int length) {
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- Toast.makeText(MuWifiLogin.this, message, length).show();
- }
- });
- }
+ static final String TAG = "MuWifiLogin";
+ static final int LOGIN_ERROR_ID = 1;
+ static final int LOGIN_ONGOING_ID = 2;
+ static final String EXTRA_LOGOUT = "logout";
+
+ private Handler mHandler;
+ private SharedPreferences mPrefs;
+ private NotificationManager mNotifMan;
+ private Notification mNotification;
+
+ public MuWifiLogin() {
+ super(TAG);
+ }
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ Utils.loadLocale(this);
+
+ mHandler = new Handler();
+ mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
+ mNotifMan = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
+
+ mNotification = new Notification(R.drawable.ic_stat_notify_key, null, System.currentTimeMillis());
+ updateOngoingNotification(null, false); // Foreground service requires a valid notification
+ startForeground(LOGIN_ONGOING_ID, mNotification); // Stopped automatically when onHandleIntent returns
+ }
+
+ @Override
+ protected void onHandleIntent(Intent intent) {
+ mNotifMan.cancel(LOGIN_ERROR_ID); // clear any old notification
+
+ boolean isLogout = intent.getBooleanExtra(EXTRA_LOGOUT, false);
+
+ MuWifiClient loginClient = new MuWifiClient(mPrefs.getString(Preferences.KEY_USERNAME, null), mPrefs.getString(Preferences.KEY_PASSWORD, null));
+
+ try {
+ if (isLogout) {
+ Log.v(TAG, "Logging out");
+ updateOngoingNotification(getString(R.string.notify_logout_ongoing_text), true);
+ loginClient.logout();
+ createToastNotification(R.string.logout_successful, Toast.LENGTH_SHORT);
+ Log.v(TAG, "Logout successful");
+ } else {
+ updateOngoingNotification(getString(R.string.notify_login_ongoing_text_determine_requirement), true);
+ if (loginClient.loginRequired()) {
+ try {
+ Log.v(TAG, "Login required");
+
+ updateOngoingNotification(getString(R.string.notify_login_ongoing_text_logging_in), true);
+ loginClient.login();
+
+ if (mPrefs.getBoolean(Preferences.KEY_TOAST_NOTIFY_SUCCESS, true)) {
+ createToastNotification(R.string.login_successful, Toast.LENGTH_SHORT);
+ }
+
+ Log.v(TAG, "Login successful");
+ } catch (SocketTimeoutException e) {
+ // A socket timeout here means invalid credentials!
+ Log.v(TAG, "Invalid credentials");
+
+ Intent notificationIntent = new Intent(this, Preferences.class);
+ notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
+ PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
+ createErrorNotification(contentIntent, getString(R.string.notify_login_error_invalid_credentials_text), isLogout);
+ }
+ } else {
+ if (mPrefs.getBoolean(Preferences.KEY_TOAST_NOTIFY_NOT_REQUIRED, true)) {
+ createToastNotification(R.string.no_login_required, Toast.LENGTH_SHORT);
+ }
+
+ Log.v(TAG, "No login required");
+ }
+ }
+ } catch (LoginException e) {
+ Log.v(TAG, "Login failed: LoginException");
+ Log.v(TAG, Utils.stackTraceToString(e));
+
+ createRetryNotification(isLogout, e.getMessage());
+ } catch (IOException e) {
+ Log.v(TAG, "Login failed: IOException");
+ Log.v(TAG, Utils.stackTraceToString(e));
+
+ createRetryNotification(isLogout);
+ } catch (NullPointerException e) {
+ // a bug in HttpClient library
+ // thrown when there is a connection failure when handling a redirect
+ Log.v(TAG, "Login failed: NullPointerException");
+ Log.v(TAG, Utils.stackTraceToString(e));
+
+ createRetryNotification(isLogout);
+ }
+ }
+
+ private void updateOngoingNotification(String message, boolean notify) {
+ PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent() , 0);
+ mNotification.setLatestEventInfo(this, getString(R.string.notify_login_ongoing_title), message, contentIntent);
+
+ if (notify) {
+ mNotifMan.notify(LOGIN_ONGOING_ID, mNotification);
+ }
+ }
+
+ private void createRetryNotification(boolean isLogout, String text) {
+ Intent notificationIntent = new Intent(this, MuWifiLogin.class);
+ PendingIntent contentIntent = PendingIntent.getService(this, 0, notificationIntent, 0);
+ createErrorNotification(contentIntent, text, isLogout);
+ }
+
+ private void createRetryNotification(boolean isLogout) {
+ createRetryNotification(isLogout, getString(R.string.notify_login_error_text));
+ }
+
+ private void createErrorNotification(PendingIntent contentIntent, String errorText, boolean isLogout) {
+ WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
+ if (!wifi.isWifiEnabled()) {
+ // Don't show errors if wifi is disabled
+ return;
+ }
+
+ Notification notification = new Notification(R.drawable.ic_stat_notify_key, getString(R.string.ticker_login_error), System.currentTimeMillis());
+ int message = isLogout ? R.string.notify_logout_error_title : R.string.notify_login_error_title;
+ notification.setLatestEventInfo(this, getString(message), errorText, contentIntent);
+ notification.flags = Notification.FLAG_AUTO_CANCEL;
+
+ if (mPrefs.getBoolean(Preferences.KEY_ERROR_NOTIFY_SOUND, false)) {
+ notification.defaults |= Notification.DEFAULT_SOUND;
+ }
+ if (mPrefs.getBoolean(Preferences.KEY_ERROR_NOTIFY_VIBRATE, false)) {
+ notification.defaults |= Notification.DEFAULT_VIBRATE;
+ }
+ if (mPrefs.getBoolean(Preferences.KEY_ERROR_NOTIFY_LIGHTS, false)) {
+ notification.defaults |= Notification.DEFAULT_LIGHTS;
+ }
+
+ mNotifMan.notify(LOGIN_ERROR_ID, notification);
+ }
+
+ private void createToastNotification(final int message, final int length) {
+ mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ Toast.makeText(MuWifiLogin.this, message, length).show();
+ }
+ });
+ }
}
View
74 src/org/dyndns/pawitp/muwifiautologin/NetworkStateChanged.java
@@ -11,42 +11,42 @@
public class NetworkStateChanged extends BroadcastReceiver {
- static final String TAG = "NetworkStateChanged";
- static final String SSID = "MU-WiFi";
-
- @Override
- public void onReceive(Context context, Intent intent) {
- // Check preference
- SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
- if (!prefs.getBoolean(Preferences.KEY_ENABLED, false)) {
- // Disable the BroadcastReceiver so it isn't called in the future
- Utils.setEnableBroadcastReceiver(context, false);
- return;
- }
-
- // Check network connected
- NetworkInfo netInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
- if (!netInfo.isConnected()) {
- return;
- }
-
- // Check SSID
- WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
- try {
- if (!wifi.getConnectionInfo().getSSID().equalsIgnoreCase(SSID)) {
- return;
- }
- }
- catch (NullPointerException e) {
- // So many things can be null here when network is not connected
- return;
- }
-
-
- Log.v(TAG, "Connected to the correct network");
-
- Intent i = new Intent(context, MuWifiLogin.class);
- context.startService(i);
- }
+ static final String TAG = "NetworkStateChanged";
+ static final String SSID = "MU-WiFi";
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ // Check preference
+ SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
+ if (!prefs.getBoolean(Preferences.KEY_ENABLED, false)) {
+ // Disable the BroadcastReceiver so it isn't called in the future
+ Utils.setEnableBroadcastReceiver(context, false);
+ return;
+ }
+
+ // Check network connected
+ NetworkInfo netInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
+ if (!netInfo.isConnected()) {
+ return;
+ }
+
+ // Check SSID
+ WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
+ try {
+ if (!wifi.getConnectionInfo().getSSID().equalsIgnoreCase(SSID)) {
+ return;
+ }
+ }
+ catch (NullPointerException e) {
+ // So many things can be null here when network is not connected
+ return;
+ }
+
+
+ Log.v(TAG, "Connected to the correct network");
+
+ Intent i = new Intent(context, MuWifiLogin.class);
+ context.startService(i);
+ }
}
View
414 src/org/dyndns/pawitp/muwifiautologin/Preferences.java
@@ -18,218 +18,236 @@
import android.widget.Toast;
public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {
- static final String KEY_LOGIN_NOW = "login_now";
- static final String KEY_ENABLED = "enabled";
- static final String KEY_USERNAME = "username";
- static final String KEY_PASSWORD = "password";
- static final String KEY_ERROR_NOTIFY = "error_notify";
- static final String KEY_ERROR_NOTIFY_SOUND = "error_notify_sound";
- static final String KEY_ERROR_NOTIFY_VIBRATE = "error_notify_vibrate";
- static final String KEY_ERROR_NOTIFY_LIGHTS = "error_notify_lights";
- static final String KEY_TOAST_NOTIFY = "toast_notify";
- static final String KEY_TOAST_NOTIFY_SUCCESS = "toast_notify_success";
- static final String KEY_TOAST_NOTIFY_NOT_REQUIRED = "toast_notify_not_required";
- static final String KEY_LANGUAGE = "language";
- static final String KEY_VERSION = "version";
- static final String KEY_WEBSITE = "website";
- static final String KEY_AUTHOR = "author";
-
- static final String LANGUAGE_DEFAULT = "default";
- static final String MARKET_PREFIX = "market://details?id=";
- static final String EMAIL_TYPE = "message/rfc822";
- static final String EMAIL_AUTHOR = "p.pawit@gmail.com";
- static final String EMAIL_SUBJECT = "[MU-WiFi Autologin] ";
- static final String WEBSITE_URL = "http://pawitp.dats.us/muwifi-autologin/";
-
+ static final String KEY_LOGIN_NOW = "login_now";
+ static final String KEY_LOGOUT_NOW = "logout_now";
+ static final String KEY_ENABLED = "enabled";
+ static final String KEY_USERNAME = "username";
+ static final String KEY_PASSWORD = "password";
+ static final String KEY_ERROR_NOTIFY = "error_notify";
+ static final String KEY_ERROR_NOTIFY_SOUND = "error_notify_sound";
+ static final String KEY_ERROR_NOTIFY_VIBRATE = "error_notify_vibrate";
+ static final String KEY_ERROR_NOTIFY_LIGHTS = "error_notify_lights";
+ static final String KEY_TOAST_NOTIFY = "toast_notify";
+ static final String KEY_TOAST_NOTIFY_SUCCESS = "toast_notify_success";
+ static final String KEY_TOAST_NOTIFY_NOT_REQUIRED = "toast_notify_not_required";
+ static final String KEY_LANGUAGE = "language";
+ static final String KEY_VERSION = "version";
+ static final String KEY_WEBSITE = "website";
+ static final String KEY_AUTHOR = "author";
+
+ static final String LANGUAGE_DEFAULT = "default";
+ static final String MARKET_PREFIX = "market://details?id=";
+ static final String EMAIL_TYPE = "message/rfc822";
+ static final String EMAIL_AUTHOR = "p.pawit@gmail.com";
+ static final String EMAIL_SUBJECT = "[MU-WiFi Autologin] ";
+ static final String WEBSITE_URL = "http://pawitp.dats.us/muwifi-autologin/";
+
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.loadLocale(this);
addPreferencesFromResource(R.xml.preferences);
-
+
updateUsernameSummary();
updateErrorNotificationSummary();
updateToastNotificationSummary();
updateLanguageSummary();
-
+
// Set version number
- String versionSummary = String.format(getString(R.string.pref_version_summary), Utils.getVersionName(this));
- findPreference(KEY_VERSION).setSummary(versionSummary);
-
- // Login now callback
- findPreference(KEY_LOGIN_NOW).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
- @Override
- public boolean onPreferenceClick(Preference preference) {
- WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
- if (wifi.isWifiEnabled()) {
- Intent i = new Intent(Preferences.this, MuWifiLogin.class);
- startService(i);
- }
- else {
- Toast.makeText(Preferences.this, R.string.wifi_disabled, Toast.LENGTH_SHORT).show();
- }
- return true;
- }
- });
-
- // Version (visit android market) callback
- findPreference(KEY_VERSION).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
- @Override
- public boolean onPreferenceClick(Preference preference) {
- Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(MARKET_PREFIX + getPackageName()));
- startActivity(i);
- return true;
- }
- });
-
- // Visit website callback
- findPreference(KEY_WEBSITE).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
- @Override
- public boolean onPreferenceClick(Preference preference) {
- Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(WEBSITE_URL));
- startActivity(i);
- return true;
- }
- });
-
- // Contact author callback
- findPreference(KEY_AUTHOR).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
- @Override
- public boolean onPreferenceClick(Preference preference) {
- Intent i = new Intent(Intent.ACTION_SEND);
- i.setType(EMAIL_TYPE);
- i.putExtra(Intent.EXTRA_EMAIL, new String[] {EMAIL_AUTHOR});
- i.putExtra(Intent.EXTRA_SUBJECT, EMAIL_SUBJECT);
-
- startActivity(Intent.createChooser(i, ""));
- return true;
- }
- });
+ String versionSummary = String.format(getString(R.string.pref_version_summary), Utils.getVersionName(this));
+ findPreference(KEY_VERSION).setSummary(versionSummary);
+
+ // Login now callback
+ findPreference(KEY_LOGIN_NOW).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
+ @Override
+ public boolean onPreferenceClick(Preference preference) {
+ WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
+ if (wifi.isWifiEnabled()) {
+ Intent i = new Intent(Preferences.this, MuWifiLogin.class);
+ startService(i);
+ }
+ else {
+ Toast.makeText(Preferences.this, R.string.wifi_disabled, Toast.LENGTH_SHORT).show();
+ }
+ return true;
+ }
+ });
+
+ // Logout now callback
+ findPreference(KEY_LOGOUT_NOW).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
+ @Override
+ public boolean onPreferenceClick(Preference preference) {
+ WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
+ if (wifi.isWifiEnabled()) {
+ Intent i = new Intent(Preferences.this, MuWifiLogin.class);
+ i.putExtra(MuWifiLogin.EXTRA_LOGOUT, true);
+ startService(i);
+ }
+ else {
+ Toast.makeText(Preferences.this, R.string.wifi_disabled, Toast.LENGTH_SHORT).show();
+ }
+ return true;
+ }
+ });
+
+ // Version (visit android market) callback
+ findPreference(KEY_VERSION).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
+ @Override
+ public boolean onPreferenceClick(Preference preference) {
+ Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(MARKET_PREFIX + getPackageName()));
+ startActivity(i);
+ return true;
+ }
+ });
+
+ // Visit website callback
+ findPreference(KEY_WEBSITE).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
+ @Override
+ public boolean onPreferenceClick(Preference preference) {
+ Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(WEBSITE_URL));
+ startActivity(i);
+ return true;
+ }
+ });
+
+ // Contact author callback
+ findPreference(KEY_AUTHOR).setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
+ @Override
+ public boolean onPreferenceClick(Preference preference) {
+ Intent i = new Intent(Intent.ACTION_SEND);
+ i.setType(EMAIL_TYPE);
+ i.putExtra(Intent.EXTRA_EMAIL, new String[] {EMAIL_AUTHOR});
+ i.putExtra(Intent.EXTRA_SUBJECT, EMAIL_SUBJECT);
+
+ startActivity(Intent.createChooser(i, ""));
+ return true;
+ }
+ });
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+
+ // Callback to update dynamic summaries when they get changed
+ getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
+ }
+
+ @Override
+ protected void onPause() {
+ super.onPause();
+ getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
+ }
+
+ @Override
+ public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
+ String key) {
+ if (key.equals(KEY_ENABLED)) {
+ updateEnabled();
+ }
+ else if (key.equals(KEY_USERNAME)) {
+ updateUsernameSummary();
+ }
+ else if (key.equals(KEY_ERROR_NOTIFY_SOUND)
+ || key.equals(KEY_ERROR_NOTIFY_VIBRATE)
+ || key.equals(KEY_ERROR_NOTIFY_LIGHTS)) {
+ updateErrorNotificationSummary();
+ ((BaseAdapter) getPreferenceScreen().getRootAdapter()).notifyDataSetChanged(); // force update parent screen
+ }
+ else if (key.equals(KEY_TOAST_NOTIFY_SUCCESS)
+ || key.equals(KEY_TOAST_NOTIFY_NOT_REQUIRED)) {
+ updateToastNotificationSummary();
+ ((BaseAdapter) getPreferenceScreen().getRootAdapter()).notifyDataSetChanged(); // force update parent screen
+ }
+ else if (key.equals(KEY_LANGUAGE)) {
+ updateLanguageSummary();
+
+ // WARNING: restarting the activity, don't do anything after this
+ Intent intent = getIntent();
+ intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
+ finish();
+ overridePendingTransition(0, 0);
+ startActivity(intent);
+ overridePendingTransition(0, 0);
+ }
+ }
+
+ // Enable / disable the BroadcastReceiver
+ private void updateEnabled() {
+ boolean enabled = getPreferenceManager().getSharedPreferences().getBoolean(KEY_ENABLED, false);
+ Utils.setEnableBroadcastReceiver(this, enabled);
}
- @Override
- protected void onResume() {
- super.onResume();
-
- // Callback to update dynamic summaries when they get changed
- getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
- }
-
- @Override
- protected void onPause() {
- super.onPause();
- getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
- }
-
- @Override
- public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
- String key) {
- if (key.equals(KEY_ENABLED)) {
- updateEnabled();
- }
- else if (key.equals(KEY_USERNAME)) {
- updateUsernameSummary();
- }
- else if (key.equals(KEY_ERROR_NOTIFY_SOUND)
- || key.equals(KEY_ERROR_NOTIFY_VIBRATE)
- || key.equals(KEY_ERROR_NOTIFY_LIGHTS)) {
- updateErrorNotificationSummary();
- ((BaseAdapter) getPreferenceScreen().getRootAdapter()).notifyDataSetChanged(); // force update parent screen
- }
- else if (key.equals(KEY_TOAST_NOTIFY_SUCCESS)
- || key.equals(KEY_TOAST_NOTIFY_NOT_REQUIRED)) {
- updateToastNotificationSummary();
- ((BaseAdapter) getPreferenceScreen().getRootAdapter()).notifyDataSetChanged(); // force update parent screen
- }
- else if (key.equals(KEY_LANGUAGE)) {
- updateLanguageSummary();
-
- // WARNING: restarting the activity, don't do anything after this
- Intent intent = getIntent();
- intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
- finish();
- overridePendingTransition(0, 0);
- startActivity(intent);
- overridePendingTransition(0, 0);
- }
- }
-
- // Enable / disable the BroadcastReceiver
- private void updateEnabled() {
- boolean enabled = getPreferenceManager().getSharedPreferences().getBoolean(KEY_ENABLED, false);
- Utils.setEnableBroadcastReceiver(this, enabled);
- }
-
- private void updateUsernameSummary() {
- // Set username as summary if set
+ private void updateUsernameSummary() {
+ // Set username as summary if set
String username = getPreferenceManager().getSharedPreferences().getString(KEY_USERNAME, "");
if (username.length() != 0) {
- findPreference(KEY_USERNAME).setSummary(username);
+ findPreference(KEY_USERNAME).setSummary(username);
} else {
- findPreference(KEY_USERNAME).setSummary(R.string.pref_username_summary);
- }
- }
-
- private void updateErrorNotificationSummary() {
- ArrayList<String> methods = new ArrayList<String>();
-
- SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
-
- if (prefs.getBoolean(Preferences.KEY_ERROR_NOTIFY_SOUND, false)) {
- methods.add(getString(R.string.pref_error_notify_sound));
- }
- if (prefs.getBoolean(Preferences.KEY_ERROR_NOTIFY_VIBRATE, false)) {
- methods.add(getString(R.string.pref_error_notify_vibrate));
- }
- if (prefs.getBoolean(Preferences.KEY_ERROR_NOTIFY_LIGHTS, false)) {
- methods.add(getString(R.string.pref_error_notify_lights));
- }
-
- if (methods.size() == 0) {
- findPreference(KEY_ERROR_NOTIFY).setSummary(R.string.pref_error_notify_none);
- }
- else {
- String summaryStr = join(methods, getString(R.string.pref_error_notify_deliminator));
- findPreference(KEY_ERROR_NOTIFY).setSummary(summaryStr);
- }
- }
-
- private void updateToastNotificationSummary() {
- ArrayList<String> methods = new ArrayList<String>();
-
- SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
-
- if (prefs.getBoolean(KEY_TOAST_NOTIFY_SUCCESS, true)) {
- methods.add(getString(R.string.pref_toast_notify_success));
- }
- if (prefs.getBoolean(KEY_TOAST_NOTIFY_NOT_REQUIRED, true)) {
- methods.add(getString(R.string.pref_toast_notify_not_required));
- }
-
- if (methods.size() == 0) {
- findPreference(KEY_TOAST_NOTIFY).setSummary(R.string.pref_error_notify_none);
- }
- else {
- String summaryStr = join(methods, getString(R.string.pref_error_notify_deliminator));
- findPreference(KEY_TOAST_NOTIFY).setSummary(summaryStr);
- }
- }
-
- private void updateLanguageSummary() {
- ListPreference listPref = (ListPreference) findPreference(KEY_LANGUAGE);
- listPref.setSummary(listPref.getEntry());
- }
-
- private static String join(Collection<String> col, String deliminator) {
- StringBuilder sb = new StringBuilder();
- Iterator<String> iter = col.iterator();
-
- sb.append(iter.next());
- while (iter.hasNext()) {
- sb.append(deliminator);
- sb.append(iter.next());
- }
- return sb.toString();
- }
+ findPreference(KEY_USERNAME).setSummary(R.string.pref_username_summary);
+ }
+ }
+
+ private void updateErrorNotificationSummary() {
+ ArrayList<String> methods = new ArrayList<String>();
+
+ SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
+
+ if (prefs.getBoolean(Preferences.KEY_ERROR_NOTIFY_SOUND, false)) {
+ methods.add(getString(R.string.pref_error_notify_sound));
+ }
+ if (prefs.getBoolean(Preferences.KEY_ERROR_NOTIFY_VIBRATE, false)) {
+ methods.add(getString(R.string.pref_error_notify_vibrate));
+ }
+ if (prefs.getBoolean(Preferences.KEY_ERROR_NOTIFY_LIGHTS, false)) {
+ methods.add(getString(R.string.pref_error_notify_lights));
+ }
+
+ if (methods.size() == 0) {
+ findPreference(KEY_ERROR_NOTIFY).setSummary(R.string.pref_error_notify_none);
+ }
+ else {
+ String summaryStr = join(methods, getString(R.string.pref_error_notify_deliminator));
+ findPreference(KEY_ERROR_NOTIFY).setSummary(summaryStr);
+ }
+ }
+
+ private void updateToastNotificationSummary() {
+ ArrayList<String> methods = new ArrayList<String>();
+
+ SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
+
+ if (prefs.getBoolean(KEY_TOAST_NOTIFY_SUCCESS, true)) {
+ methods.add(getString(R.string.pref_toast_notify_success));
+ }
+ if (prefs.getBoolean(KEY_TOAST_NOTIFY_NOT_REQUIRED, true)) {
+ methods.add(getString(R.string.pref_toast_notify_not_required));
+ }
+
+ if (methods.size() == 0) {
+ findPreference(KEY_TOAST_NOTIFY).setSummary(R.string.pref_error_notify_none);
+ }
+ else {
+ String summaryStr = join(methods, getString(R.string.pref_error_notify_deliminator));
+ findPreference(KEY_TOAST_NOTIFY).setSummary(summaryStr);
+ }
+ }
+
+ private void updateLanguageSummary() {
+ ListPreference listPref = (ListPreference) findPreference(KEY_LANGUAGE);
+ listPref.setSummary(listPref.getEntry());
+ }
+
+ private static String join(Collection<String> col, String deliminator) {
+ StringBuilder sb = new StringBuilder();
+ Iterator<String> iter = col.iterator();
+
+ sb.append(iter.next());
+ while (iter.hasNext()) {
+ sb.append(deliminator);
+ sb.append(iter.next());
+ }
+ return sb.toString();
+ }
}
View
80 src/org/dyndns/pawitp/muwifiautologin/Utils.java
@@ -13,44 +13,44 @@
import android.util.Log;
public class Utils {
-
- private static final String TAG = "Utils";
-
- public static String stackTraceToString(Exception e) {
- ByteArrayOutputStream os = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(os);
- e.printStackTrace(ps);
- String ret = os.toString();
- ps.close();
- return ret;
- }
-
- public static String getVersionName(Context context) {
- try {
- return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
- } catch (NameNotFoundException e) {
- // Should not happen
- return "Unknown";
- }
- }
-
- public static void loadLocale(Context context) {
- String lang = PreferenceManager.getDefaultSharedPreferences(context).getString(Preferences.KEY_LANGUAGE, Preferences.LANGUAGE_DEFAULT);
- Configuration config = new Configuration();
- if (!lang.equals(Preferences.LANGUAGE_DEFAULT)) {
- config.locale = new Locale(lang);
- }
- else {
- config.locale = Locale.getDefault();
- }
- context.getResources().updateConfiguration(config, null);
- }
-
- public static void setEnableBroadcastReceiver(Context context, boolean enabled) {
- Log.v(TAG, "Setting BroadcastReceiver status to: " + enabled);
-
- ComponentName receiver = new ComponentName(context, NetworkStateChanged.class);
- int state = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
- context.getPackageManager().setComponentEnabledSetting(receiver, state, PackageManager.DONT_KILL_APP);
- }
+
+ private static final String TAG = "Utils";
+
+ public static String stackTraceToString(Exception e) {
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
+ PrintStream ps = new PrintStream(os);
+ e.printStackTrace(ps);
+ String ret = os.toString();
+ ps.close();
+ return ret;
+ }
+
+ public static String getVersionName(Context context) {
+ try {
+ return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
+ } catch (NameNotFoundException e) {
+ // Should not happen
+ return "Unknown";
+ }
+ }
+
+ public static void loadLocale(Context context) {
+ String lang = PreferenceManager.getDefaultSharedPreferences(context).getString(Preferences.KEY_LANGUAGE, Preferences.LANGUAGE_DEFAULT);
+ Configuration config = new Configuration();
+ if (!lang.equals(Preferences.LANGUAGE_DEFAULT)) {
+ config.locale = new Locale(lang);
+ }
+ else {
+ config.locale = Locale.getDefault();
+ }
+ context.getResources().updateConfiguration(config, null);
+ }
+
+ public static void setEnableBroadcastReceiver(Context context, boolean enabled) {
+ Log.v(TAG, "Setting BroadcastReceiver status to: " + enabled);
+
+ ComponentName receiver = new ComponentName(context, NetworkStateChanged.class);
+ int state = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
+ context.getPackageManager().setComponentEnabledSetting(receiver, state, PackageManager.DONT_KILL_APP);
+ }
}
Please sign in to comment.
Something went wrong with that request. Please try again.