commit 24e0100efca280d6e03416c9d8baf77ba0a66a71 Author: Felix Ableitner Date: Sun Nov 25 20:02:28 2012 +0100 Initial commit. diff --git a/AndroidManifest.xml b/AndroidManifest.xml new file mode 100644 index 0000000..75ecb16 --- /dev/null +++ b/AndroidManifest.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7a4a3ea --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. \ No newline at end of file diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..32f2446 --- /dev/null +++ b/NOTICE @@ -0,0 +1,13 @@ +Copyright (C) 2012 Felix Ableitner + +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. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..11e2360 --- /dev/null +++ b/README.md @@ -0,0 +1,6 @@ +Pegasus +================= + +This app allows a user to automatically change his phone profile based on +current position. For example, it can turn the phone to silent mode when +entering the workplace. \ No newline at end of file diff --git a/proguard-project.txt b/proguard-project.txt new file mode 100644 index 0000000..782c598 --- /dev/null +++ b/proguard-project.txt @@ -0,0 +1,14 @@ +# Basic config from http://stackoverflow.com/a/2466662/1837158 + +-dontskipnonpubliclibraryclasses +-dontobfuscate +-forceprocessing +-optimizationpasses 5 + +-keep class * extends android.app.Activity +-keep class * extends android.app.Service +-keep class * extends android.view.View +-assumenosideeffects class android.util.Log { + public static *** d(...); + public static *** v(...); +} diff --git a/project.properties b/project.properties new file mode 100644 index 0000000..e22da9e --- /dev/null +++ b/project.properties @@ -0,0 +1,14 @@ +# This file is automatically generated by Android Tools. +# Do not modify this file -- YOUR CHANGES WILL BE ERASED! +# +# This file must be checked in Version Control Systems. +# +# To customize properties used by the Ant build system edit +# "ant.properties", and override values to adapt the script to your +# project structure. +# +# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): +proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt + +# Project target. +target=android-16 diff --git a/res/drawable-hdpi/content_new.png b/res/drawable-hdpi/content_new.png new file mode 100644 index 0000000..ad8ada6 Binary files /dev/null and b/res/drawable-hdpi/content_new.png differ diff --git a/res/drawable-hdpi/device_access_volume_on.png b/res/drawable-hdpi/device_access_volume_on.png new file mode 100644 index 0000000..7b69ea5 Binary files /dev/null and b/res/drawable-hdpi/device_access_volume_on.png differ diff --git a/res/drawable-hdpi/ic_launcher.png b/res/drawable-hdpi/ic_launcher.png new file mode 100644 index 0000000..0d021d5 Binary files /dev/null and b/res/drawable-hdpi/ic_launcher.png differ diff --git a/res/drawable-ldpi/ic_launcher.png b/res/drawable-ldpi/ic_launcher.png new file mode 100644 index 0000000..e2f84bd Binary files /dev/null and b/res/drawable-ldpi/ic_launcher.png differ diff --git a/res/drawable-mdpi/content_new.png b/res/drawable-mdpi/content_new.png new file mode 100644 index 0000000..4d5d484 Binary files /dev/null and b/res/drawable-mdpi/content_new.png differ diff --git a/res/drawable-mdpi/device_access_volume_on.png b/res/drawable-mdpi/device_access_volume_on.png new file mode 100644 index 0000000..f8dd846 Binary files /dev/null and b/res/drawable-mdpi/device_access_volume_on.png differ diff --git a/res/drawable-mdpi/ic_launcher.png b/res/drawable-mdpi/ic_launcher.png new file mode 100644 index 0000000..8e7436e Binary files /dev/null and b/res/drawable-mdpi/ic_launcher.png differ diff --git a/res/drawable-xhdpi/content_new.png b/res/drawable-xhdpi/content_new.png new file mode 100644 index 0000000..23b9a1c Binary files /dev/null and b/res/drawable-xhdpi/content_new.png differ diff --git a/res/drawable-xhdpi/device_access_volume_on.png b/res/drawable-xhdpi/device_access_volume_on.png new file mode 100644 index 0000000..dfd2b33 Binary files /dev/null and b/res/drawable-xhdpi/device_access_volume_on.png differ diff --git a/res/drawable-xhdpi/ic_launcher.png b/res/drawable-xhdpi/ic_launcher.png new file mode 100644 index 0000000..74e57f9 Binary files /dev/null and b/res/drawable-xhdpi/ic_launcher.png differ diff --git a/res/layout/seekbar_dialog.xml b/res/layout/seekbar_dialog.xml new file mode 100644 index 0000000..97e3164 --- /dev/null +++ b/res/layout/seekbar_dialog.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/res/menu/area_list.xml b/res/menu/area_list.xml new file mode 100644 index 0000000..a410e37 --- /dev/null +++ b/res/menu/area_list.xml @@ -0,0 +1,31 @@ + + + + + + + + + + \ No newline at end of file diff --git a/res/menu/area_list_context.xml b/res/menu/area_list_context.xml new file mode 100644 index 0000000..8b9a874 --- /dev/null +++ b/res/menu/area_list_context.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/res/menu/profile_list.xml b/res/menu/profile_list.xml new file mode 100644 index 0000000..ea91d04 --- /dev/null +++ b/res/menu/profile_list.xml @@ -0,0 +1,25 @@ + + + + + + + + \ No newline at end of file diff --git a/res/values/strings.xml b/res/values/strings.xml new file mode 100644 index 0000000..06f93d0 --- /dev/null +++ b/res/values/strings.xml @@ -0,0 +1,86 @@ + + + + + + + Pegasus + + + Unknown Area + Normal + Silent + Home + Work + + + Areas + Welcome + This app automatically activates different profiles when you enter certain areas.\n\nTo get started, choose or create an area you are currently at, long click on it and choose \'learn\'. Select the interval you were or will be in the area.\n\nThe app will then apply the associated profile whenever you enter the area (note that inaccuracies of multiple kilometers/miles may occur).\n\nYou can see the current area and profile in the notification. + None + Choose Profile + Learn Area + Rename Area + Delete Area + Do you really want to delete this area? + New Area + + + Next 6 hours + Next 3 hours + Next 2 hours + Next hour + Next 30 minutes + Next 10 minutes + Next 5 minutes + Next minute + Last minute + Last 5 minutes + Last 10 minutes + Last 30 minutes + Last hour + Last 2 hours + Last 3 hours + Last 6 hours + + + + Profiles + Delete Profile + Do you really want to delete this profile? + Rename Profile + New Profile + Edit Profile + + + Please choose the volume level + Ringtone Volume + Notification Volume + Media Volume + Alarm Volume + Ringer Mode + Wifi Enabled + + Normal + Silent + Vibrate only + + + + Unknown Area + No profile + + diff --git a/res/values/values.xml b/res/values/values.xml new file mode 100644 index 0000000..28ecaf3 --- /dev/null +++ b/res/values/values.xml @@ -0,0 +1,50 @@ + + + + + + + 0.1.0 + + + + + 21600000 + 10800000 + 7200000 + 3600000 + 1800000 + 600000 + 300000 + 60000 + -60000 + -300000 + -600000 + -1800000 + -3600000 + -7200000 + -10800000 + -21600000 + + + + + "2" + "0" + "1" + + + \ No newline at end of file diff --git a/res/xml/profile.xml b/res/xml/profile.xml new file mode 100644 index 0000000..7c3c5a2 --- /dev/null +++ b/res/xml/profile.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/com/github/nutomic/pegasus/BootCompletedReceiver.java b/src/com/github/nutomic/pegasus/BootCompletedReceiver.java new file mode 100644 index 0000000..7ed10f5 --- /dev/null +++ b/src/com/github/nutomic/pegasus/BootCompletedReceiver.java @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2012 Felix Ableitner + * + * 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.github.nutomic.pegasus; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; + +/** + * Launches LocationService on boot. + * + * @author Felix Ableitner + * + */ +public class BootCompletedReceiver extends BroadcastReceiver { + + /** + * Start LocationService. + */ + @Override + public void onReceive(Context context, Intent intent) { + context.startService(new Intent(context, LocationService.class)); + } + +} diff --git a/src/com/github/nutomic/pegasus/LocationService.java b/src/com/github/nutomic/pegasus/LocationService.java new file mode 100644 index 0000000..66e9341 --- /dev/null +++ b/src/com/github/nutomic/pegasus/LocationService.java @@ -0,0 +1,370 @@ +/* + * Copyright (C) 2012 Felix Ableitner + * + * 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.github.nutomic.pegasus; + +import java.util.Set; + +import android.app.Notification; +import android.app.PendingIntent; +import android.app.Service; +import android.content.ContentValues; +import android.content.Context; +import android.content.Intent; +import android.database.Cursor; +import android.media.AudioManager; +import android.net.wifi.WifiManager; +import android.os.Bundle; +import android.os.IBinder; +import android.os.SystemClock; +import android.support.v4.app.NotificationCompat; +import android.telephony.CellLocation; +import android.telephony.PhoneStateListener; +import android.telephony.TelephonyManager; +import android.telephony.cdma.CdmaCellLocation; +import android.telephony.gsm.GsmCellLocation; +import android.util.Log; + +import com.github.nutomic.pegasus.activities.AreaList; +import com.github.nutomic.pegasus.content.AreaColumns; +import com.github.nutomic.pegasus.content.CellColumns; +import com.github.nutomic.pegasus.content.CellLogColumns; +import com.github.nutomic.pegasus.content.Database; +import com.github.nutomic.pegasus.content.ProfileColumns; + +/** + * Changes the sound profile when a different network cell is entered. + * + * @author Felix Ableitner + * + */ +public class LocationService extends Service { + + /** + * Start learning an area, pass time interval in seconds as data. Must + * also set MESSAGE_LEARN_AREA. + */ + public static final String MESSAGE_LEARN_INTERVAL = "learn_interval"; + + /** + * Start learning an area, pass the id of the area to learn. Must also + * set MESSAGE_LEARN_INTERVAL. + */ + public static final String MESSAGE_LEARN_AREA = "learn_area"; + + /** Areas or profiles updated, reapply current profile. */ + public static final String MESSAGE_UPDATE = "update"; + + private static final int NOTIFICATION_ID = 1; + + private static final String TAG = "LocationService"; + + private static final int CELL_NO_SIGNAL = -1; + + /** Database ID of the current area. */ + private volatile long mCurrentArea = Database.ROW_NONE; + + private volatile int mCurrentCell = CELL_NO_SIGNAL; + + /** The database ID of the area to assign new cells to. */ + private volatile long mLearnArea = Database.ROW_NONE; + + /** Time limit after which to stop learning mLearnArea. */ + private volatile long mLearnUntil = 0; + + private Notification mNotification = null; + + private CellListener mCellListener; + + private class CellListener extends PhoneStateListener { + + /** + * Network type as TelephonyManager.PHONE_TYPE_CDMA or + * TelephonyManager.PHONE_TYPE_GSM. + */ + private final int mNetworkType; + + /** + * Set the network type on start as callback is only called on changes. + */ + CellListener(int networkType) { + mNetworkType = networkType; + } + + /** + * Read the cell id, add it to the database if it is entered + * for the first time, log it, apply the associated sound profile. + */ + @Override + public void onCellLocationChanged(final CellLocation location) { + super.onCellLocationChanged(location); + + new Thread(new Runnable() { + + @Override + public void run() { + int cell = CELL_NO_SIGNAL; + + if (mNetworkType == TelephonyManager.PHONE_TYPE_CDMA) { + CdmaCellLocation l = (CdmaCellLocation) location; + cell = l.getBaseStationId(); + } else if (mNetworkType == TelephonyManager.PHONE_TYPE_GSM) { + GsmCellLocation l = (GsmCellLocation) location; + cell = l.getCid(); + } + + // Ignore no signal. + if (cell == CELL_NO_SIGNAL) { + Log.i(TAG, "Lost signal, igoring"); + return; + } + + Log.i(TAG, "Switch to cell " + Integer.toString(cell)); + + final Database db = Database.getInstance(LocationService.this); + + // Get cell ID if cell exists. + Cursor c = db.getReadableDatabase().query( + CellColumns.TABLE_NAME + " as c, " + AreaColumns.TABLE_NAME + " as a", + new String[] { "c." + CellColumns._ID + " as cell_id", + "a." + AreaColumns._ID + " as area_id" }, + "a." + AreaColumns._ID + " = c." + CellColumns.AREA_ID + " " + + "AND " + CellColumns.CELL_ID + " = ? " + + "AND " + CellColumns.CELL_TYPE + " = ?", + new String[] { Long.toString(cell), + Integer.toString(mNetworkType) }, + null, null, null); + long cellRow = Database.ROW_NONE; + long newArea = Database.ROW_NONE; + + // If cell is in database, select and update if necessary. + if (c.moveToFirst()) { + // Get the values. + cellRow = c.getLong(c.getColumnIndex("cell_id")); + newArea = c.getLong(c.getColumnIndex("area_id")); + // Update the cell if we are learning an area. + if (SystemClock.elapsedRealtime() <= mLearnUntil) { + ContentValues cv = new ContentValues(); + cv.put(CellColumns.AREA_ID, mLearnArea); + db.getWritableDatabase().update(CellColumns.TABLE_NAME, + cv, + CellColumns._ID + " = ?", + new String[] { Long.toString(cellRow) }); + newArea = mLearnArea; + } + } + // Create cell if it does not exist. + else { + // Check if we are still learning, if not use default area. + newArea = (SystemClock.elapsedRealtime() <= mLearnUntil) + ? mLearnArea + : AreaColumns.AREA_DEFAULT; + + ContentValues cv = new ContentValues(); + cv.put(CellColumns.AREA_ID, newArea); + cv.put(CellColumns.CELL_ID, cell); + cv.put(CellColumns.CELL_TYPE, mNetworkType); + cellRow = db.getWritableDatabase() + .insert(CellColumns.TABLE_NAME, null, cv); + } + + // Only apply profile if we weren't in the same area before. + if (mCurrentArea != newArea) { + mCurrentArea = newArea; + applyProfile(cell); + } + + // Log cell. + ContentValues cv = new ContentValues(); + cv.put(CellLogColumns.CELL_ID, cellRow); + cv.put(CellLogColumns.TIMESTAMP, System.currentTimeMillis()); + db.getWritableDatabase().insert(CellLogColumns.TABLE_NAME, null, cv); + + mCurrentCell = cell; + } + }).start(); + } + + /** + * Applies the profile for the current area. + */ + private void applyProfile(final int cell) { + new Thread(new Runnable() { + + @Override + public void run() { + final Database db = Database.getInstance(LocationService.this); + + // Get area name and ID of the associated profile. + Cursor c = db.getReadableDatabase().query( + AreaColumns.TABLE_NAME + " as a, " + CellColumns.TABLE_NAME, + new String[] { AreaColumns.PROFILE_ID, AreaColumns.NAME }, + "a." + AreaColumns._ID + " = " + CellColumns.AREA_ID + " AND " + + CellColumns.CELL_ID + " = ? AND " + + CellColumns.CELL_TYPE + " = ?", + new String[] { Integer.toString(mCurrentCell), + Integer.toString(mNetworkType)}, + null, null, null); + + long profileId = Database.ROW_NONE; + String areaName; + if (c.moveToFirst()) { + profileId = c.getLong(c.getColumnIndex(AreaColumns.PROFILE_ID)); + areaName = c.getString(c.getColumnIndex(AreaColumns.NAME)); + } + else { + areaName = getResources().getString( + R.string.locationservice_area_unknown); + } + + c = db.getReadableDatabase().query( + ProfileColumns.TABLE_NAME, + new String[] { ProfileColumns.NAME, + ProfileColumns.RINGTONE_VOLUME, + ProfileColumns.NOTIFICATION_VOLUME, + ProfileColumns.MEDIA_VOLUME, + ProfileColumns.ALARM_VOLUME, + ProfileColumns.WIFI_ENABLED, + ProfileColumns.RINGER_MODE }, + "_id = ?", + new String[] { Long.toString(profileId) }, + null, null, null); + + // Apply profile if there is one and set the name for the notification. + String profileName; + if (c.moveToFirst()) { + Context context = LocationService.this; + AudioManager am = (AudioManager) context + .getSystemService(Context.AUDIO_SERVICE); + WifiManager wm = (WifiManager) context + .getSystemService(Context.WIFI_SERVICE); + + am.setStreamVolume(AudioManager.STREAM_RING, + c.getInt(c.getColumnIndex(ProfileColumns.RINGTONE_VOLUME)), + AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE); + + am.setStreamVolume(AudioManager.STREAM_NOTIFICATION, + c.getInt(c.getColumnIndex(ProfileColumns.NOTIFICATION_VOLUME)), + AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE); + + am.setStreamVolume(AudioManager.STREAM_MUSIC, + c.getInt(c.getColumnIndex(ProfileColumns.MEDIA_VOLUME)), + AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE); + + am.setStreamVolume(AudioManager.STREAM_ALARM, + c.getInt(c.getColumnIndex(ProfileColumns.ALARM_VOLUME)), + AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE); + + am.setRingerMode(c.getInt(c.getColumnIndex(ProfileColumns.RINGER_MODE))); + + wm.setWifiEnabled((c.getInt(c.getColumnIndex(ProfileColumns.WIFI_ENABLED)) == 0) + ? true : false); + + profileName = c.getString(c.getColumnIndex(ProfileColumns.NAME)); + } + else { + profileName = getResources().getString( + R.string.arealist_profile_none); + } + + Log.i(TAG, "Apply profile " + profileName + + " (in area " + areaName + ")"); + showNotification(areaName, profileName); + } + }).start(); + } + } + + /** + * Convenience method for sending an Intent with MESSAGE_UPDATE + * to the service. + * + * @param context Application context. + */ + public static void sendUpdateIntent(Context context) { + Intent i = new Intent(context, LocationService.class); + // Value is unused. + i.putExtra(MESSAGE_UPDATE, 0); + context.startService(i); + } + + /** + * Register CellListener and show Notification. + */ + @Override + public void onCreate() { + super.onCreate(); + TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); + mCellListener = new CellListener(tm.getPhoneType()); + tm.listen(mCellListener, PhoneStateListener.LISTEN_CELL_LOCATION); + // Force update. + mCellListener.onCellLocationChanged(tm.getCellLocation()); + } + + /** + * Show Notification displaying area and profile. + * + * @param area Currently active area. + * @param profile Currently active profile. + */ + private void showNotification(String area, String profile) { + mNotification = new NotificationCompat.Builder(this) + .setContentTitle(area) + .setContentText(profile) + .setSmallIcon(R.drawable.ic_launcher) + .setAutoCancel(false) + .setOngoing(true) + .setContentIntent(PendingIntent.getActivity(this, 0, + new Intent(this, AreaList.class), 0)) + .build(); + + startForeground(NOTIFICATION_ID, mNotification); + } + + /** + * Receive start Intent, start learning an area or check if the + * sound profile for the current area has changed. + */ + @Override + public int onStartCommand(Intent intent, int flags, int startId) { + if (intent != null) { + Bundle extras = intent.getExtras(); + if (extras != null) { + Set keys = extras.keySet(); + if (keys.contains(MESSAGE_LEARN_AREA)) { + // Set the area to learn now and the learn duration. + mLearnUntil = SystemClock.elapsedRealtime() + + extras.getLong(MESSAGE_LEARN_INTERVAL); + mLearnArea = extras.getLong(MESSAGE_LEARN_AREA); + } + if (keys.contains(MESSAGE_UPDATE)) { + // Profile/area mappings have changed, reapply profile. + mCellListener.applyProfile(mCurrentCell); + } + } + } + return START_STICKY; + } + + /** + * Cannot bind. + */ + @Override + public IBinder onBind(Intent intent) { + return null; + } + +} diff --git a/src/com/github/nutomic/pegasus/VolumePreference.java b/src/com/github/nutomic/pegasus/VolumePreference.java new file mode 100644 index 0000000..8ddcb73 --- /dev/null +++ b/src/com/github/nutomic/pegasus/VolumePreference.java @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2012 Felix Ableitner + * + * 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.github.nutomic.pegasus; + +import android.content.Context; +import android.preference.DialogPreference; +import android.util.AttributeSet; +import android.view.View; +import android.widget.SeekBar; + +/** + * Preference that opens a SeekBar dialog. + * + * @author Felix Ableitner + * + */ +public class VolumePreference extends DialogPreference { + + private int mMax; + private int mProgress; + private SeekBar mSeekBar; + + /** + * Initialize layout, set Preference not persistent- + */ + public VolumePreference(Context context, AttributeSet attrs) { + super(context, attrs); + + setPersistent(false); + setDialogLayoutResource(R.layout.seekbar_dialog); + + setPositiveButtonText(android.R.string.ok); + setNegativeButtonText(android.R.string.cancel); + } + + @Override + protected void onBindDialogView(View view) { + super.onBindDialogView(view); + + mSeekBar = (SeekBar) view.findViewById(R.id.seekbar); + + mSeekBar.setProgress(mProgress); + mSeekBar.setMax(mMax); + } + + /** + * Set current position of the selector. + */ + @Override + public void setDefaultValue(Object defaultValue) { + mProgress = (Integer) defaultValue; + if (mSeekBar != null) { + mSeekBar.setProgress((Integer) defaultValue); + } + } + + /** + * Set the maximum value for the SeekBar. + */ + public void setMaxValue(int max) { + mMax = max; + if (mSeekBar != null) { + mSeekBar.setMax(max); + } + } + + /** + * Send new value to listener (if positive button was clicked). + */ + @Override + protected void onDialogClosed(boolean positiveResult) { + if (positiveResult) { + mProgress = mSeekBar.getProgress(); + callChangeListener(mProgress); + } + } +} \ No newline at end of file diff --git a/src/com/github/nutomic/pegasus/activities/AreaList.java b/src/com/github/nutomic/pegasus/activities/AreaList.java new file mode 100644 index 0000000..1358247 --- /dev/null +++ b/src/com/github/nutomic/pegasus/activities/AreaList.java @@ -0,0 +1,426 @@ +/* + * Copyright (C) 2012 Felix Ableitner + * + * 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.github.nutomic.pegasus.activities; + +import android.app.AlertDialog; +import android.app.ListActivity; +import android.content.ContentValues; +import android.content.DialogInterface; +import android.content.DialogInterface.OnClickListener; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.SharedPreferences.Editor; +import android.content.res.TypedArray; +import android.database.Cursor; +import android.os.AsyncTask; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.support.v4.widget.SimpleCursorAdapter; +import android.util.Pair; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.WindowManager; +import android.widget.AdapterView.AdapterContextMenuInfo; +import android.widget.EditText; +import android.widget.ListView; + +import com.github.nutomic.pegasus.LocationService; +import com.github.nutomic.pegasus.R; +import com.github.nutomic.pegasus.content.AreaColumns; +import com.github.nutomic.pegasus.content.CellColumns; +import com.github.nutomic.pegasus.content.CellLogColumns; +import com.github.nutomic.pegasus.content.Database; +import com.github.nutomic.pegasus.content.ProfileColumns; + +/** + * Displays a list of areas. + * + * @author Felix Ableitner + * + */ +public class AreaList extends ListActivity { + + public static final String AREANAME = "areaname"; + public static final String PROFILENAME = "profilename"; + + private static final String FIRST_RUN = "first_run"; + + SimpleCursorAdapter mAdapter; + + /** + * AsyncTask that refreshes the ListView and LocationService after finishing. + * + * @author Felix Ableitner + * + */ + private abstract class UpdateTask extends AsyncTask { + + @Override + protected void onPostExecute(Long result) { + updateCursor(); + LocationService.sendUpdateIntent(AreaList.this); + } + + } + + /** + * Initializes layout. + */ + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + registerForContextMenu(getListView()); + mAdapter = new SimpleCursorAdapter(this, + android.R.layout.simple_list_item_2, + null, + new String[] { AREANAME, PROFILENAME }, + new int[] { android.R.id.text1, android.R.id.text2 }, + 0); + setListAdapter(mAdapter); + + // Show welcome dialog only on first start. + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); + if (prefs.getBoolean(FIRST_RUN, true)) { + Editor e = prefs.edit(); + e.putBoolean(FIRST_RUN, false); + e.commit(); + + new AlertDialog.Builder(this) + .setTitle(R.string.arealist_intro_title) + .setMessage(R.string.arealist_intro_text) + .setPositiveButton(android.R.string.ok, null) + .show(); + } + + // Make sure LocationService is running. + startService(new Intent(this, LocationService.class)); + } + + /** + * Open SQL cursor. + */ + @Override + protected void onStart() { + super.onStart(); + updateCursor(); + } + + /** + * Close SQL cursor. + */ + @Override + protected void onStop() { + super.onStop(); + mAdapter.changeCursor(null); + } + + /** + * Replace the current list cursor with a new one. + */ + private void updateCursor() { + // Default string if noe profile is set. + String noProfile = getResources().getString(R.string.arealist_profile_none); + mAdapter.changeCursor(Database.getInstance(this) + .getReadableDatabase().rawQuery( + "SELECT a._id, a.name as " + AREANAME + ", " + + "ifnull(p.name, '" + noProfile + "') as " + PROFILENAME + " " + + "FROM " + AreaColumns.TABLE_NAME + " as a " + + "LEFT JOIN " + ProfileColumns.TABLE_NAME + " as p " + + "ON a.profile_id = p._id " + + "ORDER BY a." + AreaColumns._ID + " ASC", + null)); + } + + /** + * Open corresponding sound profile. + */ + @Override + protected void onListItemClick(ListView l, View v, int position, long id) { + chooseProfile(id); + } + + /** + * Show a "pick sound profile" dialog for an area, the selected profile is + * then set to be launched when entering the area. + * + * @param area + * The sqlite id of the area to choose a profile for. Set -1 if + * the area does not exist and should be created. + */ + private void chooseProfile(final long area) { + final Database db = Database.getInstance(this); + + // Get a pair of all area names and all area IDs. + Cursor c = db.getReadableDatabase().query( + ProfileColumns.TABLE_NAME, + new String[] { ProfileColumns._ID, + ProfileColumns.NAME }, + null, null, null, null, null); + String[] names = new String[c.getCount()]; + Long[] ids = new Long[c.getCount()]; + while (c.moveToNext()) { + ids[c.getPosition()] = c.getLong(c.getColumnIndex(ProfileColumns._ID)); + names[c.getPosition()] = c.getString(c.getColumnIndex(ProfileColumns.NAME)); + } + final Pair p = Pair.create(names, ids); + + new AlertDialog.Builder(this).setTitle(R.string.arealist_profile_choose) + .setItems(p.first, new DialogInterface.OnClickListener() { + + public void onClick(DialogInterface dialog, final int which) { + new UpdateTask() { + + @Override + protected Long doInBackground(Void... params) { + // Set the new profile in area. + ContentValues cv = new ContentValues(); + cv.put(AreaColumns.PROFILE_ID, p.second[which]); + + db.getWritableDatabase().update(AreaColumns.TABLE_NAME, + cv, + AreaColumns._ID + " = ?", + new String[] { Long.toString(area) }); + return null; + } + }.execute((Void) null); + } + }).show(); + } + + /** + * Create context menu for ListView items. Modifiers are hidden for the + * default area. + */ + public void onCreateContextMenu(android.view.ContextMenu menu, View v, + android.view.ContextMenu.ContextMenuInfo menuInfo) { + getMenuInflater().inflate(R.menu.area_list_context, menu); + AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; + + String name = getAreaName(info); + + menu.setHeaderTitle(name); + + // Default area selected, can't rename, learn or delete. + if (info.id == AreaColumns.AREA_DEFAULT) { + menu.removeItem(R.id.rename); + menu.removeItem(R.id.learn); + menu.removeItem(R.id.delete); + } + } + + private String getAreaName(AdapterContextMenuInfo info) { + Cursor c = (Cursor) mAdapter.getItem(info.position); + return c.getString(c.getColumnIndex(AREANAME)); + } + + /** + * Context item on ListView selected, allow choosing the associated sound + * profile, renaming, learning or deleting the area. + */ + @Override + public boolean onContextItemSelected(MenuItem item) { + final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item + .getMenuInfo(); + final Database db = Database.getInstance(this); + switch (item.getItemId()) { + case R.id.choose: + chooseProfile(info.id); + return true; + case R.id.rename: + renameArea(info.id, getAreaName((AdapterContextMenuInfo) item.getMenuInfo())); + return true; + case R.id.learn: + new AlertDialog.Builder(this) + .setTitle(R.string.arealist_learn) + .setItems(R.array.arealist_learn_area_strings, + new DialogInterface.OnClickListener() { + + public void onClick(DialogInterface dialog, + int which) { + TypedArray millisecondValues = getResources() + .obtainTypedArray( + R.array.arealist_learn_area_values); + long interval = millisecondValues.getInt(which, 0); + + if (interval > 0) { + // Add future cells during interval. + Intent i = new Intent(AreaList.this, LocationService.class); + i.putExtra(LocationService.MESSAGE_LEARN_AREA, info.id); + i.putExtra(LocationService.MESSAGE_LEARN_INTERVAL, interval); + startService(i); + // Add only the current cell from database. + interval = 0; + } else { + // Do not pass the negativity to Database. + interval = -interval; + } + + final long selectionStartTime = System.currentTimeMillis() - interval; + new UpdateTask() { + + @Override + protected Long doInBackground(Void... params) { + ContentValues cv = new ContentValues(); + cv.put(CellColumns.AREA_ID, info.id); + // Set current area in current cell and in any cell that was visited during interval. + db.getWritableDatabase().update(CellColumns.TABLE_NAME, + cv, + CellColumns._ID + " = (SELECT " + CellLogColumns.CELL_ID + " FROM " + + CellLogColumns.TABLE_NAME + " ORDER BY " + + CellLogColumns.TIMESTAMP + " DESC Limit 1) OR " + + CellColumns._ID + " IN (SELECT " + + CellLogColumns.CELL_ID + " FROM " + + CellLogColumns.TABLE_NAME + " WHERE " + + CellLogColumns.TIMESTAMP + " > ?)", + new String[] { Long.toString(selectionStartTime) }); + return null; + } + }.execute((Void) null); + } + }) + .show(); + return true; + case R.id.delete: + new AlertDialog.Builder(this) + .setTitle(R.string.arealist_delete) + .setMessage(R.string.arealist_delete_message) + .setPositiveButton(android.R.string.yes, new OnClickListener() { + + @Override + public void onClick(DialogInterface dialog, int which) { + new UpdateTask() { + + @Override + protected Long doInBackground(Void... params) { + // Don't delete default area. + if (info.id != AreaColumns.AREA_DEFAULT) { + db.getWritableDatabase().delete(AreaColumns.TABLE_NAME, + AreaColumns._ID + " = ?", + new String[] { Long.toString(info.id) }); + // Reset cells to default area. + ContentValues cv = new ContentValues(); + cv.put(CellColumns.AREA_ID, AreaColumns.AREA_DEFAULT); + db.getWritableDatabase().update(CellColumns.TABLE_NAME, + cv, + CellColumns.AREA_ID + " = ?", + new String[] { Long.toString(info.id) }); + } + return null; + } + }.execute((Void) null); + } + }) + .setNegativeButton(android.R.string.no, null) + .show(); + return true; + default: + return super.onContextItemSelected(item); + } + } + + /** + * Show an AlertDialog to edit the name of an area. + * + * @param area ID of the area to rename. + */ + private void renameArea(final long id, String name) { + final Database db = Database.getInstance(this); + final EditText input = new EditText(this); + input.setText(name); + input.setSingleLine(); + AlertDialog alert = new AlertDialog.Builder(this) + .setTitle(R.string.arealist_rename) + .setView(input) + .setPositiveButton(android.R.string.ok, + new OnClickListener() { + + public void onClick(DialogInterface dialog, + int which) { + new UpdateTask() { + + @Override + protected Long doInBackground(Void... params) { + // Don't rename default area. + if (id != AreaColumns.AREA_DEFAULT) { + ContentValues cv = new ContentValues(); + cv.put(AreaColumns.NAME, input.getText().toString()); + + db.getWritableDatabase().update(AreaColumns.TABLE_NAME, + cv, + AreaColumns._ID + " = ?", + new String[] { Long.toString(id) }); + } + return null; + } + }.execute((Void) null); + } + }) + .setNegativeButton(android.R.string.cancel, null) + .create(); + alert.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); + alert.show(); + input.selectAll(); + } + + /** + * Create ActionBar menu from xml. + */ + @Override + public boolean onCreateOptionsMenu(Menu menu) { + MenuInflater inflater = getMenuInflater(); + inflater.inflate(R.menu.area_list, menu); + return true; + } + + /** + * Handle ActionBar item selections. + */ + @Override + public boolean onOptionsItemSelected(final MenuItem item) { + switch (item.getItemId()) { + case R.id.profiles: + startActivity(new Intent(this, ProfileList.class)); + return true; + case R.id.new_area: + new UpdateTask() { + + @Override + protected Long doInBackground(Void... arg0) { + ContentValues cv = new ContentValues(); + cv.put(AreaColumns.NAME, getResources() + .getString(R.string.arealist_new)); + cv.put(AreaColumns.PROFILE_ID, Database.ROW_NONE); + return Database.getInstance(AreaList.this).getWritableDatabase() + .insert(AreaColumns.TABLE_NAME, null, cv); + } + + @Override + protected void onPostExecute(Long result) { + super.onPostExecute(result); + renameArea(result, getAreaName((AdapterContextMenuInfo) item.getMenuInfo())); + } + }.execute((Void) null); + return true; + default: + return super.onOptionsItemSelected(item); + } + } + +} diff --git a/src/com/github/nutomic/pegasus/activities/ProfileEdit.java b/src/com/github/nutomic/pegasus/activities/ProfileEdit.java new file mode 100644 index 0000000..93537ef --- /dev/null +++ b/src/com/github/nutomic/pegasus/activities/ProfileEdit.java @@ -0,0 +1,175 @@ +/* + * Copyright (C) 2012 Felix Ableitner + * + * 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.github.nutomic.pegasus.activities; + +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.media.AudioManager; +import android.os.AsyncTask; +import android.os.Bundle; +import android.preference.CheckBoxPreference; +import android.preference.ListPreference; +import android.preference.Preference; +import android.preference.Preference.OnPreferenceChangeListener; +import android.preference.PreferenceActivity; + +import com.github.nutomic.pegasus.LocationService; +import com.github.nutomic.pegasus.R; +import com.github.nutomic.pegasus.VolumePreference; +import com.github.nutomic.pegasus.content.Database; +import com.github.nutomic.pegasus.content.ProfileColumns; + +/** + * Allows editing a sound profile, uses Database values (or defaults) to + * initialize, saves to Database. + * + * Using deprecated methods because v4 support library does not have + * PreferenceFragment implementation. + * + * @author Felix Ableitner + * + */ +public class ProfileEdit extends PreferenceActivity implements + OnPreferenceChangeListener { + + /** Key for the Intent extra to store the profile edited here. */ + public static final String PROFILE_ID = "profile_id"; + + private volatile long mProfile; + private VolumePreference mRingtoneVolume; + private VolumePreference mNotificationVolume; + private VolumePreference mMediaVolume; + private VolumePreference mAlarmVolume; + private ListPreference mRingerMode; + private CheckBoxPreference mWifiEnabled; + + /** + * Initialize sound profile id from intent (extra "profile_id" must + * be set. + */ + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + mProfile = getIntent().getExtras().getLong(PROFILE_ID); + + addPreferencesFromResource(R.xml.profile); + + new AsyncTask() { + + @Override + protected Cursor doInBackground(Void... params) { + Cursor c = Database.getInstance(ProfileEdit.this).getReadableDatabase().query( + ProfileColumns.TABLE_NAME, + new String[] { ProfileColumns.NAME, + ProfileColumns.RINGTONE_VOLUME, + ProfileColumns.NOTIFICATION_VOLUME, + ProfileColumns.MEDIA_VOLUME, + ProfileColumns.ALARM_VOLUME, + ProfileColumns.WIFI_ENABLED, + ProfileColumns.RINGER_MODE }, + "_id = ?", + new String[] { Long.toString(mProfile) }, + null, null, null); + c.moveToFirst(); + return c; + } + + protected void onPostExecute(Cursor c) { + setTitle(c.getString(c.getColumnIndex(ProfileColumns.NAME))); + + final AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); + + mRingtoneVolume = (VolumePreference) findPreference("ringtone_volume"); + mRingtoneVolume.setMaxValue(am.getStreamMaxVolume(AudioManager.STREAM_RING)); + mRingtoneVolume.setDefaultValue(c.getInt(c.getColumnIndex(ProfileColumns.RINGTONE_VOLUME))); + mRingtoneVolume.setOnPreferenceChangeListener(ProfileEdit.this); + + mNotificationVolume = (VolumePreference) findPreference("notification_volume"); + mNotificationVolume.setMaxValue(am.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION)); + mNotificationVolume.setDefaultValue(c.getInt(c.getColumnIndex(ProfileColumns.NOTIFICATION_VOLUME))); + mNotificationVolume.setOnPreferenceChangeListener(ProfileEdit.this); + + mMediaVolume = (VolumePreference) findPreference("media_volume"); + mMediaVolume.setMaxValue(am.getStreamMaxVolume(AudioManager.STREAM_MUSIC)); + mMediaVolume.setDefaultValue(c.getInt(c.getColumnIndex(ProfileColumns.MEDIA_VOLUME))); + mMediaVolume.setOnPreferenceChangeListener(ProfileEdit.this); + + mAlarmVolume = (VolumePreference) findPreference("alarm_volume"); + mAlarmVolume.setMaxValue(am.getStreamMaxVolume(AudioManager.STREAM_ALARM)); + mAlarmVolume.setDefaultValue(c.getInt(c.getColumnIndex(ProfileColumns.ALARM_VOLUME))); + mAlarmVolume.setOnPreferenceChangeListener(ProfileEdit.this); + + mRingerMode = (ListPreference) findPreference("ringer_mode"); + mRingerMode.setValue(Integer.toString(c.getInt(c.getColumnIndex(ProfileColumns.RINGER_MODE)))); + mRingerMode.setOnPreferenceChangeListener(ProfileEdit.this); + + mWifiEnabled = (CheckBoxPreference) findPreference("wifi_enabled"); + mWifiEnabled.setChecked((c.getInt(c.getColumnIndex(ProfileColumns.WIFI_ENABLED)) == 0) + ? true : false); + mWifiEnabled.setOnPreferenceChangeListener(ProfileEdit.this); + + }; + + }.execute((Void) null); + } + + /** + * Write changed preference to database. + */ + public boolean onPreferenceChange(Preference preference, Object newValue) { + ContentValues cv = new ContentValues(); + if (preference.equals(mRingtoneVolume)) { + cv.put(ProfileColumns.RINGTONE_VOLUME, (Integer) newValue); + } + else if (preference.equals(mNotificationVolume)) { + cv.put(ProfileColumns.NOTIFICATION_VOLUME, (Integer) newValue); + } + else if (preference.equals(mMediaVolume)) { + cv.put(ProfileColumns.MEDIA_VOLUME, (Integer) newValue); + } + else if (preference.equals(mAlarmVolume)) { + cv.put(ProfileColumns.ALARM_VOLUME, (Integer) newValue); + } + else if (preference.equals(mRingerMode)) { + cv.put(ProfileColumns.RINGER_MODE, Integer.parseInt((String) newValue)); + } + else if (preference.equals(mWifiEnabled)) { + cv.put(ProfileColumns.RINGTONE_VOLUME, (Boolean) newValue); + } + + final ContentValues values = cv; + new Thread(new Runnable() { + + @Override + public void run() { + + Database.getInstance(ProfileEdit.this) + .getWritableDatabase().update(ProfileColumns.TABLE_NAME, + values, + ProfileColumns._ID + " = ?", + new String[] { Long.toString(mProfile) }); + + LocationService.sendUpdateIntent(ProfileEdit.this); + } + }).start(); + + return true; + } + +} diff --git a/src/com/github/nutomic/pegasus/activities/ProfileList.java b/src/com/github/nutomic/pegasus/activities/ProfileList.java new file mode 100644 index 0000000..e559441 --- /dev/null +++ b/src/com/github/nutomic/pegasus/activities/ProfileList.java @@ -0,0 +1,282 @@ +/* + * Copyright (C) 2012 Felix Ableitner + * + * 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.github.nutomic.pegasus.activities; + +import android.app.AlertDialog; +import android.app.AlertDialog.Builder; +import android.app.ListActivity; +import android.content.ContentValues; +import android.content.DialogInterface; +import android.content.DialogInterface.OnClickListener; +import android.content.Intent; +import android.database.Cursor; +import android.media.AudioManager; +import android.os.AsyncTask; +import android.os.Bundle; +import android.support.v4.widget.SimpleCursorAdapter; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.WindowManager; +import android.widget.AdapterView.AdapterContextMenuInfo; +import android.widget.EditText; +import android.widget.ListView; + +import com.github.nutomic.pegasus.LocationService; +import com.github.nutomic.pegasus.R; +import com.github.nutomic.pegasus.content.Database; +import com.github.nutomic.pegasus.content.ProfileColumns; + +/** + * Displays a list of profiles. + * + * @author Felix Ableitner + * + */ +public class ProfileList extends ListActivity { + + SimpleCursorAdapter mAdapter; + + /** + * AsyncTask that refreshes the ListView and LocationService after finishing. + * + * @author Felix Ableitner + * + */ + private abstract class UpdateTask extends AsyncTask { + + @Override + protected void onPostExecute(Long result) { + updateCursor(); + LocationService.sendUpdateIntent(ProfileList.this); + } + + } + + /** + * Initialize layout. + */ + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + registerForContextMenu(getListView()); + mAdapter = new SimpleCursorAdapter(this, + android.R.layout.simple_list_item_1, + null, + new String[] { ProfileColumns.NAME }, + new int[] { android.R.id.text1 }, + 0); + setListAdapter(mAdapter); + } + + /** + * Open SQL cursor. + */ + @Override + protected void onStart() { + super.onStart(); + updateCursor(); + } + + /** + * Close SQL cursor. + */ + @Override + protected void onStop() { + super.onStop(); + mAdapter.changeCursor(null); + } + + /** + * Replace the current list cursor with a new one. + */ + private void updateCursor() { + mAdapter.changeCursor(Database.getInstance(this) + .getReadableDatabase().query(ProfileColumns.TABLE_NAME, + new String[]{ ProfileColumns._ID, ProfileColumns.NAME }, + null, + new String[]{}, + null, + null, + ProfileColumns._ID + " ASC")); + } + + /** + * Open corresponding sound profile. + */ + @Override + protected void onListItemClick(ListView l, View v, int position, long id) { + startActivity(new Intent(this, ProfileEdit.class) + .putExtra(ProfileEdit.PROFILE_ID, id)); + } + + /** + * Create context menu for ListView items. + */ + public void onCreateContextMenu(android.view.ContextMenu menu, View v, + android.view.ContextMenu.ContextMenuInfo menuInfo) { + getMenuInflater().inflate(R.menu.profile_list_context, menu); + final AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; + + // Set profile name as menu title. + Cursor c = (Cursor) getListAdapter().getItem(info.position); + menu.setHeaderTitle(c.getString(c.getColumnIndex(ProfileColumns.NAME))); + } + + private String getProfileName(AdapterContextMenuInfo info) { + Cursor c = (Cursor) mAdapter.getItem(info.position); + return c.getString(c.getColumnIndex(ProfileColumns.NAME)); + } + + /** + * Context menu selection, edit, rename or delete profile. + */ + @Override + public boolean onContextItemSelected(MenuItem item) { + final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item + .getMenuInfo(); + final Database db = Database.getInstance(this); + switch (item.getItemId()) { + case R.id.edit: + Intent i = new Intent(this, ProfileEdit.class); + i.putExtra(ProfileEdit.PROFILE_ID, info.id); + startActivity(i); + return true; + case R.id.rename: + renameProfile(info.id, getProfileName((AdapterContextMenuInfo) item.getMenuInfo())); + return true; + case R.id.delete: + new Builder(this) + .setTitle(R.string.profilelist_delete) + .setMessage(R.string.profilelist_delete_message) + .setPositiveButton(android.R.string.yes, + new OnClickListener() { + + public void onClick(DialogInterface dialog, + int which) { + new UpdateTask() { + + @Override + protected Long doInBackground(Void... arg0) { + db.getWritableDatabase().delete(ProfileColumns.TABLE_NAME, + ProfileColumns._ID + " = ?", + new String[] { Long.toString(info.id) }); + return null; + } + }.execute((Void) null); + } + }).setNegativeButton(android.R.string.no, null) + .show(); + return true; + default: + return super.onContextItemSelected(item); + } + } + + /** + * Show an AlertDialog to edit the name of a profile. + * + * @param profile ID of the profile to rename. + */ + private void renameProfile(final long profile, String name) { + final EditText input = new EditText(this); + input.setText(name); + input.setSingleLine(); + AlertDialog alert = new AlertDialog.Builder(this) + .setTitle(R.string.profilelist_rename) + .setView(input) + .setPositiveButton(android.R.string.ok, + new OnClickListener() { + + public void onClick(DialogInterface dialog, + int which) { + new UpdateTask() { + + @Override + protected Long doInBackground(Void... params) { + ContentValues cv = new ContentValues(); + cv.put(ProfileColumns.NAME, input.getText().toString()); + Database.getInstance(ProfileList.this) + .getWritableDatabase().update( + ProfileColumns.TABLE_NAME, + cv, + ProfileColumns._ID + " = ?", + new String[] { Long.toString(profile) }); + return null; + } + }.execute((Void) null); + } + }) + .setNegativeButton(android.R.string.cancel, null) + .create(); + alert.getWindow().setSoftInputMode( + WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); + alert.show(); + input.selectAll(); + } + + /** + * Create ActionBar menu. + */ + @Override + public boolean onCreateOptionsMenu(Menu menu) { + MenuInflater inflater = getMenuInflater(); + inflater.inflate(R.menu.profile_list, menu); + return true; + } + + /** + * Handle ActionBar item selections. + */ + @Override + public boolean onOptionsItemSelected(final MenuItem item) { + switch (item.getItemId()) { + case R.id.new_item: + new UpdateTask() { + + @Override + protected Long doInBackground(Void... params) { + // Insert new profile into database. + ContentValues cv = new ContentValues(); + cv.put(ProfileColumns.NAME, getResources() + .getString(R.string.profilelist_new)); + cv.put(ProfileColumns.RINGTONE_VOLUME, 5); + cv.put(ProfileColumns.NOTIFICATION_VOLUME, 5); + cv.put(ProfileColumns.MEDIA_VOLUME, 5); + cv.put(ProfileColumns.ALARM_VOLUME, 5); + cv.put(ProfileColumns.WIFI_ENABLED, true); + cv.put(ProfileColumns.RINGER_MODE, AudioManager.RINGER_MODE_NORMAL); + + return Database.getInstance(ProfileList.this).getWritableDatabase() + .insert(ProfileColumns.TABLE_NAME, null, cv); + } + + @Override + protected void onPostExecute(Long result) { + super.onPostExecute(result); + renameProfile(result, getProfileName((AdapterContextMenuInfo) item.getMenuInfo())); + } + }.execute((Void) null); + return true; + default: + return super.onOptionsItemSelected(item); + } + } + +} diff --git a/src/com/github/nutomic/pegasus/content/AreaColumns.java b/src/com/github/nutomic/pegasus/content/AreaColumns.java new file mode 100644 index 0000000..9362827 --- /dev/null +++ b/src/com/github/nutomic/pegasus/content/AreaColumns.java @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2012 Felix Ableitner + * + * 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.github.nutomic.pegasus.content; + +import android.provider.BaseColumns; + +/** + * Area table columns. + * + * @author Felix Ableitner + * + */ +public class AreaColumns implements BaseColumns { + + public static final String TABLE_NAME = "area"; + + public static final long AREA_DEFAULT = 1; + + // Columns + public static final String NAME = "name"; + public static final String PROFILE_ID = "profile_id"; + + public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + + NAME + " TEXT," + + PROFILE_ID + " INTEGER" + + ");"; + +} diff --git a/src/com/github/nutomic/pegasus/content/CellColumns.java b/src/com/github/nutomic/pegasus/content/CellColumns.java new file mode 100644 index 0000000..1cff26c --- /dev/null +++ b/src/com/github/nutomic/pegasus/content/CellColumns.java @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2012 Felix Ableitner + * + * 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.github.nutomic.pegasus.content; + +import android.provider.BaseColumns; + +/** + * Cell table columns. + * + * @author Felix Ableitner + * + */ +public class CellColumns implements BaseColumns { + + public static final String TABLE_NAME = "cell"; + + // Columns + public static final String AREA_ID = "area_id"; + public static final String CELL_ID = "cell_id"; + public static final String CELL_TYPE = "cell_type"; + + public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + + AREA_ID + " INTEGER," + + CELL_ID + " INTEGER," + + CELL_TYPE + " INTEGER" + + ");"; + +} diff --git a/src/com/github/nutomic/pegasus/content/CellLogColumns.java b/src/com/github/nutomic/pegasus/content/CellLogColumns.java new file mode 100644 index 0000000..b2fb7d0 --- /dev/null +++ b/src/com/github/nutomic/pegasus/content/CellLogColumns.java @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2012 Felix Ableitner + * + * 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.github.nutomic.pegasus.content; + +import android.provider.BaseColumns; + +/** + * Cell log table columns. + * + * @author Felix Ableitner + * + */ +public class CellLogColumns implements BaseColumns { + + public static final String TABLE_NAME = "cell_log"; + + // Columns + public static final String CELL_ID = "cell_id"; + public static final String TIMESTAMP = "timestamp"; + + + public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + + CELL_ID + " INTEGER," + + TIMESTAMP + " INTEGER" + + ");"; + +} diff --git a/src/com/github/nutomic/pegasus/content/Database.java b/src/com/github/nutomic/pegasus/content/Database.java new file mode 100644 index 0000000..aa79c3b --- /dev/null +++ b/src/com/github/nutomic/pegasus/content/Database.java @@ -0,0 +1,128 @@ +/* + * Copyright (C) 2012 Felix Ableitner + * + * 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.github.nutomic.pegasus.content; + +import android.content.ContentValues; +import android.content.Context; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteOpenHelper; +import android.media.AudioManager; +import android.util.Log; + +import com.github.nutomic.pegasus.R; + +/** + * Singleton that handles SQL database connection and provides + * methods for common queries. + * + * @author Felix Ableitner + * + */ +public class Database extends SQLiteOpenHelper { + + public static final long ROW_NONE = -1; + + private static final String TAG = "Database"; + private static final String DATABASE_NAME = "pegasus.db"; + private static final int DATABASE_VERSION = 1; + + private static Database mInstance = null; + + private Context mContext; + + /** + * Return the database instance, creating it if it does not exist. + * + * @param context + * The context to start in. Will automatically take the app + * context of it. + * @return The databse instance. + */ + public static synchronized Database getInstance(Context context) { + if (mInstance == null) { + mInstance = new Database(context.getApplicationContext()); + } + return mInstance; + } + + private Database(Context context) { + super(context, DATABASE_NAME, null, DATABASE_VERSION); + mContext = context; + } + + /** + * Create tables (area, profile, cell, cell_log). + */ + @Override + public void onCreate(SQLiteDatabase db) { + Log.i(TAG, "Creating database tables."); + db.execSQL(AreaColumns.CREATE_TABLE); + db.execSQL(ProfileColumns.CREATE_TABLE); + db.execSQL(CellColumns.CREATE_TABLE); + db.execSQL(CellLogColumns.CREATE_TABLE); + + // Insert "Normal" profile. + ContentValues cv = new ContentValues(); + cv.put(ProfileColumns.NAME, mContext.getResources() + .getString(R.string.sql_profile_normal)); + cv.put(ProfileColumns.RINGTONE_VOLUME, 5); + cv.put(ProfileColumns.NOTIFICATION_VOLUME, 5); + cv.put(ProfileColumns.MEDIA_VOLUME, 9); + cv.put(ProfileColumns.ALARM_VOLUME, 5); + cv.put(ProfileColumns.WIFI_ENABLED, true); + cv.put(ProfileColumns.RINGER_MODE, AudioManager.RINGER_MODE_NORMAL); + long normal = db.insert(ProfileColumns.TABLE_NAME, null, cv); + + // Insert "Silent" profile. + cv = new ContentValues(); + cv.put(ProfileColumns.NAME, mContext.getResources() + .getString(R.string.sql_profile_silent)); + cv.put(ProfileColumns.RINGTONE_VOLUME, 0); + cv.put(ProfileColumns.NOTIFICATION_VOLUME, 0); + cv.put(ProfileColumns.MEDIA_VOLUME, 0); + cv.put(ProfileColumns.ALARM_VOLUME, 0); + cv.put(ProfileColumns.WIFI_ENABLED, true); + cv.put(ProfileColumns.RINGER_MODE, AudioManager.RINGER_MODE_VIBRATE); + long silent = db.insert(ProfileColumns.TABLE_NAME, null, cv); + + // Insert the default area. + cv = new ContentValues(); + cv.put(AreaColumns.NAME, mContext.getResources() + .getString(R.string.sql_area_unknown)); + cv.put(AreaColumns.PROFILE_ID, normal); + db.insert(AreaColumns.TABLE_NAME, null, cv); + + // Insert "Home" area. + cv = new ContentValues(); + cv.put(AreaColumns.NAME, mContext.getResources() + .getString(R.string.sql_area_home)); + cv.put(AreaColumns.PROFILE_ID, normal); + db.insert(AreaColumns.TABLE_NAME, null, cv); + + // Insert "Work" area. + cv = new ContentValues(); + cv.put(AreaColumns.NAME, mContext.getResources() + .getString(R.string.sql_area_work)); + cv.put(AreaColumns.PROFILE_ID, silent); + db.insert(AreaColumns.TABLE_NAME, null, cv); + } + + @Override + public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + } + +} diff --git a/src/com/github/nutomic/pegasus/content/ProfileColumns.java b/src/com/github/nutomic/pegasus/content/ProfileColumns.java new file mode 100644 index 0000000..9742856 --- /dev/null +++ b/src/com/github/nutomic/pegasus/content/ProfileColumns.java @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2012 Felix Ableitner + * + * 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.github.nutomic.pegasus.content; + +import android.provider.BaseColumns; + +/** + * Profile table columns. + * + * @author Felix Ableitner + * + */ +public class ProfileColumns implements BaseColumns { + + public static final String TABLE_NAME = "profile"; + + // Columns + public static final String NAME = "name"; + public static final String RINGTONE_VOLUME = "ringtone_volume"; + public static final String NOTIFICATION_VOLUME = "notification_volume"; + public static final String MEDIA_VOLUME = "media_volume"; + public static final String ALARM_VOLUME = "alarm_volume"; + public static final String WIFI_ENABLED = "wifi_enabled"; + public static final String RINGER_MODE = "ringer_mode"; + + + public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + + NAME + " TEXT," + + RINGTONE_VOLUME + " INTEGER," + + NOTIFICATION_VOLUME + " INTEGER," + + MEDIA_VOLUME + " INTEGER," + + ALARM_VOLUME + " INTEGER," + + WIFI_ENABLED + " INTEGER," + + RINGER_MODE + " INTEGER" + + ");"; + +}