Cleaned up code

This commit is contained in:
2012-07-22 09:37:28 -04:00
parent 19b5c13206
commit f06f790b48
37 changed files with 2889 additions and 2692 deletions

View File

@@ -2,8 +2,8 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.TwentyCodes.android.LocationRinger" package="com.TwentyCodes.android.LocationRinger"
android:installLocation="internalOnly" android:installLocation="internalOnly"
android:versionCode="65" android:versionCode="67"
android:versionName="c708c3d" > android:versionName="19b5c13" >
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16"/> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16"/>

View File

@@ -8,10 +8,11 @@ package com.TwentyCodes.android.LocationRinger;
/** /**
* A simple listener to allow fragments to set scrolling enabled * A simple listener to allow fragments to set scrolling enabled
*
* @author ricky * @author ricky
*/ */
public interface EnableScrollingListener { public interface EnableScrollingListener {
public void setScrollEnabled(boolean enabled); public void setScrollEnabled(boolean enabled);
} }

View File

@@ -9,13 +9,15 @@ package com.TwentyCodes.android.LocationRinger;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
/** /**
* This interface will be used to notify * This interface will be used to notify
*
* @author ricky barrette * @author ricky barrette
*/ */
public interface FeatureRemovedListener { public interface FeatureRemovedListener {
/** /**
* Called when a feature is removed from the list * Called when a feature is removed from the list
*
* @author ricky barrette * @author ricky barrette
*/ */
public void onFeatureRemoved(Fragment fragment); public void onFeatureRemoved(Fragment fragment);

View File

@@ -8,16 +8,17 @@ package com.TwentyCodes.android.LocationRinger;
import android.content.ContentValues; import android.content.ContentValues;
/** /**
* This interface will be used to pass the content updated in fragments down to the main FragmentActivity * This interface will be used to pass the content updated in fragments down to
* the main FragmentActivity
*
* @author ricky * @author ricky
*/ */
public interface OnContentChangedListener { public interface OnContentChangedListener {
void onRingerContentChanged(ContentValues ringer);
void onInfoContentChanged(ContentValues info); void onInfoContentChanged(ContentValues info);
void onInfoContentRemoved(String... keys); void onInfoContentRemoved(String... keys);
void onRingerContentChanged(ContentValues ringer);
} }

View File

@@ -7,13 +7,16 @@
package com.TwentyCodes.android.LocationRinger; package com.TwentyCodes.android.LocationRinger;
/** /**
* A simple interface to allow a compent other than an activity to handle a seach event * A simple interface to allow a compent other than an activity to handle a
* seach event
*
* @author ricky barrette * @author ricky barrette
*/ */
public interface SearchRequestedListener { public interface SearchRequestedListener {
/** /**
* Called when the a seach is request via seach button * Called when the a seach is request via seach button
*
* @return * @return
* @author ricky barrette * @author ricky barrette
*/ */

View File

@@ -7,17 +7,19 @@
package com.TwentyCodes.android.LocationRinger.db; package com.TwentyCodes.android.LocationRinger.db;
/** /**
* This interface will be used to listen to see when the database events are complete * This interface will be used to listen to see when the database events are
* complete
*
* @author ricky barrette * @author ricky barrette
*/ */
public interface DatabaseListener { public interface DatabaseListener {
public void onDatabaseUpgradeComplete(); public void onDatabaseUpgrade();
public void onRingerDeletionComplete(); public void onDatabaseUpgradeComplete();
public void onRestoreComplete(); public void onRestoreComplete();
public void onDatabaseUpgrade(); public void onRingerDeletionComplete();
} }

View File

@@ -11,60 +11,63 @@ import android.content.Context;
/** /**
* A convince class containing debugging variables * A convince class containing debugging variables
* @author ricky barrette */ *
* @author ricky barrette
*/
public class Debug { public class Debug {
public static final boolean SUPPORTS_FROYO; public static final boolean SUPPORTS_FROYO;
public static final boolean SUPPORTS_GINGERBREAD; public static final boolean SUPPORTS_GINGERBREAD;
public static final boolean SUPPORTS_HONEYCOMB; public static final boolean SUPPORTS_HONEYCOMB;
public static final int SHARED_PREFS_MODE; public static final int SHARED_PREFS_MODE;
/** /**
* Sets the logging output of this application * Sets the logging output of this application
*/ */
public static final boolean DEBUG = true; public static final boolean DEBUG = true;
/** /**
* The amount of intersecting that is needed between a users accuracy radius and a ringers location radius * The amount of intersecting that is needed between a users accuracy radius
* and a ringers location radius
*/ */
public static final float FUDGE_FACTOR = .002f; public static final float FUDGE_FACTOR = .002f;
/** /**
* Drops the ringer database table every time the database is created * Drops the ringer database table every time the database is created
*/ */
public static boolean DROP_TABLE_EVERY_TIME = false; public static boolean DROP_TABLE_EVERY_TIME = false;
/** /**
* Max radius that can be set by a ringer * Max radius that can be set by a ringer
*/ */
public static final int MAX_RADIUS_IN_METERS = 600; public static final int MAX_RADIUS_IN_METERS = 600;
/** /**
* the update interval in ms * the update interval in ms
*/ */
public static final long UPDATE_INTERVAL = AlarmManager.INTERVAL_FIFTEEN_MINUTES; public static final long UPDATE_INTERVAL = AlarmManager.INTERVAL_FIFTEEN_MINUTES;
/** /**
* minum accracy required to report in meters * minum accracy required to report in meters
*/ */
public static final int ACCURACY = 100; public static final int ACCURACY = 100;
/** /**
* all lolcations with an accuracy greater then this will be ignored. in meters * all lolcations with an accuracy greater then this will be ignored. in
* meters
*/ */
public static final int IGNORE = 500; public static final int IGNORE = 500;
static{ static {
SUPPORTS_FROYO = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO; SUPPORTS_FROYO = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO;
SUPPORTS_GINGERBREAD = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD; SUPPORTS_GINGERBREAD = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD;
SUPPORTS_HONEYCOMB = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB; SUPPORTS_HONEYCOMB = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB;
SHARED_PREFS_MODE = SUPPORTS_HONEYCOMB ? Context.MODE_MULTI_PROCESS : Context.MODE_PRIVATE; SHARED_PREFS_MODE = SUPPORTS_HONEYCOMB ? Context.MODE_MULTI_PROCESS : Context.MODE_PRIVATE;
} }
} }

View File

@@ -21,7 +21,9 @@ import com.TwentyCodes.android.LocationRinger.services.LocationService;
import com.TwentyCodes.android.LocationRinger.ui.SettingsActivity; import com.TwentyCodes.android.LocationRinger.ui.SettingsActivity;
/** /**
* This widget will be used to force a Location update from the users home screen * This widget will be used to force a Location update from the users home
* screen
*
* @author ricky barrette * @author ricky barrette
*/ */
public class GetLocationWidget extends AppWidgetProvider { public class GetLocationWidget extends AppWidgetProvider {
@@ -29,87 +31,101 @@ public class GetLocationWidget extends AppWidgetProvider {
public final String TAG = "GetLocationWidget"; public final String TAG = "GetLocationWidget";
public static final String ACTION_UPDATE = "action_update"; public static final String ACTION_UPDATE = "action_update";
/** /**
* Called in response to the ACTION_APPWIDGET_UPDATE broadcast when this AppWidget provider is being asked to provide RemoteViews for a set of AppWidgets. * Called in response to the ACTION_APPWIDGET_DELETED broadcast when one or
* Override this method to implement your own AppWidget functionality. * more AppWidget instances have been deleted. Override this method to
* @see android.appwidget.AppWidgetProvider#onUpdate(android.content.Context, android.appwidget.AppWidgetManager, int[]) * implement your own AppWidget functionality. (non-Javadoc)
*
* @see android.appwidget.AppWidgetProvider#onDeleted(android.content.Context,
* int[])
* @param context
* @param appWidgetIds
* @author ricky barrette
*/
@Override
public void onDeleted(final Context context, final int[] appWidgetIds) {
if (Debug.DEBUG)
Log.v(TAG, "onDelete()");
super.onDeleted(context, appWidgetIds);
}
/**
* Implements onReceive(Context, Intent) to dispatch calls to the various
* other methods on AppWidgetProvider. (non-Javadoc)
*
* @see android.appwidget.AppWidgetProvider#onReceive(android.content.Context,
* android.content.Intent)
* @param context
* @param intent
* received
* @author ricky barrette
*/
@Override
public void onReceive(final Context context, final Intent intent) {
if (Debug.DEBUG)
Log.v(TAG, "onReceive");
// v1.5 fix that doesn't call onDelete Action
final String action = intent.getAction();
if (action.equals(ACTION_UPDATE)) {
final AppWidgetManager mgr = AppWidgetManager.getInstance(context);
onUpdate(context, mgr, mgr.getAppWidgetIds(new ComponentName(context, GetLocationWidget.class)));
}
if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
final int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID)
onDeleted(context, new int[] { appWidgetId });
}
super.onReceive(context, intent);
}
/**
* Called in response to the ACTION_APPWIDGET_UPDATE broadcast when this
* AppWidget provider is being asked to provide RemoteViews for a set of
* AppWidgets. Override this method to implement your own AppWidget
* functionality.
*
* @see android.appwidget.AppWidgetProvider#onUpdate(android.content.Context,
* android.appwidget.AppWidgetManager, int[])
* @param context * @param context
* @param appWidgetManager * @param appWidgetManager
* @param appWidgetIds * @param appWidgetIds
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { public void onUpdate(final Context context, final AppWidgetManager appWidgetManager, final int[] appWidgetIds) {
if (Debug.DEBUG) if (Debug.DEBUG)
Log.v(TAG, "onUpdate()"); Log.v(TAG, "onUpdate()");
final int N = appWidgetIds.length; final int N = appWidgetIds.length;
// Perform this loop procedure for each App Widget that belongs to this provider // Perform this loop procedure for each App Widget that belongs to this
for (int i=0; i<N; i++) { // provider
int appWidgetId = appWidgetIds[i]; for (int i = 0; i < N; i++) {
final int appWidgetId = appWidgetIds[i];
Intent intent = LocationService.getSingleShotServiceIntent(context);
//create a pending intent to start the post activity
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
// Get the layout for the App Widget and attach an on-click listener to the button
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.get_location_widget);
views.setOnClickPendingIntent(R.id.widget_get_location_button, pendingIntent);
views.setTextViewText(R.id.widget_label, context.getSharedPreferences(SettingsActivity.SETTINGS, Debug.SHARED_PREFS_MODE).getString(SettingsActivity.CURRENT, context.getString(R.string.default_ringer)));
// Tell the AppWidgetManager to perform an update on the current App Widget final Intent intent = LocationService.getSingleShotServiceIntent(context);
appWidgetManager.updateAppWidget(appWidgetId, views);
// create a pending intent to start the post activity
} final PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
// Get the layout for the App Widget and attach an on-click listener
// to the button
final RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.get_location_widget);
views.setOnClickPendingIntent(R.id.widget_get_location_button, pendingIntent);
views.setTextViewText(
R.id.widget_label,
context.getSharedPreferences(SettingsActivity.SETTINGS, Debug.SHARED_PREFS_MODE).getString(SettingsActivity.CURRENT,
context.getString(R.string.default_ringer)));
// Tell the AppWidgetManager to perform an update on the current App
// Widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
super.onUpdate(context, appWidgetManager, appWidgetIds); super.onUpdate(context, appWidgetManager, appWidgetIds);
} }
/**
* Implements onReceive(Context, Intent) to dispatch calls to the various other methods on AppWidgetProvider.
* (non-Javadoc)
* @see android.appwidget.AppWidgetProvider#onReceive(android.content.Context, android.content.Intent)
* @param context
* @param intent received
* @author ricky barrette
*/
@Override
public void onReceive(Context context, Intent intent) {
if (Debug.DEBUG)
Log.v(TAG, "onReceive");
// v1.5 fix that doesn't call onDelete Action
final String action = intent.getAction();
if(action.equals(ACTION_UPDATE)){
AppWidgetManager mgr=AppWidgetManager.getInstance(context);
onUpdate(context, mgr, mgr.getAppWidgetIds(new ComponentName(context, GetLocationWidget.class)));
}
if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
final int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
this.onDeleted(context, new int[] { appWidgetId });
}
}
super.onReceive(context, intent);
}
/**
* Called in response to the ACTION_APPWIDGET_DELETED broadcast when one or more AppWidget instances have been deleted.
* Override this method to implement your own AppWidget functionality.
* (non-Javadoc)
* @see android.appwidget.AppWidgetProvider#onDeleted(android.content.Context, int[])
* @param context
* @param appWidgetIds
* @author ricky barrette
*/
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
if (Debug.DEBUG)
Log.v(TAG, "onDelete()");
super.onDeleted(context, appWidgetIds);
}
} }

View File

@@ -16,7 +16,9 @@ import com.TwentyCodes.android.debug.LocationLibraryConstants;
import com.TwentyCodes.android.location.BaseLocationReceiver; import com.TwentyCodes.android.location.BaseLocationReceiver;
/** /**
* This class will receive broadcast from the location service. it will wake the ringer processing service. * This class will receive broadcast from the location service. it will wake the
* ringer processing service.
*
* @author ricky barrette * @author ricky barrette
*/ */
public class LocationChangedReceiver extends BaseLocationReceiver { public class LocationChangedReceiver extends BaseLocationReceiver {
@@ -24,15 +26,13 @@ public class LocationChangedReceiver extends BaseLocationReceiver {
protected static String TAG = "LocationReceiver"; protected static String TAG = "LocationReceiver";
@Override @Override
public void onLocationUpdate(Location location) { public void onLocationUpdate(final Location location) {
if(location != null) if (location != null)
if(location.getAccuracy()<= Debug.IGNORE) if (location.getAccuracy() <= Debug.IGNORE)
mContext.startService(new Intent(mContext, RingerProcessingService.class).putExtra(LocationLibraryConstants.INTENT_EXTRA_LOCATION_CHANGED, location)); mContext.startService(new Intent(mContext, RingerProcessingService.class).putExtra(LocationLibraryConstants.INTENT_EXTRA_LOCATION_CHANGED, location));
else else if (Debug.DEBUG)
if(Debug.DEBUG) Log.d(TAG, "location accuracy = " + location.getAccuracy() + " ignoring");
Log.d(TAG, "location accuracy = "+ location.getAccuracy()+" ignoring"); else if (Debug.DEBUG)
else
if(Debug.DEBUG)
Log.d(TAG, "location was null"); Log.d(TAG, "location was null");
} }
} }

View File

@@ -8,11 +8,12 @@ package com.TwentyCodes.android.LocationRinger.receivers;
/** /**
* This class will be used to listen for location updates passively. * This class will be used to listen for location updates passively.
*
* @author ricky barrette * @author ricky barrette
*/ */
public class PassiveLocationChangedReceiver extends LocationChangedReceiver { public class PassiveLocationChangedReceiver extends LocationChangedReceiver {
static{ static {
TAG = "PassiveLocationChangedReceiver"; TAG = "PassiveLocationChangedReceiver";
} }

View File

@@ -20,6 +20,7 @@ import com.TwentyCodes.android.location.PassiveLocationListener;
/** /**
* This receiver will system events * This receiver will system events
*
* @author ricky barrette * @author ricky barrette
*/ */
public class SystemReceiver extends BroadcastReceiver { public class SystemReceiver extends BroadcastReceiver {
@@ -29,53 +30,53 @@ public class SystemReceiver extends BroadcastReceiver {
*/ */
private final String BATTERY_LOW = "battery_low"; private final String BATTERY_LOW = "battery_low";
private final String TAG = "SystemEventReciever"; private final String TAG = "SystemEventReciever";
/** /**
* (non-Javadoc) * (non-Javadoc)
* @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent) *
* @see android.content.BroadcastReceiver#onReceive(android.content.Context,
* android.content.Intent)
* @param context * @param context
* @param intent * @param intent
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onReceive(final Context context, final Intent intent) { public void onReceive(final Context context, final Intent intent) {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG, "onReceive() ~"+intent.getAction()); Log.d(TAG, "onReceive() ~" + intent.getAction());
final SharedPreferences systemEventHistory = context.getSharedPreferences(TAG, Debug.SHARED_PREFS_MODE); final SharedPreferences systemEventHistory = context.getSharedPreferences(TAG, Debug.SHARED_PREFS_MODE);
/* /*
* if the phone finishes booting, then start the service if the user enabled it * if the phone finishes booting, then start the service if the user
* enabled it
*/ */
if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){ if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
if(context.getSharedPreferences(SettingsActivity.SETTINGS, Debug.SHARED_PREFS_MODE).getBoolean(SettingsActivity.START_ON_BOOT, false)){ if (context.getSharedPreferences(SettingsActivity.SETTINGS, Debug.SHARED_PREFS_MODE).getBoolean(SettingsActivity.START_ON_BOOT, false)) {
LocationService.startMultiShotService(context); LocationService.startMultiShotService(context);
PassiveLocationListener.requestPassiveLocationUpdates(context, new Intent(context, PassiveLocationChangedReceiver.class)); PassiveLocationListener.requestPassiveLocationUpdates(context, new Intent(context, PassiveLocationChangedReceiver.class));
} }
}
/* /*
* if the battery is reported to be low then * if the battery is reported to be low then stop the service, and
* stop the service, and remove the pending alarm * remove the pending alarm and finally record that the phone's battery
* and finally record that the phone's battery was low in the shared_prefs * was low in the shared_prefs
*/ */
if(intent.getAction().equals(Intent.ACTION_BATTERY_LOW)){ if (intent.getAction().equals(Intent.ACTION_BATTERY_LOW)) {
LocationService.stopService(context).run(); com.TwentyCodes.android.location.LocationService.stopService(context).run();
new Handler().postDelayed(LocationService.stopService(context), 30000L); new Handler().postDelayed(com.TwentyCodes.android.location.LocationService.stopService(context), 30000L);
systemEventHistory.edit().putBoolean(BATTERY_LOW, true).commit(); systemEventHistory.edit().putBoolean(BATTERY_LOW, true).commit();
} }
/* /*
* if the phone is plugged in then * if the phone is plugged in then check to see if the battery was
* check to see if the battery was reported low, if it was then * reported low, if it was then restart the service, and remove
* restart the service, and remove shared_prefs entry * shared_prefs entry
*/ */
if(intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)){ if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED))
if (systemEventHistory.getBoolean(BATTERY_LOW, false)) { if (systemEventHistory.getBoolean(BATTERY_LOW, false)) {
systemEventHistory.edit().remove(BATTERY_LOW).commit(); systemEventHistory.edit().remove(BATTERY_LOW).commit();
LocationService.startMultiShotService(context); LocationService.startMultiShotService(context);
} }
}
} }
} }

View File

@@ -23,97 +23,111 @@ import com.TwentyCodes.android.exception.ExceptionHandler;
/** /**
* We override the location service so we can attach the exception handler * We override the location service so we can attach the exception handler
*
* @author ricky barrette * @author ricky barrette
*/ */
public class LocationService extends com.TwentyCodes.android.location.LocationService { public class LocationService extends com.TwentyCodes.android.location.LocationService {
private final int GATHERING_LOCATION_ONGING_NOTIFICATION_ID = 232903877;
private SharedPreferences mSettings;
private NotificationManager mNotificationManager;
/** /**
* convince method for getting the single shot service intent * convince method for getting the single shot service intent
*
* @param context * @param context
* @return service intent * @return service intent
* @author ricky barrette * @author ricky barrette
*/ */
public static Intent getSingleShotServiceIntent(Context context) { public static Intent getSingleShotServiceIntent(final Context context) {
return new Intent(context, LocationService.class) return new Intent(context, LocationService.class).putExtra(LocationLibraryConstants.INTENT_EXTRA_REQUIRED_ACCURACY, Debug.ACCURACY).setAction(
.putExtra(LocationLibraryConstants.INTENT_EXTRA_REQUIRED_ACCURACY, Debug.ACCURACY) LocationLibraryConstants.INTENT_ACTION_UPDATE);
.setAction(LocationLibraryConstants.INTENT_ACTION_UPDATE);
} }
/* (non-Javadoc) /**
* Starts the location service in multi shot mode
*
* @param context
* @return
* @author ricky barrette
*/
public static ComponentName startMultiShotService(final Context context) {
final Intent i = getSingleShotServiceIntent(context).putExtra(LocationLibraryConstants.INTENT_EXTRA_PERIOD_BETWEEN_UPDATES, Debug.UPDATE_INTERVAL);
return context.startService(i);
}
/**
* starts the service in single shot mode
*
* @param context
* @return
* @author ricky barrette
*/
public static ComponentName startSingleShotService(final Context context) {
return context.startService(getSingleShotServiceIntent(context));
}
private final int GATHERING_LOCATION_ONGING_NOTIFICATION_ID = 232903877;
private SharedPreferences mSettings;
private NotificationManager mNotificationManager;
/*
* (non-Javadoc)
*
* @see com.TwentyCodes.android.SkyHook.SkyHookService#onCreate() * @see com.TwentyCodes.android.SkyHook.SkyHookService#onCreate()
*
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onCreate() { public void onCreate() {
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this)); Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
this.mSettings = this.getSharedPreferences(SettingsActivity.SETTINGS, Debug.SHARED_PREFS_MODE); mSettings = getSharedPreferences(SettingsActivity.SETTINGS, Debug.SHARED_PREFS_MODE);
this.mSettings.edit().putBoolean(SettingsActivity.IS_SERVICE_STARTED, true).commit(); mSettings.edit().putBoolean(SettingsActivity.IS_SERVICE_STARTED, true).commit();
startOnGoingNotification(); startOnGoingNotification();
super.onCreate(); super.onCreate();
} }
/* (non-Javadoc) /*
* (non-Javadoc)
*
* @see com.TwentyCodes.android.SkyHook.SkyHookService#onDestroy() * @see com.TwentyCodes.android.SkyHook.SkyHookService#onDestroy()
*
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onDestroy() { public void onDestroy() {
this.mSettings.edit().remove(SettingsActivity.IS_SERVICE_STARTED).commit(); mSettings.edit().remove(SettingsActivity.IS_SERVICE_STARTED).commit();
this.mNotificationManager.cancel(this.GATHERING_LOCATION_ONGING_NOTIFICATION_ID); mNotificationManager.cancel(GATHERING_LOCATION_ONGING_NOTIFICATION_ID);
super.onDestroy(); super.onDestroy();
} }
/* (non-Javadoc) /*
* @see com.TwentyCodes.android.SkyHook.SkyHookService#onStartCommand(android.content.Intent, int, int) * (non-Javadoc)
*
* @see
* com.TwentyCodes.android.SkyHook.SkyHookService#onStartCommand(android
* .content.Intent, int, int)
*
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(final Intent intent, final int flags, final int startId) {
this.mPeriod = Debug.UPDATE_INTERVAL; mPeriod = Debug.UPDATE_INTERVAL;
return super.onStartCommand(intent, flags, startId); return super.onStartCommand(intent, flags, startId);
} }
/** /**
* Starts the location service in multi shot mode * starts a simple ongoing notification to inform the user that we are
* @param context * gathering location
* @return *
* @author ricky barrette
*/
public static ComponentName startMultiShotService(final Context context){
Intent i = getSingleShotServiceIntent(context).putExtra(LocationLibraryConstants.INTENT_EXTRA_PERIOD_BETWEEN_UPDATES, Debug.UPDATE_INTERVAL);
return context.startService(i);
}
/**
* starts a simple ongoing notification to inform the user that we are gathering location
* @author ricky barrette * @author ricky barrette
*/ */
private void startOnGoingNotification() { private void startOnGoingNotification() {
this.mNotificationManager = (NotificationManager) this.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
final NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
.setContentTitle(getString(R.string.app_name))
.setContentText(this.getString(R.string.gathering))
.setTicker(this.getString(R.string.gathering))
.setSmallIcon(R.drawable.icon)
.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, ListActivity.class), android.content.Intent.FLAG_ACTIVITY_NEW_TASK))
.setWhen(System.currentTimeMillis())
.setOngoing(true);
this.mNotificationManager.notify(this.GATHERING_LOCATION_ONGING_NOTIFICATION_ID, builder.getNotification());
}
/** final NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext()).setContentTitle(getString(R.string.app_name))
* starts the service in single shot mode .setContentText(this.getString(R.string.gathering)).setTicker(this.getString(R.string.gathering)).setSmallIcon(R.drawable.icon)
* @param context .setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, ListActivity.class), android.content.Intent.FLAG_ACTIVITY_NEW_TASK))
* @return .setWhen(System.currentTimeMillis()).setOngoing(true);
* @author ricky barrette
*/ mNotificationManager.notify(GATHERING_LOCATION_ONGING_NOTIFICATION_ID, builder.getNotification());
public static ComponentName startSingleShotService(final Context context){
return context.startService(getSingleShotServiceIntent(context));
} }
} }

View File

@@ -36,6 +36,7 @@ import com.google.android.maps.GeoPoint;
/** /**
* This service will handle processing the users location and the ringers * This service will handle processing the users location and the ringers
*
* @author ricky barrette * @author ricky barrette
*/ */
public class RingerProcessingService extends Service { public class RingerProcessingService extends Service {
@@ -49,70 +50,71 @@ public class RingerProcessingService extends Service {
private SharedPreferences mSettings; private SharedPreferences mSettings;
private WifiManager mWifiManager; private WifiManager mWifiManager;
private BluetoothAdapter mBluetoothAdapter; private BluetoothAdapter mBluetoothAdapter;
/** /**
* Applies a ringers options to the current system settings * Applies a ringers options to the current system settings
*
* @param id * @param id
* @author ricky barrette * @author ricky barrette
*/ */
private void applyRinger(final ContentValues values) { private void applyRinger(final ContentValues values) {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG, "applyRigner()"); Log.d(TAG, "applyRigner()");
final String name = values.getAsString(RingerDatabase.KEY_RINGER_NAME); final String name = values.getAsString(RingerDatabase.KEY_RINGER_NAME);
this.getSharedPreferences(SettingsActivity.SETTINGS, Debug.SHARED_PREFS_MODE).edit().putString(SettingsActivity.CURRENT, name).commit(); getSharedPreferences(SettingsActivity.SETTINGS, Debug.SHARED_PREFS_MODE).edit().putString(SettingsActivity.CURRENT, name).commit();
this.sendBroadcast(new Intent(this, GetLocationWidget.class).setAction(GetLocationWidget.ACTION_UPDATE)); this.sendBroadcast(new Intent(this, GetLocationWidget.class).setAction(GetLocationWidget.ACTION_UPDATE));
/* /*
* ringtone & volume * ringtone & volume
*/ */
if(values.containsKey(RingerDatabase.KEY_RINGTONE_URI)) if (values.containsKey(RingerDatabase.KEY_RINGTONE_URI))
Log.d(TAG, "Ringtone: "+ applyRingtone(RingtoneManager.TYPE_RINGTONE, values.getAsString(RingerDatabase.KEY_RINGTONE_URI))); Log.d(TAG, "Ringtone: " + applyRingtone(RingtoneManager.TYPE_RINGTONE, values.getAsString(RingerDatabase.KEY_RINGTONE_URI)));
if(values.containsKey(RingerDatabase.KEY_RINGTONE_VOLUME)) if (values.containsKey(RingerDatabase.KEY_RINGTONE_VOLUME))
setStreamVolume(values.getAsInteger(RingerDatabase.KEY_RINGTONE_VOLUME), AudioManager.STREAM_RING); setStreamVolume(values.getAsInteger(RingerDatabase.KEY_RINGTONE_VOLUME), AudioManager.STREAM_RING);
/* /*
* notification ringtone & volume * notification ringtone & volume
*/ */
if(values.containsKey(RingerDatabase.KEY_NOTIFICATION_RINGTONE_URI)) if (values.containsKey(RingerDatabase.KEY_NOTIFICATION_RINGTONE_URI))
Log.d(TAG, "Notification Ringtone: "+ applyRingtone(RingtoneManager.TYPE_NOTIFICATION, values.getAsString(RingerDatabase.KEY_NOTIFICATION_RINGTONE_URI))); Log.d(TAG, "Notification Ringtone: " + applyRingtone(RingtoneManager.TYPE_NOTIFICATION, values.getAsString(RingerDatabase.KEY_NOTIFICATION_RINGTONE_URI)));
if(values.containsKey(RingerDatabase.KEY_NOTIFICATION_RINGTONE_VOLUME)) if (values.containsKey(RingerDatabase.KEY_NOTIFICATION_RINGTONE_VOLUME))
setStreamVolume(values.getAsInteger(RingerDatabase.KEY_NOTIFICATION_RINGTONE_VOLUME), AudioManager.STREAM_NOTIFICATION); setStreamVolume(values.getAsInteger(RingerDatabase.KEY_NOTIFICATION_RINGTONE_VOLUME), AudioManager.STREAM_NOTIFICATION);
if(Debug.DEBUG){ if (Debug.DEBUG) {
Log.d(TAG, "Music "+ (mAudioManager.isMusicActive() ? "is playing " : "is not playing")); Log.d(TAG, "Music " + (mAudioManager.isMusicActive() ? "is playing " : "is not playing"));
Log.d(TAG, "Wired Headset "+ (mAudioManager.isWiredHeadsetOn() ? "is on " : "is off")); Log.d(TAG, "Wired Headset " + (mAudioManager.isWiredHeadsetOn() ? "is on " : "is off"));
} }
/* /*
* music volume * music volume we will set the music volume only if music is not
* we will set the music volume only if music is not playing, and there is no wired head set * playing, and there is no wired head set
*/ */
if(values.containsKey(RingerDatabase.KEY_MUSIC_VOLUME)) if (values.containsKey(RingerDatabase.KEY_MUSIC_VOLUME))
if(values.get(RingerDatabase.KEY_MUSIC_VOLUME) != null) if (values.get(RingerDatabase.KEY_MUSIC_VOLUME) != null)
if(! mAudioManager.isMusicActive()) if (!mAudioManager.isMusicActive())
if(! mAudioManager.isWiredHeadsetOn()) if (!mAudioManager.isWiredHeadsetOn())
setStreamVolume(values.getAsInteger(RingerDatabase.KEY_MUSIC_VOLUME), AudioManager.STREAM_MUSIC); setStreamVolume(values.getAsInteger(RingerDatabase.KEY_MUSIC_VOLUME), AudioManager.STREAM_MUSIC);
/* /*
* alarm volume * alarm volume
*/ */
if(values.containsKey(RingerDatabase.KEY_ALARM_VOLUME)) if (values.containsKey(RingerDatabase.KEY_ALARM_VOLUME))
if(values.get(RingerDatabase.KEY_ALARM_VOLUME) != null) if (values.get(RingerDatabase.KEY_ALARM_VOLUME) != null)
setStreamVolume(values.getAsInteger(RingerDatabase.KEY_ALARM_VOLUME), AudioManager.STREAM_ALARM); setStreamVolume(values.getAsInteger(RingerDatabase.KEY_ALARM_VOLUME), AudioManager.STREAM_ALARM);
/* /*
* wifi & bluetooth * wifi & bluetooth
*/ */
if(values.containsKey(RingerDatabase.KEY_WIFI)) if (values.containsKey(RingerDatabase.KEY_WIFI))
if(mWifiManager != null) if (mWifiManager != null)
mWifiManager.setWifiEnabled(RingerDatabase.parseBoolean(values.getAsString(RingerDatabase.KEY_WIFI))); mWifiManager.setWifiEnabled(RingerDatabase.parseBoolean(values.getAsString(RingerDatabase.KEY_WIFI)));
if(values.containsKey(RingerDatabase.KEY_BT)) if (values.containsKey(RingerDatabase.KEY_BT))
if(mBluetoothAdapter != null) if (mBluetoothAdapter != null)
if(RingerDatabase.parseBoolean(values.getAsString(RingerDatabase.KEY_BT))) if (RingerDatabase.parseBoolean(values.getAsString(RingerDatabase.KEY_BT)))
mBluetoothAdapter.enable(); mBluetoothAdapter.enable();
else else
mBluetoothAdapter.disable(); mBluetoothAdapter.disable();
@@ -120,76 +122,86 @@ public class RingerProcessingService extends Service {
/** /**
* Apply the ring tone * Apply the ring tone
* @param stream audio stream to apply to *
* @param isSilent true if silent * @param stream
* @param uri of ringtone, if null silent will be applied * audio stream to apply to
* @param isSilent
* true if silent
* @param uri
* of ringtone, if null silent will be applied
* @return string uri of applied ringtone, null if silent was applied * @return string uri of applied ringtone, null if silent was applied
* @author ricky barrette * @author ricky barrette
*/ */
private String applyRingtone(int type, String uri) { private String applyRingtone(final int type, final String uri) {
RingtoneManager.setActualDefaultRingtoneUri(this, type, uri == null ? null : Uri.parse(uri)); RingtoneManager.setActualDefaultRingtoneUri(this, type, uri == null ? null : Uri.parse(uri));
return uri; return uri;
} }
/** /**
* appends the new ringer's information in content values * appends the new ringer's information in content values
*
* @param id * @param id
* @return * @return
*/ */
private ContentValues getRinger(ContentValues values, long id) { private ContentValues getRinger(final ContentValues values, final long id) {
String name = this.mDb.getRingerName(id); final String name = mDb.getRingerName(id);
values.put(RingerDatabase.KEY_RINGER_NAME, name); values.put(RingerDatabase.KEY_RINGER_NAME, name);
/* /*
* get the ringer's info, and parse it into content values * get the ringer's info, and parse it into content values
*/ */
values.putAll(this.mDb.getRingerInfo(name)); values.putAll(mDb.getRingerInfo(name));
return values; return values;
} }
/** /**
* returns all the ringers information as content values * returns all the ringers information as content values
*
* @param id * @param id
* @return * @return
*/ */
private ContentValues getRinger(long id) { private ContentValues getRinger(final long id) {
return getRinger(new ContentValues(), id); return getRinger(new ContentValues(), id);
} }
/* (non-Javadoc) /*
* (non-Javadoc)
*
* @see android.app.Service#onBind(android.content.Intent) * @see android.app.Service#onBind(android.content.Intent)
*
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public IBinder onBind(Intent intent) { public IBinder onBind(final Intent intent) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return null; return null;
} }
/** /**
* Called when the service is first created * Called when the service is first created
*
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onCreate() { public void onCreate() {
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this)); Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG, "onCreate()"); Log.d(TAG, "onCreate()");
super.onCreate(); super.onCreate();
this.mDb = new RingerDatabase(this); mDb = new RingerDatabase(this);
this.mSettings = this.getSharedPreferences(SettingsActivity.SETTINGS, Debug.SHARED_PREFS_MODE); mSettings = getSharedPreferences(SettingsActivity.SETTINGS, Debug.SHARED_PREFS_MODE);
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
this.mWakeLock = (WakeLock) pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
this.mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
this.mWifiManager = (WifiManager) this.getSystemService(WIFI_SERVICE); mWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
this.mWakeLock.acquire(); mWakeLock.acquire();
} }
@Override @Override
public void onDestroy() { public void onDestroy() {
if(mWakeLock.isHeld()) if (mWakeLock.isHeld())
mWakeLock.release(); mWakeLock.release();
System.gc(); System.gc();
super.onDestroy(); super.onDestroy();
@@ -197,123 +209,130 @@ public class RingerProcessingService extends Service {
/** /**
* Called when the service is first started * Called when the service is first started
*
* @param intent * @param intent
* @param flags * @param flags
* @param startId * @param startId
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(final Intent intent, final int flags, final int startId) {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG, "onStartCommand: "+startId); Log.d(TAG, "onStartCommand: " + startId);
this.mStartId = startId; mStartId = startId;
/* /*
* try to sleep so skyhook doesn't cock block us * try to sleep so skyhook doesn't cock block us
*/ */
try { try {
Thread.sleep(1000l); Thread.sleep(1000l);
} catch (InterruptedException e) { } catch (final InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }
if(intent.getParcelableExtra(LocationLibraryConstants.INTENT_EXTRA_LOCATION_CHANGED) != null){ if (intent.getParcelableExtra(LocationLibraryConstants.INTENT_EXTRA_LOCATION_CHANGED) != null) {
this.mLocation = intent.getParcelableExtra(LocationLibraryConstants.INTENT_EXTRA_LOCATION_CHANGED); mLocation = intent.getParcelableExtra(LocationLibraryConstants.INTENT_EXTRA_LOCATION_CHANGED);
processRingers(); processRingers();
}else if(Debug.DEBUG) } else if (Debug.DEBUG)
Log.d(TAG, "Location was null"); Log.d(TAG, "Location was null");
return super.onStartCommand(intent, flags, startId); return super.onStartCommand(intent, flags, startId);
} }
/** /**
* Processes the ringer database for applicable ringers * Processes the ringer database for applicable ringers
*
* @author ricky barrette * @author ricky barrette
*/ */
private void processRingers() { private void processRingers() {
long index = 1; long index = 1;
boolean isDeafult = true; boolean isDeafult = true;
/* /*
* get the default ringer information * get the default ringer information
*/ */
final ContentValues ringer = getRinger(1); final ContentValues ringer = getRinger(1);
final GeoPoint point = new GeoPoint((int) (mLocation.getLatitude() * 1E6), (int) (mLocation.getLongitude()*1E6)); final GeoPoint point = new GeoPoint((int) (mLocation.getLatitude() * 1E6), (int) (mLocation.getLongitude() * 1E6));
if(Debug.DEBUG){ if (Debug.DEBUG) {
Log.d(TAG, "Processing ringers"); Log.d(TAG, "Processing ringers");
Log.d(TAG, "Current location "+(int) (mLocation.getLatitude() * 1E6)+", "+(int) (mLocation.getLongitude() * 1E6)+" @ "+ Float.valueOf(mLocation.getAccuracy()) / 1000+"km"); Log.d(TAG,
"Current location " + (int) (mLocation.getLatitude() * 1E6) + ", " + (int) (mLocation.getLongitude() * 1E6) + " @ "
+ Float.valueOf(mLocation.getAccuracy()) / 1000 + "km");
} }
final Cursor c = mDb.getAllRingers(); final Cursor c = mDb.getAllRingers();
c.moveToFirst(); c.moveToFirst();
if (c.moveToFirst()) { if (c.moveToFirst())
do { do {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG, "Checking ringer "+c.getString(0)); Log.d(TAG, "Checking ringer " + c.getString(0));
if(RingerDatabase.parseBoolean(c.getString(1))){ if (RingerDatabase.parseBoolean(c.getString(1))) {
final ContentValues info = this.mDb.getRingerInfo(c.getString(0)); final ContentValues info = mDb.getRingerInfo(c.getString(0));
if(info.containsKey(RingerDatabase.KEY_LOCATION) && info.containsKey(RingerDatabase.KEY_RADIUS)){ if (info.containsKey(RingerDatabase.KEY_LOCATION) && info.containsKey(RingerDatabase.KEY_RADIUS)) {
final String[] pointInfo = info.getAsString(RingerDatabase.KEY_LOCATION).split(","); final String[] pointInfo = info.getAsString(RingerDatabase.KEY_LOCATION).split(",");
if(GeoUtils.isIntersecting(point, Float.valueOf(mLocation.getAccuracy()) / 1000, new GeoPoint(Integer.parseInt(pointInfo[0]), Integer.parseInt(pointInfo[1])), Float.valueOf(info.getAsInteger(RingerDatabase.KEY_RADIUS)) / 1000, Debug.FUDGE_FACTOR)){ if (GeoUtils.isIntersecting(point, Float.valueOf(mLocation.getAccuracy()) / 1000,
new GeoPoint(Integer.parseInt(pointInfo[0]), Integer.parseInt(pointInfo[1])),
Float.valueOf(info.getAsInteger(RingerDatabase.KEY_RADIUS)) / 1000, Debug.FUDGE_FACTOR)) {
c.close(); c.close();
getRinger(ringer, index); getRinger(ringer, index);
isDeafult = false; isDeafult = false;
//break loop, we will only apply the first applicable ringer // break loop, we will only apply the first
// applicable ringer
break; break;
} }
} }
} }
index++; index++;
} while (c.moveToNext()); } while (c.moveToNext());
}
c.close(); c.close();
if(Debug.DEBUG) if (Debug.DEBUG)
for(Entry<String,Object> item : ringer.valueSet()) for (final Entry<String, Object> item : ringer.valueSet())
Log.d(TAG, item.getKey()); Log.d(TAG, item.getKey());
applyRinger(ringer); applyRinger(ringer);
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG, "Finished processing ringers"); Log.d(TAG, "Finished processing ringers");
//store is default // store is default
this.mSettings.edit().putBoolean(SettingsActivity.IS_DEFAULT, isDeafult).commit(); mSettings.edit().putBoolean(SettingsActivity.IS_DEFAULT, isDeafult).commit();
this.stopSelf(mStartId); this.stopSelf(mStartId);
} }
/** /**
* set the volume of a particular stream * set the volume of a particular stream
*
* @param volume * @param volume
* @param stream * @param stream
* @author ricky barrette * @author ricky barrette
*/ */
private void setStreamVolume(int volume, int stream) { private void setStreamVolume(final int volume, final int stream) {
/* /*
* if the seek bar is set to a value that is higher than what the the stream value is set for * if the seek bar is set to a value that is higher than what the the
* then subtract the seek bar's value from the current volume of the stream, and then * stream value is set for then subtract the seek bar's value from the
* raise the stream by that many times * current volume of the stream, and then raise the stream by that many
* times
*/ */
if (volume > mAudioManager.getStreamVolume(stream)) { if (volume > mAudioManager.getStreamVolume(stream)) {
int adjust = volume - mAudioManager.getStreamVolume(stream); final int adjust = volume - mAudioManager.getStreamVolume(stream);
for (int i = 0; i < adjust; i++) { for (int i = 0; i < adjust; i++)
mAudioManager.adjustSuggestedStreamVolume(AudioManager.ADJUST_RAISE, stream, 0); mAudioManager.adjustSuggestedStreamVolume(AudioManager.ADJUST_RAISE, stream, 0);
}
} }
/* /*
* if the seek bar is set to a value that is lower than what the the stream value is set for * if the seek bar is set to a value that is lower than what the the
* then subtract the current volume of the stream from the seek bar's value, and then * stream value is set for then subtract the current volume of the
* lower the stream by that many times * stream from the seek bar's value, and then lower the stream by that
* many times
*/ */
if (volume < mAudioManager.getStreamVolume(stream)) { if (volume < mAudioManager.getStreamVolume(stream)) {
int adjust = mAudioManager.getStreamVolume(stream) - volume; final int adjust = mAudioManager.getStreamVolume(stream) - volume;
for (int i = 0; i < adjust; i++) { for (int i = 0; i < adjust; i++)
mAudioManager.adjustSuggestedStreamVolume(AudioManager.ADJUST_LOWER, stream, 0); mAudioManager.adjustSuggestedStreamVolume(AudioManager.ADJUST_LOWER, stream, 0);
} }
}
} }
} }

View File

@@ -29,103 +29,113 @@ import com.TwentyCodes.android.LocationRinger.R;
import com.TwentyCodes.android.LocationRinger.services.LocationService; import com.TwentyCodes.android.LocationRinger.services.LocationService;
/** /**
* This Activity actually handles two stages of a launcher shortcut's life cycle. * This Activity actually handles two stages of a launcher shortcut's life
* cycle.
*
* 1. Your application offers to provide shortcuts to the launcher. When the
* user installs a shortcut, an activity within your application generates the
* actual shortcut and returns it to the launcher, where it is shown to the user
* as an icon.
* *
* 1. Your application offers to provide shortcuts to the launcher. When
* the user installs a shortcut, an activity within your application
* generates the actual shortcut and returns it to the launcher, where it
* is shown to the user as an icon.
*
* 2. Any time the user clicks on an installed shortcut, an intent is sent. * 2. Any time the user clicks on an installed shortcut, an intent is sent.
* Typically this would then be handled as necessary by an activity within * Typically this would then be handled as necessary by an activity within your
* your application. * application.
*
* We handle stage 1 (creating a shortcut) by simply sending back the information (in the form
* of an {@link android.content.Intent} that the launcher will use to create the shortcut.
* *
* You can also implement this in an interactive way, by having your activity actually present * We handle stage 1 (creating a shortcut) by simply sending back the
* UI for the user to select the specific nature of the shortcut, such as a contact, picture, URL, * information (in the form of an {@link android.content.Intent} that the
* media item, or action. * launcher will use to create the shortcut.
* *
* We handle stage 2 (responding to a shortcut) in this sample by simply displaying the contents * You can also implement this in an interactive way, by having your activity
* of the incoming {@link android.content.Intent}. * actually present UI for the user to select the specific nature of the
* shortcut, such as a contact, picture, URL, media item, or action.
* *
* In a real application, you would probably use the shortcut intent to display specific content * We handle stage 2 (responding to a shortcut) in this sample by simply
* or start a particular operation. * displaying the contents of the incoming {@link android.content.Intent}.
*
* In a real application, you would probably use the shortcut intent to display
* specific content or start a particular operation.
*/ */
public class CheckLocationShortcut extends Activity { public class CheckLocationShortcut extends Activity {
@Override @Override
public void onCreate(Bundle icicle) { public void onCreate(final Bundle icicle) {
super.onCreate(icicle); super.onCreate(icicle);
// Resolve the intent // Resolve the intent
final Intent intent = getIntent(); final Intent intent = getIntent();
final String action = intent.getAction(); final String action = intent.getAction();
// If the intent is a request to create a shortcut, we'll do that and exit // If the intent is a request to create a shortcut, we'll do that and
// exit
if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) { if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {
setupShortcut(); setupShortcut();
finish(); finish();
return; return;
} }
/*
* start the location service in single shot mode
*/
LocationService.startSingleShotService(this);
this.finish();
}
/** /*
* This function creates a shortcut and returns it to the caller. There are actually two * start the location service in single shot mode
* intents that you will send back. */
* LocationService.startSingleShotService(this);
* The first intent serves as a container for the shortcut and is returned to the launcher by
* setResult(). This intent must contain three fields:
*
* <ul>
* <li>{@link android.content.Intent#EXTRA_SHORTCUT_INTENT} The shortcut intent.</li>
* <li>{@link android.content.Intent#EXTRA_SHORTCUT_NAME} The text that will be displayed with
* the shortcut.</li>
* <li>{@link android.content.Intent#EXTRA_SHORTCUT_ICON} The shortcut's icon, if provided as a
* bitmap, <i>or</i> {@link android.content.Intent#EXTRA_SHORTCUT_ICON_RESOURCE} if provided as
* a drawable resource.</li>
* </ul>
*
* If you use a simple drawable resource, note that you must wrapper it using
* {@link android.content.Intent.ShortcutIconResource}, as shown below. This is required so
* that the launcher can access resources that are stored in your application's .apk file. If
* you return a bitmap, such as a thumbnail, you can simply put the bitmap into the extras
* bundle using {@link android.content.Intent#EXTRA_SHORTCUT_ICON}.
*
* The shortcut intent can be any intent that you wish the launcher to send, when the user
* clicks on the shortcut. Typically this will be {@link android.content.Intent#ACTION_VIEW}
* with an appropriate Uri for your content, but any Intent will work here as long as it
* triggers the desired action within your Activity.
*/
private void setupShortcut() {
// First, set up the shortcut intent. For this example, we simply create an intent that
// will bring us directly back to this activity. A more typical implementation would use a
// data Uri in order to display a more specific result, or a custom action in order to
// launch a specific operation.
Intent shortcutIntent = new Intent(Intent.ACTION_MAIN); finish();
shortcutIntent.setClassName(this, this.getClass().getName()); }
// Then, set up the container intent (the response to the caller) /**
* This function creates a shortcut and returns it to the caller. There are
* actually two intents that you will send back.
*
* The first intent serves as a container for the shortcut and is returned
* to the launcher by setResult(). This intent must contain three fields:
*
* <ul>
* <li>{@link android.content.Intent#EXTRA_SHORTCUT_INTENT} The shortcut
* intent.</li>
* <li>{@link android.content.Intent#EXTRA_SHORTCUT_NAME} The text that will
* be displayed with the shortcut.</li>
* <li>{@link android.content.Intent#EXTRA_SHORTCUT_ICON} The shortcut's
* icon, if provided as a bitmap, <i>or</i>
* {@link android.content.Intent#EXTRA_SHORTCUT_ICON_RESOURCE} if provided
* as a drawable resource.</li>
* </ul>
*
* If you use a simple drawable resource, note that you must wrapper it
* using {@link android.content.Intent.ShortcutIconResource}, as shown
* below. This is required so that the launcher can access resources that
* are stored in your application's .apk file. If you return a bitmap, such
* as a thumbnail, you can simply put the bitmap into the extras bundle
* using {@link android.content.Intent#EXTRA_SHORTCUT_ICON}.
*
* The shortcut intent can be any intent that you wish the launcher to send,
* when the user clicks on the shortcut. Typically this will be
* {@link android.content.Intent#ACTION_VIEW} with an appropriate Uri for
* your content, but any Intent will work here as long as it triggers the
* desired action within your Activity.
*/
private void setupShortcut() {
// First, set up the shortcut intent. For this example, we simply create
// an intent that
// will bring us directly back to this activity. A more typical
// implementation would use a
// data Uri in order to display a more specific result, or a custom
// action in order to
// launch a specific operation.
Intent intent = new Intent(); final Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); shortcutIntent.setClassName(this, this.getClass().getName());
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.start_location_service));
Parcelable iconResource = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
// Now, return the result to the launcher // Then, set up the container intent (the response to the caller)
setResult(RESULT_OK, intent); final Intent intent = new Intent();
} intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.start_location_service));
final Parcelable iconResource = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
// Now, return the result to the launcher
setResult(RESULT_OK, intent);
}
} }

View File

@@ -6,74 +6,78 @@
*/ */
package com.TwentyCodes.android.LocationRinger.ui; package com.TwentyCodes.android.LocationRinger.ui;
import com.TwentyCodes.android.LocationRinger.R;
import com.TwentyCodes.android.LocationRinger.debug.Debug;
import android.app.Dialog; import android.app.Dialog;
import android.content.Context; import android.content.Context;
import android.view.View; import android.view.View;
import android.view.Window; import android.view.Window;
import com.TwentyCodes.android.LocationRinger.R;
import com.TwentyCodes.android.LocationRinger.debug.Debug;
/** /**
* This class will be used to display the first boot dialog * This class will be used to display the first boot dialog
*
* @author ricky barrette * @author ricky barrette
*/ */
public class FirstBootDialog extends Dialog implements android.view.View.OnClickListener { public class FirstBootDialog extends Dialog implements android.view.View.OnClickListener {
/** /**
* Creates a new FirstBootDialog * Creates a new FirstBootDialog
*
* @param context * @param context
* @author ricky barrette * @author ricky barrette
*/ */
public FirstBootDialog(Context context) { public FirstBootDialog(final Context context) {
super(context); super(context);
build(context); build(context);
} }
/**
* Creates a new FirstBootDialog
* @param context
* @param theme
* @author ricky barrette
*/
public FirstBootDialog(Context context, int theme) {
super(context, theme);
build(context);
}
/** /**
* Creates a new FirstBootDialog * Creates a new FirstBootDialog
*
* @param context * @param context
* @param cancelable * @param cancelable
* @param cancelListener * @param cancelListener
* @author ricky barrette * @author ricky barrette
*/ */
public FirstBootDialog(Context context, boolean cancelable, OnCancelListener cancelListener) { public FirstBootDialog(final Context context, final boolean cancelable, final OnCancelListener cancelListener) {
super(context, cancelable, cancelListener); super(context, cancelable, cancelListener);
build(context); build(context);
} }
/**
* Creates a new FirstBootDialog
*
* @param context
* @param theme
* @author ricky barrette
*/
public FirstBootDialog(final Context context, final int theme) {
super(context, theme);
build(context);
}
/** /**
* Builds the dialog * Builds the dialog
*
* @param context * @param context
* @author ricky barrette * @author ricky barrette
*/ */
private void build(Context context) { private void build(final Context context) {
this.requestWindowFeature(Window.FEATURE_LEFT_ICON); requestWindowFeature(Window.FEATURE_LEFT_ICON);
this.setContentView(R.layout.first_boot_dialog); this.setContentView(R.layout.first_boot_dialog);
this.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.icon); setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.icon);
this.setTitle(R.string.welcome); this.setTitle(R.string.welcome);
this.findViewById(R.id.ok_button).setOnClickListener(this); findViewById(R.id.ok_button).setOnClickListener(this);
} }
/** /**
* called when the ok button is clicked * called when the ok button is clicked
*/ */
@Override @Override
public void onClick(View arg0) { public void onClick(final View arg0) {
this.getContext().getSharedPreferences(SettingsActivity.SETTINGS, Debug.SHARED_PREFS_MODE).edit().putBoolean(SettingsActivity.IS_FIRST_BOOT, false).commit(); getContext().getSharedPreferences(SettingsActivity.SETTINGS, Debug.SHARED_PREFS_MODE).edit().putBoolean(SettingsActivity.IS_FIRST_BOOT, false).commit();
this.dismiss(); dismiss();
} }
} }

View File

@@ -45,13 +45,13 @@ import com.skyhookwireless.wps.WPSReturnCode;
@SuppressLint("Registered") @SuppressLint("Registered")
public class ListActivity extends Activity implements OnItemClickListener, OnClickListener, DatabaseListener, RegistrationCallback { public class ListActivity extends Activity implements OnItemClickListener, OnClickListener, DatabaseListener, RegistrationCallback {
private RingerDatabase mDb; private RingerDatabase mDb;
private ListView mListView; private ListView mListView;
private SharedPreferences mSettings; private SharedPreferences mSettings;
private ProgressDialog mProgress; private ProgressDialog mProgress;
private Dialog mSplashDialog; private Dialog mSplashDialog;
public static final String NO_SPLASH = "no splash"; public static final String NO_SPLASH = "no splash";
public static final String KEY_RINGER = "key_ringer"; public static final String KEY_RINGER = "key_ringer";
public static final String KEY_INFO = "key_info"; public static final String KEY_INFO = "key_info";
@@ -60,58 +60,60 @@ public class ListActivity extends Activity implements OnItemClickListener, OnCli
private static final int ACTIVITY_EDIT = 4; private static final int ACTIVITY_EDIT = 4;
private static final String KEY_ROWID = "key_row_id"; private static final String KEY_ROWID = "key_row_id";
public static final String ACTION_NEW_RINGER = "action_new_ringer"; public static final String ACTION_NEW_RINGER = "action_new_ringer";
@Override @Override
public void done() { public void done() {
} }
@Override @Override
public WPSContinuation handleError(WPSReturnCode arg0) { public WPSContinuation handleError(final WPSReturnCode arg0) {
Toast.makeText(this, R.string.skyhook_error_registration, Toast.LENGTH_SHORT).show(); Toast.makeText(this, R.string.skyhook_error_registration, Toast.LENGTH_SHORT).show();
return WPSContinuation.WPS_CONTINUE; return WPSContinuation.WPS_CONTINUE;
} }
@Override @Override
public void handleSuccess() { public void handleSuccess() {
Toast.makeText(this, R.string.registered, Toast.LENGTH_SHORT).show(); Toast.makeText(this, R.string.registered, Toast.LENGTH_SHORT).show();
this.mSettings.edit().putBoolean(SettingsActivity.IS_REGISTERED, true).commit(); mSettings.edit().putBoolean(SettingsActivity.IS_REGISTERED, true).commit();
} }
/** /**
* called when the note edit activity finishes * called when the note edit activity finishes (non-Javadoc)
* (non-Javadoc) *
* @see android.app.Activity#onActivityResult(int, int, android.content.Intent) * @see android.app.Activity#onActivityResult(int, int,
* android.content.Intent)
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) { public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) {
super.onActivityResult(requestCode, resultCode, intent); super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK){ if (resultCode == RESULT_OK) {
final ProgressDialog progress = ProgressDialog.show(this, "", this.getText(R.string.saving), true, true); final ProgressDialog progress = ProgressDialog.show(this, "", getText(R.string.saving), true, true);
new Thread(new Runnable() { new Thread(new Runnable() {
@Override @Override
public void run() { public void run() {
switch (requestCode) { switch (requestCode) {
case ACTIVITY_CREATE: case ACTIVITY_CREATE:
ContentValues ringer = (ContentValues) intent.getParcelableExtra(KEY_RINGER); final ContentValues ringer = (ContentValues) intent.getParcelableExtra(KEY_RINGER);
mDb.insertRinger(ringer, (ContentValues) intent.getParcelableExtra(KEY_INFO)); mDb.insertRinger(ringer, (ContentValues) intent.getParcelableExtra(KEY_INFO));
break; break;
case ACTIVITY_EDIT: case ACTIVITY_EDIT:
mDb.updateRinger(intent.getLongExtra(KEY_ROWID, 1), (ContentValues) intent.getParcelableExtra(KEY_RINGER), (ContentValues) intent.getParcelableExtra(KEY_INFO)); mDb.updateRinger(intent.getLongExtra(KEY_ROWID, 1), (ContentValues) intent.getParcelableExtra(KEY_RINGER),
(ContentValues) intent.getParcelableExtra(KEY_INFO));
break; break;
} }
final String action = ListActivity.this.getIntent().getAction(); final String action = ListActivity.this.getIntent().getAction();
if(action != null) if (action != null)
if(action.equals(ACTION_NEW_RINGER)) if (action.equals(ACTION_NEW_RINGER))
finish(); finish();
else else
ListActivity.this.mListView.post(new Runnable(){ mListView.post(new Runnable() {
@Override @Override
public void run(){ public void run() {
progress.dismiss(); progress.dismiss();
populate(); populate();
} }
@@ -120,131 +122,140 @@ public class ListActivity extends Activity implements OnItemClickListener, OnCli
}).start(); }).start();
} else { } else {
final String action = ListActivity.this.getIntent().getAction(); final String action = ListActivity.this.getIntent().getAction();
if(action != null) if (action != null)
if(action.equals(ACTION_NEW_RINGER)) if (action.equals(ACTION_NEW_RINGER))
finish(); finish();
} }
} }
@Override @Override
public void onClick(View v) { public void onClick(final View v) {
Intent i = new Intent(this, RingerInformationActivity.class); final Intent i = new Intent(this, RingerInformationActivity.class);
startActivityForResult(i, ACTIVITY_CREATE); startActivityForResult(i, ACTIVITY_CREATE);
} }
/** /**
* called when the context menu item has been selected * called when the context menu item has been selected (non-Javadoc)
* (non-Javadoc) *
* @see android.app.Activity#onContextItemSelected(android.view.MenuItem) * @see android.app.Activity#onContextItemSelected(android.view.MenuItem)
* @author ricky barrette * @author ricky barrette
*/ */
public boolean onContextItemSelected(MenuItem item) { @Override
switch(item.getItemId()) { public boolean onContextItemSelected(final MenuItem item) {
case R.id.delete: switch (item.getItemId()) {
final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); case R.id.delete:
if(info.id == 0) final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
Toast.makeText(this, this.getString(R.string.cant_delete_default), Toast.LENGTH_SHORT).show(); if (info.id == 0)
else Toast.makeText(this, this.getString(R.string.cant_delete_default), Toast.LENGTH_SHORT).show();
mDb.deleteRinger(info.id +1); else
return true; mDb.deleteRinger(info.id + 1);
} return true;
return super.onContextItemSelected(item); }
} return super.onContextItemSelected(item);
}
/** /**
* Called when the activity is first created. * Called when the activity is first created.
*/ */
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
final Intent intent = getIntent(); final Intent intent = getIntent();
final String action = intent.getAction(); final String action = intent.getAction();
// If the intent is a request to create a shortcut, we'll do that and exit // If the intent is a request to create a shortcut, we'll do that and
// exit
if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) { if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {
setupShortcut(); setupShortcut();
finish(); finish();
return; return;
} }
setContentView(R.layout.ringer_list); setContentView(R.layout.ringer_list);
this.setTitle(R.string.app_name); this.setTitle(R.string.app_name);
this.mDb = new RingerDatabase(this, this); mDb = new RingerDatabase(this, this);
this.mListView = (ListView) findViewById(R.id.ringer_list); mListView = (ListView) findViewById(R.id.ringer_list);
this.mListView.setOnItemClickListener(this); mListView.setOnItemClickListener(this);
this.mListView.setOnCreateContextMenuListener(this); mListView.setOnCreateContextMenuListener(this);
this.mListView.setEmptyView(findViewById(android.R.id.empty)); mListView.setEmptyView(findViewById(android.R.id.empty));
findViewById(R.id.add_ringer_button).setOnClickListener(this); findViewById(R.id.add_ringer_button).setOnClickListener(this);
populate(); populate();
this.mSettings = this.getSharedPreferences(SettingsActivity.SETTINGS, Debug.SHARED_PREFS_MODE); mSettings = getSharedPreferences(SettingsActivity.SETTINGS, Debug.SHARED_PREFS_MODE);
if(this.mSettings.getBoolean(SettingsActivity.IS_FIRST_BOOT, true)) if (mSettings.getBoolean(SettingsActivity.IS_FIRST_BOOT, true))
new FirstBootDialog(this).show(); new FirstBootDialog(this).show();
if(! this.mSettings.getBoolean(SettingsActivity.IS_REGISTERED, false)){ if (!mSettings.getBoolean(SettingsActivity.IS_REGISTERED, false))
new SkyHookRegistration(this).registerNewUser(this); new SkyHookRegistration(this).registerNewUser(this);
}
// if(!this.getIntent().hasExtra(NO_SPLASH))
// if(!this.getIntent().hasExtra(NO_SPLASH)) // showSplashScreen();
// showSplashScreen();
if (action != null)
if(action != null) if (action.equals(ACTION_NEW_RINGER))
if(action.equals(ACTION_NEW_RINGER)) startActivityForResult(new Intent(this, RingerInformationActivity.class), ACTIVITY_CREATE);
startActivityForResult(new Intent(this, RingerInformationActivity.class), ACTIVITY_CREATE); }
}
/**
* called when the activity is first created, creates a context menu
* @param menu
* @param v
* @param menuInfo
* @return
* @author ricky barrette
*/
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.ringer_list_context_menu, menu);
}
/** /**
* called when the activity is first created, creates options menu * called when the activity is first created, creates a context menu
* (non-Javadoc) *
* @see android.app.Activity#onCreateOptionsMenu(android.view.Menu) * @param menu
* @author ricky barrette * @param v
*/ * @param menuInfo
@Override * @return
public boolean onCreateOptionsMenu (Menu menu) { * @author ricky barrette
final MenuInflater inflater = getMenuInflater(); */
inflater.inflate(R.menu.ringer_list_menu, menu); @Override
return super.onCreateOptionsMenu(menu); public void onCreateContextMenu(final ContextMenu menu, final View v, final ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
} final MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.ringer_list_context_menu, menu);
/**
* Called when a database is being upgraded
* @author ricky barrette
*/
@Override
public void onDatabaseUpgrade() {
this.mProgress = ProgressDialog.show(this, "", this.getText(R.string.upgrading), true, true);
} }
/** /**
* called when a database upgrade is finished * called when the activity is first created, creates options menu
* @author ricky barrette * (non-Javadoc)
*/ *
* @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
* @author ricky barrette
*/
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
final MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.ringer_list_menu, menu);
return super.onCreateOptionsMenu(menu);
}
/**
* Called when a database is being upgraded
*
* @author ricky barrette
*/
@Override
public void onDatabaseUpgrade() {
mProgress = ProgressDialog.show(this, "", getText(R.string.upgrading), true, true);
}
/**
* called when a database upgrade is finished
*
* @author ricky barrette
*/
@Override @Override
public void onDatabaseUpgradeComplete() { public void onDatabaseUpgradeComplete() {
populate(); populate();
if(this.mProgress != null) if (mProgress != null)
this.mProgress.dismiss(); mProgress.dismiss();
} }
/* (non-Javadoc) /*
* (non-Javadoc)
*
* @see android.app.Activity#onDestroy() * @see android.app.Activity#onDestroy()
*
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
@@ -253,87 +264,88 @@ public class ListActivity extends Activity implements OnItemClickListener, OnCli
PassiveLocationListener.requestPassiveLocationUpdates(this, new Intent(this, PassiveLocationChangedReceiver.class)); PassiveLocationListener.requestPassiveLocationUpdates(this, new Intent(this, PassiveLocationChangedReceiver.class));
super.onDestroy(); super.onDestroy();
} }
/** /**
* called when an item in the list view has been clicked, * called when an item in the list view has been clicked, this will open the
* this will open the note edit dialog for the selected note * note edit dialog for the selected note (non-Javadoc)
* (non-Javadoc) *
* @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long) * @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView,
* @author ricky barrette * android.view.View, int, long)
*/ * @author ricky barrette
@Override */
public void onItemClick(AdapterView<?> arg0, View v, int postion, final long id) { @Override
public void onItemClick(final AdapterView<?> arg0, final View v, final int postion, final long id) {
final ProgressDialog progress = ProgressDialog.show(this, "", this.getText(R.string.loading), true, true);
final ProgressDialog progress = ProgressDialog.show(this, "", getText(R.string.loading), true, true);
//post to social sites in a new thread to prevent ANRs
new Thread( new Runnable(){ // post to social sites in a new thread to prevent ANRs
@Override new Thread(new Runnable() {
public void run(){ @Override
Looper.prepare(); public void run() {
Looper.prepare();
final Intent i = new Intent(ListActivity.this, RingerInformationActivity.class).putExtra(KEY_ROWID, id+1);
final Intent i = new Intent(ListActivity.this, RingerInformationActivity.class).putExtra(KEY_ROWID, id + 1);
/*
* get the ringer /*
*/ * get the ringer
final Cursor ringer = mDb.getRingerFromId(id+1); */
if (ringer.moveToFirst()){ final Cursor ringer = mDb.getRingerFromId(id + 1);
ContentValues r = new ContentValues(); if (ringer.moveToFirst()) {
r.put(RingerDatabase.KEY_RINGER_NAME, ringer.getString(0)); final ContentValues r = new ContentValues();
r.put(RingerDatabase.KEY_IS_ENABLED, RingerDatabase.parseBoolean(ringer.getString(1))); r.put(RingerDatabase.KEY_RINGER_NAME, ringer.getString(0));
i.putExtra(KEY_RINGER, r); r.put(RingerDatabase.KEY_IS_ENABLED, RingerDatabase.parseBoolean(ringer.getString(1)));
i.putExtra(KEY_RINGER, r);
if (ringer != null && !ringer.isClosed()) {
if (ringer != null && !ringer.isClosed())
ringer.close(); ringer.close();
}
if (id == 0)
if(id == 0)
i.putExtra(KEY_IS_DEFAULT, true); i.putExtra(KEY_IS_DEFAULT, true);
/* /*
* get the ringer's info, and parse it into content values * get the ringer's info, and parse it into content values
*/ */
i.putExtra(KEY_INFO, mDb.getRingerInfo(r.getAsString(RingerDatabase.KEY_RINGER_NAME))); i.putExtra(KEY_INFO, mDb.getRingerInfo(r.getAsString(RingerDatabase.KEY_RINGER_NAME)));
} }
progress.dismiss(); progress.dismiss();
//start the ringer info activity in editor mode
startActivityForResult(i, ACTIVITY_EDIT);
} // start the ringer info activity in editor mode
}).start(); startActivityForResult(i, ACTIVITY_EDIT);
}
}).start();
} }
/**
* called when an option is selected form the menu
* (non-Javadoc)
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
* @author ricky barrette
*/
@Override
public boolean onOptionsItemSelected (MenuItem item) {
switch (item.getItemId()){
case R.id.settings:
startActivity(new Intent(this, SettingsActivity.class));
return true;
case R.id.backup:
mDb.backup();
SettingsActivity.backup(this);
break;
case R.id.restore:
mDb.restore();
SettingsActivity.restore(this);
break;
}
return super.onOptionsItemSelected(item);
}
/** /**
* called when an option is selected form the menu (non-Javadoc)
*
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
* @author ricky barrette
*/
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
startActivity(new Intent(this, SettingsActivity.class));
return true;
case R.id.backup:
mDb.backup();
SettingsActivity.backup(this);
break;
case R.id.restore:
mDb.restore();
SettingsActivity.restore(this);
break;
}
return super.onOptionsItemSelected(item);
}
/**
* (non-Javadoc) * (non-Javadoc)
*
* @see android.app.Activity#onPause() * @see android.app.Activity#onPause()
*/ */
@Override @Override
@@ -343,11 +355,11 @@ public class ListActivity extends Activity implements OnItemClickListener, OnCli
} }
/** /**
* Called when the database is restored * Called when the database is restored
*/ */
@Override @Override
public void onRestoreComplete() { public void onRestoreComplete() {
populate(); populate();
} }
/** /**
@@ -355,85 +367,89 @@ public class ListActivity extends Activity implements OnItemClickListener, OnCli
*/ */
@Override @Override
public void onRingerDeletionComplete() { public void onRingerDeletionComplete() {
populate(); populate();
} }
/** /**
* populates the list view from the data base * populates the list view from the data base
*
* @author ricky barrette * @author ricky barrette
*/ */
private void populate() { private void populate() {
findViewById(R.id.add_ringer_button_hint).setVisibility(this.mDb.getAllRingerTitles().size() > 1 ? View.GONE : View.VISIBLE); findViewById(R.id.add_ringer_button_hint).setVisibility(mDb.getAllRingerTitles().size() > 1 ? View.GONE : View.VISIBLE);
mListView.setAdapter(new RingerListAdapter(this, mDb)); mListView.setAdapter(new RingerListAdapter(this, mDb));
} }
/** /**
* Removes the Dialog that displays the splash screen * Removes the Dialog that displays the splash screen
*/ */
protected void removeSplashScreen() { protected void removeSplashScreen() {
if (mSplashDialog != null) { if (mSplashDialog != null) {
mSplashDialog.dismiss(); mSplashDialog.dismiss();
mSplashDialog = null; mSplashDialog = null;
} }
} }
/** /**
* Restarts the service if its not already running. * Restarts the service if its not already running.
* @author ricky barrette *
*/ * @author ricky barrette
private void restartService() { */
final SharedPreferences sharedPrefs = this.getSharedPreferences(SettingsActivity.SETTINGS, Debug.SHARED_PREFS_MODE); private void restartService() {
if(! sharedPrefs.getBoolean(SettingsActivity.IS_SERVICE_STARTED, false)){ final SharedPreferences sharedPrefs = getSharedPreferences(SettingsActivity.SETTINGS, Debug.SHARED_PREFS_MODE);
if (!sharedPrefs.getBoolean(SettingsActivity.IS_SERVICE_STARTED, false)) {
// cancel the previous service // cancel the previous service
LocationService.stopService(this).run(); com.TwentyCodes.android.location.LocationService.stopService(this).run();
//start the new service // start the new service
LocationService.startMultiShotService(this); LocationService.startMultiShotService(this);
} }
} }
/** /**
* Creates a shortcut for the launcher * Creates a shortcut for the launcher
*
* @author ricky barrette * @author ricky barrette
*/ */
private void setupShortcut() { private void setupShortcut() {
Intent shortcutIntent = new Intent(this, this.getClass()); final Intent shortcutIntent = new Intent(this, this.getClass());
shortcutIntent.setAction(ACTION_NEW_RINGER); shortcutIntent.setAction(ACTION_NEW_RINGER);
//set up the container intent and return to the launcher // set up the container intent and return to the launcher
Intent intent = new Intent(); final Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.new_ringer)); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.new_ringer));
Parcelable iconResource = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon); final Parcelable iconResource = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource); intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
setResult(RESULT_OK, intent); setResult(RESULT_OK, intent);
} }
// /** // /**
// * Shows the splash screen over the full Activity // * Shows the splash screen over the full Activity
// */ // */
// protected void showSplashScreen() { // protected void showSplashScreen() {
//// mMap.setGPSDialogEnabled(false); // // mMap.setGPSDialogEnabled(false);
// mSplashDialog = new Dialog(this, android.R.style.Theme_Translucent); // mSplashDialog = new Dialog(this, android.R.style.Theme_Translucent);
// mSplashDialog.setContentView(R.layout.powered_by_skyhook); // mSplashDialog.setContentView(R.layout.powered_by_skyhook);
// mSplashDialog.setCancelable(false); // mSplashDialog.setCancelable(false);
// mSplashDialog.show(); // mSplashDialog.show();
// //
// // Set Runnable to remove splash screen just in case // // Set Runnable to remove splash screen just in case
// final Handler handler = new Handler(); // final Handler handler = new Handler();
// handler.postDelayed(new Runnable() { // handler.postDelayed(new Runnable() {
// @Override // @Override
// public void run() { // public void run() {
// removeSplashScreen(); // removeSplashScreen();
// //
// /* // /*
// * uncomment the following to display the eula // * uncomment the following to display the eula
// */ // */
//// //loads first boot dialog if this is the first boot // // //loads first boot dialog if this is the first boot
//// if (! mSettings.getBoolean(Settings.ACCEPTED, false) || Debug.FORCE_FIRSTBOOT_DIALOG) // // if (! mSettings.getBoolean(Settings.ACCEPTED, false) ||
//// eulaAlert(); // Debug.FORCE_FIRSTBOOT_DIALOG)
//// else // // eulaAlert();
//// update(); // // else
// } // // update();
// }, 2000); // }
// } // }, 2000);
// }
} }

View File

@@ -40,9 +40,10 @@ import com.jakewharton.android.viewpagerindicator.TitledFragmentAdapter;
/** /**
* This activity will handle displaying ringer options * This activity will handle displaying ringer options
*
* @author ricky * @author ricky
*/ */
public class RingerInformationActivity extends FragmentActivity implements OnContentChangedListener, EnableScrollingListener, OnPageChangeListener{ public class RingerInformationActivity extends FragmentActivity implements OnContentChangedListener, EnableScrollingListener, OnPageChangeListener {
private static final String TAG = "RingerInformationActivity"; private static final String TAG = "RingerInformationActivity";
private ContentValues mRinger; private ContentValues mRinger;
@@ -53,217 +54,228 @@ public class RingerInformationActivity extends FragmentActivity implements OnCon
/** /**
* Logs the content values * Logs the content values
*
* @param values * @param values
* @author ricky barrette * @author ricky barrette
*/ */
private void logContentValues(ContentValues values) { private void logContentValues(final ContentValues values) {
for(Entry<String,Object> item : values.valueSet()) for (final Entry<String, Object> item : values.valueSet())
Log.d(TAG, item.getKey() +" = "+ item.getValue()); Log.d(TAG, item.getKey() + " = " + item.getValue());
} }
/** /**
* Called when the activity is first created * Called when the activity is first created (non-Javadoc)
* (non-Javadoc) *
* @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle) * @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
*/ */
@SuppressLint("NewApi") @SuppressLint("NewApi")
@Override @Override
protected void onCreate(Bundle arg0) { protected void onCreate(final Bundle arg0) {
super.onCreate(arg0); super.onCreate(arg0);
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this)); Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
final Intent intent = getIntent(); final Intent intent = getIntent();
setContentView(R.layout.ringer_information_activity); setContentView(R.layout.ringer_information_activity);
/* /*
* Set up the action bar if required * Set up the action bar if required
*/ */
if(Debug.SUPPORTS_HONEYCOMB) if (Debug.SUPPORTS_HONEYCOMB)
getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setDisplayHomeAsUpEnabled(true);
this.mData = new Intent().putExtras(intent);
this.mRinger = this.mData.getParcelableExtra(ListActivity.KEY_RINGER);
this.mInfo = this.mData.getParcelableExtra(ListActivity.KEY_INFO);
if(this.mRinger == null) mData = new Intent().putExtras(intent);
this.mRinger = new ContentValues();
if(this.mInfo == null) mRinger = mData.getParcelableExtra(ListActivity.KEY_RINGER);
this.mInfo = new ContentValues(); mInfo = mData.getParcelableExtra(ListActivity.KEY_INFO);
if (mRinger == null)
mRinger = new ContentValues();
if (mInfo == null)
mInfo = new ContentValues();
/* /*
* set the title * set the title
*/ */
this.setTitle(this.mRinger.containsKey(RingerDatabase.KEY_RINGER_NAME) ?this.getString(R.string.editing)+" "+this.mRinger.getAsString(RingerDatabase.KEY_RINGER_NAME) this.setTitle(mRinger.containsKey(RingerDatabase.KEY_RINGER_NAME) ? this.getString(R.string.editing) + " " + mRinger.getAsString(RingerDatabase.KEY_RINGER_NAME)
: getString(R.string.new_ringer)); : getString(R.string.new_ringer));
boolean isDefault = getString(R.string.default_ringer).equals(this.mRinger.getAsString(RingerDatabase.KEY_RINGER_NAME)); final boolean isDefault = getString(R.string.default_ringer).equals(mRinger.getAsString(RingerDatabase.KEY_RINGER_NAME));
/* /*
* Page titles * Page titles
*/ */
String[] titles = this.getResources().getStringArray(isDefault ? R.array.ringer_info_titles_default : R.array.ringer_info_titles); final String[] titles = getResources().getStringArray(isDefault ? R.array.ringer_info_titles_default : R.array.ringer_info_titles);
ArrayList<Fragment> fragments = new ArrayList<Fragment>(); final ArrayList<Fragment> fragments = new ArrayList<Fragment>();
/* /*
* about page * about page
*/ */
if(!isDefault) if (!isDefault)
fragments.add(new AboutRingerFragment(this.mRinger, this.mInfo, this)); fragments.add(new AboutRingerFragment(mRinger, mInfo, this));
/* /*
* Location page * Location page
*/ */
if(!isDefault){ if (!isDefault) {
this.mLocationInfomationFragment = new LocationInfomationFragment(this.mInfo, this, this); mLocationInfomationFragment = new LocationInfomationFragment(mInfo, this, this);
fragments.add(this.mLocationInfomationFragment); fragments.add(mLocationInfomationFragment);
} }
fragments.add(new FeatureListFragment(this.mInfo, this)); fragments.add(new FeatureListFragment(mInfo, this));
//Populate the pager // Populate the pager
this.mPager = (ViewPager)findViewById(R.id.pager); mPager = (ViewPager) findViewById(R.id.pager);
if(this.mPager != null) if (mPager != null)
this.mPager.setAdapter(new TitledFragmentAdapter(this.getSupportFragmentManager(), fragments, titles)); mPager.setAdapter(new TitledFragmentAdapter(getSupportFragmentManager(), fragments, titles));
//populate the pager's indicator // populate the pager's indicator
TitlePageIndicator indicator = (TitlePageIndicator)findViewById(R.id.indicator); final TitlePageIndicator indicator = (TitlePageIndicator) findViewById(R.id.indicator);
if(indicator != null) if (indicator != null)
indicator.setViewPager(this.mPager); indicator.setViewPager(mPager);
indicator.setOnPageChangeListener(this); indicator.setOnPageChangeListener(this);
} }
/** /**
* Creates the main menu that is displayed when the menu button is clicked * Creates the main menu that is displayed when the menu button is clicked
*
* @author ricky barrette * @author ricky barrette
*/ */
public boolean onCreateOptionsMenu(Menu menu) { @Override
MenuInflater inflater = getMenuInflater(); public boolean onCreateOptionsMenu(final Menu menu) {
inflater.inflate(R.menu.ringer_info_menu, menu); final MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.ringer_info_menu, menu);
return super.onCreateOptionsMenu(menu); return super.onCreateOptionsMenu(menu);
} }
/** /**
* Called when the ringer info has changed * Called when the ringer info has changed (non-Javadoc)
* (non-Javadoc) *
* @see com.TwentyCodes.android.LocationRinger.OnContentChangedListener#onInfoContentChanged(android.content.ContentValues) * @see com.TwentyCodes.android.LocationRinger.OnContentChangedListener#onInfoContentChanged(android.content.ContentValues)
*/ */
@Override @Override
public void onInfoContentChanged(ContentValues values) { public void onInfoContentChanged(final ContentValues values) {
if(Debug.DEBUG){ if (Debug.DEBUG) {
Log.v(TAG,"onInfoContentChanged()"); Log.v(TAG, "onInfoContentChanged()");
logContentValues(values); logContentValues(values);
} }
this.mInfo.putAll(values); mInfo.putAll(values);
} }
/** /**
* Called when a feature is removed * Called when a feature is removed (non-Javadoc)
* (non-Javadoc) *
* @see com.TwentyCodes.android.LocationRinger.OnContentChangedListener#onInfoContentRemoved(java.lang.String[]) * @see com.TwentyCodes.android.LocationRinger.OnContentChangedListener#onInfoContentRemoved(java.lang.String[])
*/ */
@Override @Override
public void onInfoContentRemoved(String... keys) { public void onInfoContentRemoved(final String... keys) {
for(String key : keys) for (final String key : keys)
if(this.mInfo.containsKey(key)) if (mInfo.containsKey(key))
this.mInfo.remove(key); mInfo.remove(key);
} }
/* (non-Javadoc) /*
* (non-Javadoc)
*
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem) * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public boolean onOptionsItemSelected(final MenuItem item) { public boolean onOptionsItemSelected(final MenuItem item) {
switch(item.getItemId()){ switch (item.getItemId()) {
case R.id.save: case R.id.save:
save(); save();
break; break;
case android.R.id.home: case android.R.id.home:
final Intent intent = new Intent(this, this.getClass()).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP).putExtra(ListActivity.NO_SPLASH, ListActivity.NO_SPLASH); final Intent intent = new Intent(this, this.getClass()).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP).putExtra(ListActivity.NO_SPLASH, ListActivity.NO_SPLASH);
startActivity(intent); startActivity(intent);
return true; return true;
} }
return super.onOptionsItemSelected(item); return super.onOptionsItemSelected(item);
} }
@Override @Override
public void onPageScrolled(int arg0, float arg1, int arg2) { public void onPageScrolled(final int arg0, final float arg1, final int arg2) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
/** /**
* called when the pager's page is changed * called when the pager's page is changed we use this to dismiss the soft
* we use this to dismiss the soft keyboard * keyboard (non-Javadoc)
* (non-Javadoc) *
* @see android.support.v4.view.ViewPager.OnPageChangeListener#onPageScrollStateChanged(int) * @see android.support.v4.view.ViewPager.OnPageChangeListener#onPageScrollStateChanged(int)
*/ */
@Override @Override
public void onPageScrollStateChanged(int arg0) { public void onPageScrollStateChanged(final int arg0) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mPager.getWindowToken(), 0); imm.hideSoftInputFromWindow(mPager.getWindowToken(), 0);
} }
@Override @Override
public void onPageSelected(int arg0) { public void onPageSelected(final int arg0) {
} }
/** /**
* Called when the ringer content has been changed * Called when the ringer content has been changed (non-Javadoc)
* (non-Javadoc) *
* @see com.TwentyCodes.android.LocationRinger.OnContentChangedListener#onRingerContentChanged(android.content.ContentValues) * @see com.TwentyCodes.android.LocationRinger.OnContentChangedListener#onRingerContentChanged(android.content.ContentValues)
*/ */
@Override @Override
public void onRingerContentChanged(ContentValues values) { public void onRingerContentChanged(final ContentValues values) {
if(Debug.DEBUG){ if (Debug.DEBUG) {
Log.v(TAG,"onRingerContentChanged()"); Log.v(TAG, "onRingerContentChanged()");
logContentValues(values); logContentValues(values);
} }
this.mRinger.putAll(values); mRinger.putAll(values);
} }
/** /**
* (non-Javadoc) * (non-Javadoc)
*
* @see android.app.Activity#onSearchRequested() * @see android.app.Activity#onSearchRequested()
*/ */
@Override @Override
public boolean onSearchRequested() { public boolean onSearchRequested() {
if(this.mLocationInfomationFragment != null && this.mPager.getCurrentItem() == 1) if (mLocationInfomationFragment != null && mPager.getCurrentItem() == 1)
return this.mLocationInfomationFragment.onSearchRequested(); return mLocationInfomationFragment.onSearchRequested();
return super.onSearchRequested(); return super.onSearchRequested();
} }
/** /**
* Prepares a bundle containing all the information that needs to be saved, and returns it to the starting activity * Prepares a bundle containing all the information that needs to be saved,
* and returns it to the starting activity
*
* @author ricky barrette * @author ricky barrette
*/ */
private void save() { private void save() {
final ProgressDialog progress = ProgressDialog.show(this, "", this.getText(R.string.saving), true, true); final ProgressDialog progress = ProgressDialog.show(this, "", getText(R.string.saving), true, true);
//Generate the intent in a thread to prevent anr's and allow for progress dialog // Generate the intent in a thread to prevent anr's and allow for
new Thread( new Runnable(){ // progress dialog
@Override new Thread(new Runnable() {
public void run(){ @Override
Looper.prepare(); public void run() {
RingerInformationActivity.this.mData.putExtra(ListActivity.KEY_RINGER, RingerInformationActivity.this.mRinger).putExtra(ListActivity.KEY_INFO, RingerInformationActivity.this.mInfo); Looper.prepare();
RingerInformationActivity.this.setResult(Activity.RESULT_OK, RingerInformationActivity.this.mData); mData.putExtra(ListActivity.KEY_RINGER, mRinger).putExtra(ListActivity.KEY_INFO, mInfo);
progress.dismiss(); RingerInformationActivity.this.setResult(Activity.RESULT_OK, mData);
RingerInformationActivity.this.finish(); progress.dismiss();
} RingerInformationActivity.this.finish();
}).start(); }
}).start();
} }
/** /**
* Called when the scrolling state of the view pager is changed * Called when the scrolling state of the view pager is changed
* (non-Javadoc) * (non-Javadoc)
*
* @see com.TwentyCodes.android.LocationRinger.EnableScrollingListener#setScrollEnabled(boolean) * @see com.TwentyCodes.android.LocationRinger.EnableScrollingListener#setScrollEnabled(boolean)
*/ */
@Override @Override
public void setScrollEnabled(boolean enabled) { public void setScrollEnabled(final boolean enabled) {
this.mPager.setScrollEnabled(enabled); mPager.setScrollEnabled(enabled);
} }
} }

View File

@@ -24,29 +24,38 @@ import com.TwentyCodes.android.LocationRinger.db.RingerDatabase;
import com.TwentyCodes.android.LocationRinger.debug.Debug; import com.TwentyCodes.android.LocationRinger.debug.Debug;
/** /**
* This adapter will be used to populate the list view with all the ringers names, and manage enabling/disabling of ringers based on their check box. * This adapter will be used to populate the list view with all the ringers
* names, and manage enabling/disabling of ringers based on their check box.
*
* @author ricky barrette * @author ricky barrette
*/ */
public class RingerListAdapter extends BaseAdapter { public class RingerListAdapter extends BaseAdapter {
private static final String TAG = "RingerListAdapter"; class ViewHolder {
TextView title;
TextView description;
CheckBox checkbox;
}
private RingerDatabase mDb; private static final String TAG = "RingerListAdapter";
private List<String> mTitles; private final RingerDatabase mDb;
private LayoutInflater mInflater; private final List<String> mTitles;
private List<String> mDescriptions; private final LayoutInflater mInflater;
private final List<String> mDescriptions;
/** /**
* Creates a new RingerListAdapter * Creates a new RingerListAdapter
*
* @param context * @param context
* @param listener * @param listener
* @param db * @param db
* @author ricky barrette * @author ricky barrette
*/ */
public RingerListAdapter(Context context, RingerDatabase db) { public RingerListAdapter(final Context context, final RingerDatabase db) {
super(); super();
// Cache the LayoutInflate to avoid asking for a new one each time. // Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context); mInflater = LayoutInflater.from(context);
mDb = db; mDb = db;
mTitles = db.getAllRingerTitles(); mTitles = db.getAllRingerTitles();
mDescriptions = db.getAllRingerDescriptions(); mDescriptions = db.getAllRingerDescriptions();
@@ -58,88 +67,84 @@ public class RingerListAdapter extends BaseAdapter {
} }
@Override @Override
public String getItem(int position) { public String getItem(final int position) {
return mTitles.get(position); return mTitles.get(position);
} }
@Override @Override
public long getItemId(int position) { public long getItemId(final int position) {
return position; return position;
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")
@Override @Override
public View getView(final int position, View convertView, ViewGroup parent) { public View getView(final int position, View convertView, final ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unnecessary calls to findViewById() on each row.
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there is no need // A ViewHolder keeps references to children views to avoid unnecessary
// to reinflate it. We only inflate a new View when the convertView supplied // calls to findViewById() on each row.
// by ListView is null. ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
// Creates a ViewHolder and store references to the two children views // When convertView is not null, we can reuse it directly, there is no
// we want to bind data to. // need
holder = new ViewHolder(); // to reinflate it. We only inflate a new View when the convertView
holder.title = (TextView) convertView.findViewById(android.R.id.text1); // supplied
holder.description = (TextView) convertView.findViewById(android.R.id.text2); // by ListView is null.
holder.checkbox = (CheckBox) convertView.findViewById(R.id.ringer_enabled_checkbox); if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
convertView.setTag(holder); // Creates a ViewHolder and store references to the two children
} else { // views
// Get the ViewHolder back to get fast access to the TextView // we want to bind data to.
// and the ImageView. holder = new ViewHolder();
holder = (ViewHolder) convertView.getTag(); holder.title = (TextView) convertView.findViewById(android.R.id.text1);
} holder.description = (TextView) convertView.findViewById(android.R.id.text2);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.ringer_enabled_checkbox);
if(Debug.DEBUG){
Log.d(TAG, "postion = "+position);
if(convertView == null) convertView.setTag(holder);
Log.e(TAG,"convertview is null!!!"); } else
// Get the ViewHolder back to get fast access to the TextView
if(holder == null) // and the ImageView.
Log.e(TAG,"holder is null!!!"); holder = (ViewHolder) convertView.getTag();
if(holder.title == null) if (Debug.DEBUG) {
Log.e(TAG,"holder.text is null!!!"); Log.d(TAG, "postion = " + position);
if(holder.checkbox == null) if (convertView == null)
Log.e(TAG,"holder.checkbox is null!!!"); Log.e(TAG, "convertview is null!!!");
}
if (holder == null)
/* Log.e(TAG, "holder is null!!!");
* Bind the data efficiently with the holder.
* Remember that you should always call setChecked() after calling setOnCheckedChangedListener. if (holder.title == null)
* This will prevent the list from changing the values on you. Log.e(TAG, "holder.text is null!!!");
*/
holder.title.setText(getItem(position)); if (holder.checkbox == null)
holder.description.setText(mDescriptions.get(position)); Log.e(TAG, "holder.checkbox is null!!!");
holder.checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener(){ }
/*
* Bind the data efficiently with the holder. Remember that you should
* always call setChecked() after calling setOnCheckedChangedListener.
* This will prevent the list from changing the values on you.
*/
holder.title.setText(getItem(position));
holder.description.setText(mDescriptions.get(position));
holder.checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override @Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
mDb.setRingerEnabled(position +1, isChecked); mDb.setRingerEnabled(position + 1, isChecked);
} }
}); });
holder.checkbox.setChecked(mDb.isRingerEnabled(position +1)); holder.checkbox.setChecked(mDb.isRingerEnabled(position + 1));
//Remove the checkbox for the default ringer // Remove the checkbox for the default ringer
if(position == 0) { if (position == 0) {
holder.checkbox.setVisibility(View.INVISIBLE); holder.checkbox.setVisibility(View.INVISIBLE);
if(holder.description.getText().toString() == null) if (holder.description.getText().toString() == null)
holder.description.setText(R.string.about_default_ringer); holder.description.setText(R.string.about_default_ringer);
} } else
else holder.checkbox.setVisibility(View.VISIBLE);
holder.checkbox.setVisibility(View.VISIBLE); return convertView;
return convertView;
} }
class ViewHolder {
TextView title;
TextView description;
CheckBox checkbox;
}
} }

View File

@@ -36,26 +36,29 @@ import com.TwentyCodes.android.location.ReverseGeocoder;
import com.google.android.maps.GeoPoint; import com.google.android.maps.GeoPoint;
/** /**
* This dialog will be used to get users input for the address that they want to search for. A GeoPoint location will be returned via LocationSelectedListener * This dialog will be used to get users input for the address that they want to
* search for. A GeoPoint location will be returned via LocationSelectedListener
*
* @author ricky barrette * @author ricky barrette
*/ */
public class SearchDialog extends Dialog implements android.view.View.OnClickListener, OnItemClickListener, OnEditorActionListener{ public class SearchDialog extends Dialog implements android.view.View.OnClickListener, OnItemClickListener, OnEditorActionListener {
protected static final String TAG = "SearchDialog"; protected static final String TAG = "SearchDialog";
private ListView mAddressList; private final ListView mAddressList;
private EditText mAddress; private final EditText mAddress;
private JSONArray mResults; private JSONArray mResults;
private ProgressBar mProgress; private final ProgressBar mProgress;
private Handler mHandler; private final Handler mHandler;
private Context mContext; private final Context mContext;
private OnLocationSelectedListener mListener; private final OnLocationSelectedListener mListener;
/** /**
* Creates a new search dialog * Creates a new search dialog
*
* @param context * @param context
* @author ricky barrette * @author ricky barrette
*/ */
public SearchDialog(Context context, OnLocationSelectedListener listener) { public SearchDialog(final Context context, final OnLocationSelectedListener listener) {
super(context); super(context);
this.setTitle(R.string.search); this.setTitle(R.string.search);
this.setContentView(R.layout.address_dialog); this.setContentView(R.layout.address_dialog);
@@ -64,28 +67,27 @@ public class SearchDialog extends Dialog implements android.view.View.OnClickLis
mAddressList.setOnItemClickListener(this); mAddressList.setOnItemClickListener(this);
mAddress = (EditText) findViewById(R.id.address); mAddress = (EditText) findViewById(R.id.address);
mAddress.setOnEditorActionListener(this); mAddress.setOnEditorActionListener(this);
this.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE); getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
mProgress = (ProgressBar) findViewById(R.id.search_progress); mProgress = (ProgressBar) findViewById(R.id.search_progress);
mHandler = new Handler(); mHandler = new Handler();
mContext = context; mContext = context;
mListener = listener; mListener = listener;
} }
/** /**
* Retrieves all the strings from the JSON Array * Retrieves all the strings from the JSON Array
*
* @return list of addresses * @return list of addresses
* @author ricky barrette * @author ricky barrette
*/ */
private ArrayList<String> getAddress() { private ArrayList<String> getAddress() {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG,"getAddress()"); Log.d(TAG, "getAddress()");
ArrayList<String> list = new ArrayList<String>(); final ArrayList<String> list = new ArrayList<String>();
try { try {
for(int i = 0; i < mResults.length(); i++){ for (int i = 0; i < mResults.length(); i++)
list.add(mResults.getJSONObject(i).getString("address")); list.add(mResults.getJSONObject(i).getString("address"));
} } catch (final JSONException e) {
} catch (JSONException e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
@@ -94,111 +96,115 @@ public class SearchDialog extends Dialog implements android.view.View.OnClickLis
/** /**
* Retrieves the GeoPoint from the JSON Array for the given index * Retrieves the GeoPoint from the JSON Array for the given index
* @param index for the place *
* @param index
* for the place
* @return GeoPoint of the place * @return GeoPoint of the place
* @author ricky barrette * @author ricky barrette
*/ */
private GeoPoint getCoords(int index){ private GeoPoint getCoords(final int index) {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG,"getCoords()"); Log.d(TAG, "getCoords()");
try { try {
JSONArray coords = mResults.getJSONObject(index).getJSONObject("Point").getJSONArray("coordinates"); final JSONArray coords = mResults.getJSONObject(index).getJSONObject("Point").getJSONArray("coordinates");
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG,"creating geopoint: "+ new GeoPoint((int) (coords.getDouble(1) *1E6), (int) (coords.getDouble(0)*1E6)).toString()); Log.d(TAG, "creating geopoint: " + new GeoPoint((int) (coords.getDouble(1) * 1E6), (int) (coords.getDouble(0) * 1E6)).toString());
return new GeoPoint((int) (coords.getDouble(1) *1E6), (int) (coords.getDouble(0)*1E6)); return new GeoPoint((int) (coords.getDouble(1) * 1E6), (int) (coords.getDouble(0) * 1E6));
} catch (JSONException e) { } catch (final JSONException e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
/** /**
* Called when the search button is clicked * Called when the search button is clicked (non-Javadoc)
* (non-Javadoc) *
* @see android.view.View.OnClickListener#onClick(android.view.View) * @see android.view.View.OnClickListener#onClick(android.view.View)
*/ */
@Override @Override
public void onClick(final View v) { public void onClick(final View v) {
switch(v.getId()){ switch (v.getId()) {
case R.id.ok: case R.id.ok:
search(); search();
break; break;
} }
} }
/** /**
* Called when the seach button on the soft keyboard is pressed * Called when the seach button on the soft keyboard is pressed
* (non-Javadoc) * (non-Javadoc)
* @see android.widget.TextView.OnEditorActionListener#onEditorAction(android.widget.TextView, int, android.view.KeyEvent) *
* @see android.widget.TextView.OnEditorActionListener#onEditorAction(android.widget.TextView,
* int, android.view.KeyEvent)
*/ */
@Override @Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { public boolean onEditorAction(final TextView v, final int actionId, final KeyEvent event) {
search(); search();
return false; return false;
} }
/** /**
* Called when an Item from the list is selected * Called when an Item from the list is selected (non-Javadoc)
* (non-Javadoc) *
* @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long) * @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView,
* android.view.View, int, long)
*/ */
@Override @Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG,"slected "+ (int) id); Log.d(TAG, "slected " + (int) id);
mListener.onLocationSelected(getCoords((int) id)); mListener.onLocationSelected(getCoords((int) id));
this.dismiss(); dismiss();
} }
private void search() { private void search() {
final InputMethodManager imm = (InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE); final InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(this.mAddress.getWindowToken(), 0); imm.hideSoftInputFromWindow(mAddress.getWindowToken(), 0);
final View v = this.findViewById(R.id.ok); final View v = findViewById(R.id.ok);
v.setEnabled(false); v.setEnabled(false);
mProgress.setVisibility(View.VISIBLE); mProgress.setVisibility(View.VISIBLE);
mProgress.setIndeterminate(true); mProgress.setIndeterminate(true);
new Thread( new Runnable(){ new Thread(new Runnable() {
@Override @Override
public void run(){ public void run() {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG,"strarting search and parsing") ; Log.d(TAG, "strarting search and parsing");
try { try {
mResults = ReverseGeocoder.addressSearch(mAddress.getText().toString()); mResults = ReverseGeocoder.addressSearch(mAddress.getText().toString());
} catch (IOException e) { } catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
} catch (JSONException e) { } catch (final JSONException e) {
e.printStackTrace(); e.printStackTrace();
} }
if(mResults != null){ if (mResults != null) {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG,"finished searching and parsing"); Log.d(TAG, "finished searching and parsing");
//update UI // update UI
mHandler.post(new Runnable(){ mHandler.post(new Runnable() {
@Override @Override
public void run(){ public void run() {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG,"populating list"); Log.d(TAG, "populating list");
mAddressList.setAdapter(new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, getAddress())); mAddressList.setAdapter(new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, getAddress()));
v.setEnabled(true); v.setEnabled(true);
mProgress.setVisibility(View.INVISIBLE); mProgress.setVisibility(View.INVISIBLE);
mProgress.setIndeterminate(false); mProgress.setIndeterminate(false);
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG,"finished"); Log.d(TAG, "finished");
} }
}); });
} else { } else
//update the UI // update the UI
mHandler.post(new Runnable(){ mHandler.post(new Runnable() {
@Override @Override
public void run(){ public void run() {
v.setEnabled(true); v.setEnabled(true);
mProgress.setVisibility(View.INVISIBLE); mProgress.setVisibility(View.INVISIBLE);
mProgress.setIndeterminate(false); mProgress.setIndeterminate(false);
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG,"failed"); Log.d(TAG, "failed");
} }
}); });
}
} }
}).start(); }).start();
} }

View File

@@ -31,10 +31,11 @@ import com.TwentyCodes.android.LocationRinger.debug.Debug;
/** /**
* This is the settings activity for location ringer * This is the settings activity for location ringer
*
* @author ricky barrette * @author ricky barrette
*/ */
public class SettingsActivity extends PreferenceActivity implements OnPreferenceClickListener { public class SettingsActivity extends PreferenceActivity implements OnPreferenceClickListener {
public static final String SETTINGS = "settings"; public static final String SETTINGS = "settings";
public static final String EMAIL = "email"; public static final String EMAIL = "email";
public static final String START_ON_BOOT = "start_on_boot"; public static final String START_ON_BOOT = "start_on_boot";
@@ -46,26 +47,26 @@ public class SettingsActivity extends PreferenceActivity implements OnPreference
public static final String RESTORE = "restore"; public static final String RESTORE = "restore";
public static final String BACKUP = "backup"; public static final String BACKUP = "backup";
public static final String CURRENT = "current"; public static final String CURRENT = "current";
/** /**
* Backs up the database * Backs up the database
*
* @return true if successful * @return true if successful
* @author ricky barrette * @author ricky barrette
*/ */
public static boolean backup(final Context context){ public static boolean backup(final Context context) {
final File dbFile = new File(Environment.getDataDirectory() + "/data/"+context.getPackageName()+"/shared_prefs/"+SETTINGS+".xml"); final File dbFile = new File(Environment.getDataDirectory() + "/data/" + context.getPackageName() + "/shared_prefs/" + SETTINGS + ".xml");
final File exportDir = new File(Environment.getExternalStorageDirectory(), "/"+context.getString(R.string.app_name)); final File exportDir = new File(Environment.getExternalStorageDirectory(), "/" + context.getString(R.string.app_name));
if (!exportDir.exists()) { if (!exportDir.exists())
exportDir.mkdirs(); exportDir.mkdirs();
}
final File file = new File(exportDir, dbFile.getName()); final File file = new File(exportDir, dbFile.getName());
try { try {
file.createNewFile(); file.createNewFile();
copyFile(dbFile, file); copyFile(dbFile, file);
return true; return true;
} catch (IOException e) { } catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
return false; return false;
} }
@@ -73,57 +74,61 @@ public class SettingsActivity extends PreferenceActivity implements OnPreference
/** /**
* Copies a file * Copies a file
* @param src file *
* @param dst file * @param src
* file
* @param dst
* file
* @throws IOException * @throws IOException
* @author ricky barrette * @author ricky barrette
*/ */
private static void copyFile(final File src, final File dst) throws IOException { private static void copyFile(final File src, final File dst) throws IOException {
final FileInputStream in = new FileInputStream(src); final FileInputStream in = new FileInputStream(src);
final FileOutputStream out = new FileOutputStream(dst); final FileOutputStream out = new FileOutputStream(dst);
final FileChannel inChannel = in.getChannel(); final FileChannel inChannel = in.getChannel();
final FileChannel outChannel = out.getChannel(); final FileChannel outChannel = out.getChannel();
try { try {
inChannel.transferTo(0, inChannel.size(), outChannel); inChannel.transferTo(0, inChannel.size(), outChannel);
} finally { } finally {
if (inChannel != null) if (inChannel != null)
inChannel.close(); inChannel.close();
if (outChannel != null) if (outChannel != null)
outChannel.close(); outChannel.close();
if(in != null) if (in != null)
in.close(); in.close();
if(out != null) if (out != null)
out.close(); out.close();
} }
} }
/** /**
* Restores the database from the sdcard * Restores the database from the sdcard
*
* @return true if successful * @return true if successful
* @author ricky barrette * @author ricky barrette
*/ */
public static void restore(final Context context){ public static void restore(final Context context) {
final File dbFile = new File(Environment.getDataDirectory() + "/data/"+context.getPackageName()+"/shared_prefs/"+SETTINGS+".xml"); final File dbFile = new File(Environment.getDataDirectory() + "/data/" + context.getPackageName() + "/shared_prefs/" + SETTINGS + ".xml");
final File exportDir = new File(Environment.getExternalStorageDirectory(), "/"+context.getString(R.string.app_name)); final File exportDir = new File(Environment.getExternalStorageDirectory(), "/" + context.getString(R.string.app_name));
if (!exportDir.exists()) { if (!exportDir.exists())
exportDir.mkdirs(); exportDir.mkdirs();
}
final File file = new File(exportDir, dbFile.getName()); final File file = new File(exportDir, dbFile.getName());
try { try {
file.createNewFile(); file.createNewFile();
copyFile(file, dbFile); copyFile(file, dbFile);
} catch (IOException e) { } catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
context.getSharedPreferences(SETTINGS, Debug.SHARED_PREFS_MODE).edit().remove(IS_FIRST_RINGER_PROCESSING).remove(IS_DEFAULT).remove(IS_SERVICE_STARTED).commit(); context.getSharedPreferences(SETTINGS, Debug.SHARED_PREFS_MODE).edit().remove(IS_FIRST_RINGER_PROCESSING).remove(IS_DEFAULT).remove(IS_SERVICE_STARTED).commit();
} }
/** /**
* generates the exception repost email intent * generates the exception repost email intent
*
* @param report * @param report
* @return intent to start users email client * @return intent to start users email client
* @author ricky barrette * @author ricky barrette
@@ -132,65 +137,66 @@ public class SettingsActivity extends PreferenceActivity implements OnPreference
/* /*
* get the build information, and build the string * get the build information, and build the string
*/ */
final PackageManager pm = this.getPackageManager(); final PackageManager pm = getPackageManager();
PackageInfo pi; PackageInfo pi;
try { try {
pi = pm.getPackageInfo(this.getPackageName(), 0); pi = pm.getPackageInfo(getPackageName(), 0);
} catch (NameNotFoundException eNnf) { } catch (final NameNotFoundException eNnf) {
//doubt this will ever run since we want info about our own package // doubt this will ever run since we want info about our own package
pi = new PackageInfo(); pi = new PackageInfo();
pi.versionName = "unknown"; pi.versionName = "unknown";
pi.versionCode = 1; pi.versionCode = 1;
} }
final Intent intent = new Intent(Intent.ACTION_SEND); final Intent intent = new Intent(Intent.ACTION_SEND);
final String theSubject = this.getString(R.string.app_name); final String theSubject = this.getString(R.string.app_name);
final String theBody = "\n\n\n"+ Build.FINGERPRINT +"\n"+ this.getString(R.string.app_name)+" "+pi.versionName+" bulid "+pi.versionCode; final String theBody = "\n\n\n" + Build.FINGERPRINT + "\n" + this.getString(R.string.app_name) + " " + pi.versionName + " bulid " + pi.versionCode;
intent.putExtra(Intent.EXTRA_EMAIL,new String[] {this.getString(R.string.email)}); intent.putExtra(Intent.EXTRA_EMAIL, new String[] { this.getString(R.string.email) });
intent.putExtra(Intent.EXTRA_TEXT, theBody); intent.putExtra(Intent.EXTRA_TEXT, theBody);
intent.putExtra(Intent.EXTRA_SUBJECT, theSubject); intent.putExtra(Intent.EXTRA_SUBJECT, theSubject);
intent.setType("message/rfc822"); intent.setType("message/rfc822");
return intent; return intent;
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@SuppressLint("NewApi") @SuppressLint("NewApi")
@Override @Override
public void onCreate(final Bundle savedInstanceState){ public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
this.getPreferenceManager().setSharedPreferencesMode(Debug.SHARED_PREFS_MODE); getPreferenceManager().setSharedPreferencesMode(Debug.SHARED_PREFS_MODE);
this.getPreferenceManager().setSharedPreferencesName(SETTINGS); getPreferenceManager().setSharedPreferencesName(SETTINGS);
addPreferencesFromResource(R.xml.setings); addPreferencesFromResource(R.xml.setings);
this.findPreference(EMAIL).setOnPreferenceClickListener(this); findPreference(EMAIL).setOnPreferenceClickListener(this);
/* /*
* Set up the action bar if required * Set up the action bar if required
*/ */
if(Debug.SUPPORTS_HONEYCOMB) if (Debug.SUPPORTS_HONEYCOMB)
getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setDisplayHomeAsUpEnabled(true);
} }
/** /**
* (non-Javadoc) * (non-Javadoc)
*
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem) * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public boolean onOptionsItemSelected(final MenuItem item) { public boolean onOptionsItemSelected(final MenuItem item) {
switch(item.getItemId()){ switch (item.getItemId()) {
case android.R.id.home: case android.R.id.home:
final Intent intent = new Intent(this, ListActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP).putExtra(ListActivity.NO_SPLASH, ListActivity.NO_SPLASH); final Intent intent = new Intent(this, ListActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP).putExtra(ListActivity.NO_SPLASH, ListActivity.NO_SPLASH);
startActivity(intent); startActivity(intent);
return true; return true;
} }
return super.onOptionsItemSelected(item); return super.onOptionsItemSelected(item);
} }
/** /**
* called when the email preference button is clicked * called when the email preference button is clicked
*/ */
@Override @Override
public boolean onPreferenceClick(Preference preference) { public boolean onPreferenceClick(final Preference preference) {
this.startActivity(generateEmailIntent()); this.startActivity(generateEmailIntent());
return false; return false;
} }

View File

@@ -11,71 +11,77 @@ import android.util.AttributeSet;
import android.view.Gravity; import android.view.Gravity;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
/** /**
* this class will be a simple TextView to be used in a preference activity. you set the text using the set title tag * this class will be a simple TextView to be used in a preference activity. you
* set the text using the set title tag
*
* @author ricky barrette * @author ricky barrette
*/ */
public class TextViewPreference extends Preference { public class TextViewPreference extends Preference {
/** /**
* creates a preference that is nothing but a text view * creates a preference that is nothing but a text view
*
* @param context * @param context
*/ */
public TextViewPreference(Context context) { public TextViewPreference(final Context context) {
super(context); super(context);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* creates a preference that is nothing but a text view * creates a preference that is nothing but a text view
*
* @param context * @param context
* @param attrs * @param attrs
*/ */
public TextViewPreference(Context context, AttributeSet attrs) { public TextViewPreference(final Context context, final AttributeSet attrs) {
super(context, attrs); super(context, attrs);
} }
/** /**
* creates a preference that is nothing but a text view * creates a preference that is nothing but a text view
*
* @param context * @param context
* @param attrs * @param attrs
* @param defStyle * @param defStyle
*/ */
public TextViewPreference(Context context, AttributeSet attrs, int defStyle) { public TextViewPreference(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle); super(context, attrs, defStyle);
} }
/** /**
* creates a linear layout the contains only a textview. * creates a linear layout the contains only a textview. (non-Javadoc)
* (non-Javadoc) *
* @see android.preference.Preference#onCreateView(android.view.ViewGroup) * @see android.preference.Preference#onCreateView(android.view.ViewGroup)
* @param parent * @param parent
* @return * @return
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
protected View onCreateView(ViewGroup parent){ protected View onCreateView(final ViewGroup parent) {
/* /*
* create a vertical linear layout that width and height that wraps content * create a vertical linear layout that width and height that wraps
* content
*/ */
LinearLayout layout = new LinearLayout(getContext()); final LinearLayout layout = new LinearLayout(getContext());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER; params.gravity = Gravity.CENTER;
layout.setPadding(15, 5, 10, 5); layout.setPadding(15, 5, 10, 5);
layout.setOrientation(LinearLayout.VERTICAL); layout.setOrientation(LinearLayout.VERTICAL);
layout.removeAllViews(); layout.removeAllViews();
/* /*
* create a textview that will be used to display the title provided in xml * create a textview that will be used to display the title provided in
* and add it to the lay out * xml and add it to the lay out
*/ */
TextView title = new TextView(getContext()); final TextView title = new TextView(getContext());
title.setText(getTitle()); title.setText(getTitle());
title.setTextSize(16); title.setTextSize(16);
title.setTypeface(Typeface.SANS_SERIF); title.setTypeface(Typeface.SANS_SERIF);

View File

@@ -14,7 +14,7 @@ import android.view.MotionEvent;
* @author ricky * @author ricky
*/ */
public class ViewPager extends android.support.v4.view.ViewPager { public class ViewPager extends android.support.v4.view.ViewPager {
private boolean isEnabled = true; private boolean isEnabled = true;
/** /**
@@ -22,7 +22,7 @@ public class ViewPager extends android.support.v4.view.ViewPager {
* @param apiKey * @param apiKey
* @author ricky barrette * @author ricky barrette
*/ */
public ViewPager(Context context) { public ViewPager(final Context context) {
super(context); super(context);
} }
@@ -31,27 +31,28 @@ public class ViewPager extends android.support.v4.view.ViewPager {
* @param attrs * @param attrs
* @author ricky barrette * @author ricky barrette
*/ */
public ViewPager(Context context, AttributeSet attrs) { public ViewPager(final Context context, final AttributeSet attrs) {
super(context, attrs); super(context, attrs);
} }
/**
* Enables or disabled the scrollview's ability to scroll
* @param enabled
* @author ricky barrette
*/
public void setScrollEnabled(boolean enabled){
isEnabled = enabled;
}
@Override @Override
public boolean onInterceptTouchEvent(MotionEvent ev) { public boolean onInterceptTouchEvent(final MotionEvent ev) {
return isEnabled ? super.onInterceptTouchEvent(ev) : false; return isEnabled ? super.onInterceptTouchEvent(ev) : false;
} }
@Override @Override
public boolean onTouchEvent(MotionEvent ev) { public boolean onTouchEvent(final MotionEvent ev) {
return isEnabled ? super.onTouchEvent(ev) : false; return isEnabled ? super.onTouchEvent(ev) : false;
} }
/**
* Enables or disabled the scrollview's ability to scroll
*
* @param enabled
* @author ricky barrette
*/
public void setScrollEnabled(final boolean enabled) {
isEnabled = enabled;
}
} }

View File

@@ -8,11 +8,6 @@ package com.TwentyCodes.android.LocationRinger.ui.fragments;
import java.util.Map.Entry; import java.util.Map.Entry;
import com.TwentyCodes.android.LocationRinger.R;
import com.TwentyCodes.android.LocationRinger.OnContentChangedListener;
import com.TwentyCodes.android.LocationRinger.db.RingerDatabase;
import com.TwentyCodes.android.LocationRinger.debug.Debug;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.content.ContentValues; import android.content.ContentValues;
import android.content.Context; import android.content.Context;
@@ -30,157 +25,171 @@ import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText; import android.widget.EditText;
import android.widget.ToggleButton; import android.widget.ToggleButton;
import com.TwentyCodes.android.LocationRinger.OnContentChangedListener;
import com.TwentyCodes.android.LocationRinger.R;
import com.TwentyCodes.android.LocationRinger.db.RingerDatabase;
import com.TwentyCodes.android.LocationRinger.debug.Debug;
/** /**
* This fragment will used to allow the user to enter/edit ringer information * This fragment will used to allow the user to enter/edit ringer information
*
* @author ricky * @author ricky
*/ */
@SuppressLint({ "ValidFragment", "ValidFragment" }) @SuppressLint({ "ValidFragment", "ValidFragment" })
public class AboutRingerFragment extends Fragment implements OnCheckedChangeListener { public class AboutRingerFragment extends Fragment implements OnCheckedChangeListener {
/**
* This Edit text class is used in place of a standard edit text. It will
* update the pass the updated information though a listener
*
* @author ricky barrette
*/
public static class ListeningEditText extends EditText {
private String mKey;
private OnContentChangedListener mListener;
private final ContentValues mTemp;
/**
* Creates a new ListeningEditText
*
* @param context
* @author ricky barrette
*/
public ListeningEditText(final Context context) {
super(context);
mTemp = new ContentValues();
}
/**
* Creates a new ListeningEditText
*
* @param context
* @param attrs
* @author ricky barrette
*/
public ListeningEditText(final Context context, final AttributeSet attrs) {
super(context, attrs);
mTemp = new ContentValues();
}
/**
* Creates a new ListeningEditText
*
* @param context
* @param attrs
* @param defStyle
* @author ricky barrette
*/
public ListeningEditText(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
mTemp = new ContentValues();
}
/**
* Called when the edit text is drawn
*
* @author ricky barrette
*/
@Override
public void onDraw(final Canvas canvas) {
super.onDraw(canvas);
if (mListener != null) {
mTemp.put(mKey, this.getText().toString());
if (mKey.equals(RingerDatabase.KEY_RINGER_NAME))
mListener.onRingerContentChanged(mTemp);
else
mListener.onInfoContentChanged(mTemp);
}
}
/**
* Sets the key for this ListeningEditText
*
* @param key
* @ author ricky barrette
*/
public void setKey(final String key) {
mKey = key;
}
/**
* Sets the listener of this ListeningEditText
*
* @param listener
* @ author ricky barrette
*/
public void setListener(final OnContentChangedListener listener) {
mListener = listener;
}
}
private static final String TAG = "AboutRingerFragment"; private static final String TAG = "AboutRingerFragment";
private ListeningEditText mRingerName; private ListeningEditText mRingerName;
private ListeningEditText mRingerDescription; private ListeningEditText mRingerDescription;
private ToggleButton mRingerEnabled; private ToggleButton mRingerEnabled;
private final OnContentChangedListener mListener; private final OnContentChangedListener mListener;
private final ContentValues mInfo; private final ContentValues mInfo;
private final ContentValues mRinger; private final ContentValues mRinger;
public AboutRingerFragment(final ContentValues ringer, final ContentValues info, final OnContentChangedListener listener){ public AboutRingerFragment(final ContentValues ringer, final ContentValues info, final OnContentChangedListener listener) {
super(); super();
this.mInfo = info; mInfo = info;
this.mRinger = ringer; mRinger = ringer;
this.mListener = listener; mListener = listener;
} }
@Override @Override
public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) { public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
if(this.mListener != null){ if (mListener != null) {
final ContentValues info = new ContentValues(); final ContentValues info = new ContentValues();
info.put(RingerDatabase.KEY_IS_ENABLED, isChecked); info.put(RingerDatabase.KEY_IS_ENABLED, isChecked);
this.mListener.onRingerContentChanged(info); mListener.onRingerContentChanged(info);
} }
} }
@Override @Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
this.getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
final View view = inflater.inflate(R.layout.ringer_about_fragment, container, false); final View view = inflater.inflate(R.layout.ringer_about_fragment, container, false);
if(Debug.DEBUG){ if (Debug.DEBUG) {
for(Entry<String,Object> item : this.mInfo.valueSet()) for (final Entry<String, Object> item : mInfo.valueSet())
Log.d(TAG, item.getKey() +" = "+ item.getValue()); Log.d(TAG, item.getKey() + " = " + item.getValue());
for(Entry<String,Object> item : this.mRinger.valueSet()) for (final Entry<String, Object> item : mRinger.valueSet())
Log.d(TAG, item.getKey() +" = "+ item.getValue()); Log.d(TAG, item.getKey() + " = " + item.getValue());
} }
/* /*
* ringer name * ringer name
*/ */
this.mRingerName = (ListeningEditText) view.findViewById(R.id.ringer_name); mRingerName = (ListeningEditText) view.findViewById(R.id.ringer_name);
if(this.mRinger.containsKey(RingerDatabase.KEY_RINGER_NAME)) if (mRinger.containsKey(RingerDatabase.KEY_RINGER_NAME))
this.mRingerName.setText(this.mRinger.getAsString(RingerDatabase.KEY_RINGER_NAME)); mRingerName.setText(mRinger.getAsString(RingerDatabase.KEY_RINGER_NAME));
this.mRingerName.setKey(RingerDatabase.KEY_RINGER_NAME); mRingerName.setKey(RingerDatabase.KEY_RINGER_NAME);
this.mRingerName.setListener(this.mListener); mRingerName.setListener(mListener);
/* /*
* ringer description * ringer description
*/ */
this.mRingerDescription = (ListeningEditText) view.findViewById(R.id.ringer_description); mRingerDescription = (ListeningEditText) view.findViewById(R.id.ringer_description);
if(this.mInfo.containsKey(RingerDatabase.KEY_RINGER_DESCRIPTION)) if (mInfo.containsKey(RingerDatabase.KEY_RINGER_DESCRIPTION))
this.mRingerDescription.setText(this.mInfo.getAsString(RingerDatabase.KEY_RINGER_DESCRIPTION)); mRingerDescription.setText(mInfo.getAsString(RingerDatabase.KEY_RINGER_DESCRIPTION));
this.mRingerDescription.setKey(RingerDatabase.KEY_RINGER_DESCRIPTION); mRingerDescription.setKey(RingerDatabase.KEY_RINGER_DESCRIPTION);
this.mRingerDescription.setListener(this.mListener); mRingerDescription.setListener(mListener);
/* /*
* ringer enabled * ringer enabled
*/ */
this.mRingerEnabled = (ToggleButton) view.findViewById(R.id.ringer_enabled); mRingerEnabled = (ToggleButton) view.findViewById(R.id.ringer_enabled);
if(this.mRinger.containsKey(RingerDatabase.KEY_IS_ENABLED)) if (mRinger.containsKey(RingerDatabase.KEY_IS_ENABLED))
this.mRingerEnabled.setChecked(this.mRinger.getAsBoolean(RingerDatabase.KEY_IS_ENABLED)); mRingerEnabled.setChecked(mRinger.getAsBoolean(RingerDatabase.KEY_IS_ENABLED));
this.mRingerEnabled.setOnCheckedChangeListener(this); mRingerEnabled.setOnCheckedChangeListener(this);
return view; return view;
} }
/**
* This Edit text class is used in place of a standard edit text.
* It will update the pass the updated information though a listener
* @author ricky barrette
*/
public static class ListeningEditText extends EditText{
private String mKey;
private OnContentChangedListener mListener;
private final ContentValues mTemp;
/**
* Creates a new ListeningEditText
* @param context
* @author ricky barrette
*/
public ListeningEditText(Context context) {
super(context);
this.mTemp = new ContentValues();
}
/**
* Creates a new ListeningEditText
* @param context
* @param attrs
* @author ricky barrette
*/
public ListeningEditText(Context context, AttributeSet attrs) {
super(context, attrs);
this.mTemp = new ContentValues();
}
/**
* Creates a new ListeningEditText
* @param context
* @param attrs
* @param defStyle
* @author ricky barrette
*/
public ListeningEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.mTemp = new ContentValues();
}
/**
* Called when the edit text is drawn
* @author ricky barrette
*/
@Override
public void onDraw(Canvas canvas){
super.onDraw(canvas);
if(mListener != null){
mTemp.put(this.mKey, this.getText().toString());
if(this.mKey.equals(RingerDatabase.KEY_RINGER_NAME))
this.mListener.onRingerContentChanged(mTemp);
else
this.mListener.onInfoContentChanged(mTemp);
}
}
/**
* Sets the key for this ListeningEditText
* @param key
* @ author ricky barrette
*/
public void setKey(String key){
this.mKey = key;
}
/**
* Sets the listener of this ListeningEditText
* @param listener
* @ author ricky barrette
*/
public void setListener(OnContentChangedListener listener){
this.mListener = listener;
}
}
} }

View File

@@ -6,9 +6,6 @@
*/ */
package com.TwentyCodes.android.LocationRinger.ui.fragments; package com.TwentyCodes.android.LocationRinger.ui.fragments;
import com.TwentyCodes.android.LocationRinger.FeatureRemovedListener;
import com.TwentyCodes.android.LocationRinger.R;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
@@ -18,41 +15,47 @@ import android.view.View.OnClickListener;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.ImageView; import android.widget.ImageView;
import com.TwentyCodes.android.LocationRinger.FeatureRemovedListener;
import com.TwentyCodes.android.LocationRinger.R;
/** /**
* This is a simple extention of a fragment that will allow for storage of an id * This is a simple extention of a fragment that will allow for storage of an id
*
* @author ricky barrette * @author ricky barrette
*/ */
@SuppressLint("ValidFragment") @SuppressLint("ValidFragment")
public class BaseFeatureFragment extends Fragment implements OnClickListener{ public class BaseFeatureFragment extends Fragment implements OnClickListener {
private final int mId; private final int mId;
private final FeatureRemovedListener mRemovedListener; private final FeatureRemovedListener mRemovedListener;
private final int mIconRes; private final int mIconRes;
private final int mLayout; private final int mLayout;
private ImageView mIcon; private ImageView mIcon;
/** /**
* Creates a new Feature Fragment * Creates a new Feature Fragment
*
* @param id * @param id
* @param layout * @param layout
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public BaseFeatureFragment(int id, int layout, FeatureRemovedListener listener){ public BaseFeatureFragment(final int id, final int layout, final FeatureRemovedListener listener) {
this(id, layout, -1, listener); this(id, layout, -1, listener);
} }
/** /**
* Creates a new FeatureFragment * Creates a new FeatureFragment
*
* @param id * @param id
* @param layout * @param layout
* @param icon * @param icon
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public BaseFeatureFragment(int id, int layout, int icon, FeatureRemovedListener listener){ public BaseFeatureFragment(final int id, final int layout, final int icon, final FeatureRemovedListener listener) {
super(); super();
if ( listener == null ) if (listener == null)
throw new NullPointerException(); throw new NullPointerException();
mRemovedListener = listener; mRemovedListener = listener;
mId = id; mId = id;
@@ -69,36 +72,40 @@ public class BaseFeatureFragment extends Fragment implements OnClickListener{
/** /**
* Called when the user clicks the remove button * Called when the user clicks the remove button
*
* @param v * @param v
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onClick(View v) { public void onClick(final View v) {
if(v.getId() == R.id.close) if (v.getId() == R.id.close)
if(this.mRemovedListener != null) if (mRemovedListener != null)
this.mRemovedListener.onFeatureRemoved(this); mRemovedListener.onFeatureRemoved(this);
} }
/** /**
* (non-Javadoc) * (non-Javadoc)
* @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle) *
* @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater,
* android.view.ViewGroup, android.os.Bundle)
*/ */
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
final View view = inflater.inflate(mLayout, container, false); final View view = inflater.inflate(mLayout, container, false);
mIcon = (ImageView) view.findViewById(R.id.icon); mIcon = (ImageView) view.findViewById(R.id.icon);
view.findViewById(R.id.close).setOnClickListener(this); view.findViewById(R.id.close).setOnClickListener(this);
if(this.mIconRes != -1) if (mIconRes != -1)
setIcon(this.mIconRes); setIcon(mIconRes);
return view; return view;
} }
/** /**
* Sets the icon of this feature fragment * Sets the icon of this feature fragment
*
* @param icon * @param icon
* @author ricky barrette * @author ricky barrette
*/ */
public void setIcon(int icon){ public void setIcon(final int icon) {
mIcon.setImageDrawable(this.getActivity().getResources().getDrawable(icon)); mIcon.setImageDrawable(getActivity().getResources().getDrawable(icon));
} }
} }

View File

@@ -22,6 +22,7 @@ import com.TwentyCodes.android.LocationRinger.debug.Debug;
/** /**
* This fragment will be used to display a list of fragments * This fragment will be used to display a list of fragments
*
* @author ricky barrette * @author ricky barrette
*/ */
public abstract class BaseFragmentListFragment extends Fragment { public abstract class BaseFragmentListFragment extends Fragment {
@@ -33,9 +34,10 @@ public abstract class BaseFragmentListFragment extends Fragment {
/** /**
* Creates a new Populated BaseFragmentListFragment * Creates a new Populated BaseFragmentListFragment
*
* @author ricky barrette * @author ricky barrette
*/ */
public BaseFragmentListFragment(ArrayList<Fragment> fragments, int layout, int container) { public BaseFragmentListFragment(final ArrayList<Fragment> fragments, final int layout, final int container) {
super(); super();
mFragments = fragments; mFragments = fragments;
mLayout = layout; mLayout = layout;
@@ -44,11 +46,12 @@ public abstract class BaseFragmentListFragment extends Fragment {
/** /**
* Creates a new Empty Base Fragment List * Creates a new Empty Base Fragment List
*
* @param layout * @param layout
* @param container * @param container
* @author ricky barrette * @author ricky barrette
*/ */
public BaseFragmentListFragment(int layout, int container) { public BaseFragmentListFragment(final int layout, final int container) {
mLayout = layout; mLayout = layout;
mContainer = container; mContainer = container;
mFragments = new ArrayList<Fragment>(); mFragments = new ArrayList<Fragment>();
@@ -56,58 +59,64 @@ public abstract class BaseFragmentListFragment extends Fragment {
/** /**
* Adds the fragment to the list * Adds the fragment to the list
*
* @param fragment * @param fragment
* @author ricky barrette * @author ricky barrette
*/ */
public void add(final Fragment fragment){ public void add(final Fragment fragment) {
this.mFragments.add(fragment); mFragments.add(fragment);
final FragmentTransaction transaction = this.getFragmentManager().beginTransaction(); final FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(mContainer, fragment, fragment.getTag()); transaction.add(mContainer, fragment, fragment.getTag());
transaction.commit(); transaction.commit();
} }
/** /**
* Adds a collection ofs fragments to the list * Adds a collection ofs fragments to the list
*
* @param fragments * @param fragments
* @author ricky barrette * @author ricky barrette
*/ */
public void addAll(final ArrayList<Fragment> fragments){ public void addAll(final ArrayList<Fragment> fragments) {
final FragmentTransaction transaction = this.getFragmentManager().beginTransaction(); final FragmentTransaction transaction = getFragmentManager().beginTransaction();
for(Fragment f : fragments){ for (final Fragment f : fragments) {
this.mFragments.add(f); mFragments.add(f);
transaction.add(mContainer, f, f.getTag()); transaction.add(mContainer, f, f.getTag());
} }
transaction.commit(); transaction.commit();
} }
/** /**
* Adds a collection ofs fragments to the list, but doesn't preform any transactions * Adds a collection ofs fragments to the list, but doesn't preform any
* transactions
*
* @param fragment * @param fragment
* @author ricky barrette * @author ricky barrette
*/ */
protected void addAllInit(final ArrayList<Fragment> fragments){ protected void addAllInit(final ArrayList<Fragment> fragments) {
for(Fragment f : fragments){ for (final Fragment f : fragments)
this.mFragments.add(f); mFragments.add(f);
}
} }
/** /**
* Loads all the fragments * Loads all the fragments
*
* @author ricky barrette * @author ricky barrette
*/ */
private void loadFragments() { private void loadFragments() {
final FragmentTransaction transaction = this.getFragmentManager().beginTransaction(); final FragmentTransaction transaction = getFragmentManager().beginTransaction();
for(Fragment fragment : this.mFragments) for (final Fragment fragment : mFragments)
transaction.add(mContainer, fragment, fragment.getTag()); transaction.add(mContainer, fragment, fragment.getTag());
transaction.commit(); transaction.commit();
} }
/** /**
* (non-Javadoc) * (non-Javadoc)
* @see android.support.v4.app.Fragment#onActivityResult(int, int, android.content.Intent) *
* @see android.support.v4.app.Fragment#onActivityResult(int, int,
* android.content.Intent)
*/ */
@Override @Override
public void onActivityResult(int arg0, int arg1, Intent arg2) { public void onActivityResult(final int arg0, final int arg1, final Intent arg2) {
removeFragments(); removeFragments();
loadFragments(); loadFragments();
super.onActivityResult(arg0, arg1, arg2); super.onActivityResult(arg0, arg1, arg2);
@@ -115,32 +124,35 @@ public abstract class BaseFragmentListFragment extends Fragment {
/** /**
* (non-Javadoc) * (non-Javadoc)
*
* @see android.support.v4.app.ListFragment#onCreateView(android.view.LayoutInflater, * @see android.support.v4.app.ListFragment#onCreateView(android.view.LayoutInflater,
* android.view.ViewGroup, android.os.Bundle) * android.view.ViewGroup, android.os.Bundle)
*/ */
@Override @Override
public View onCreateView(LayoutInflater inflator, ViewGroup container, Bundle bundle) { public View onCreateView(final LayoutInflater inflator, final ViewGroup container, final Bundle bundle) {
return inflator.inflate(mLayout, null); return inflator.inflate(mLayout, null);
} }
/** /**
* (non-Javadoc) * (non-Javadoc)
*
* @see android.support.v4.app.Fragment#onPause() * @see android.support.v4.app.Fragment#onPause()
*/ */
@Override @Override
public void onPause() { public void onPause() {
try{ try {
removeFragments(); removeFragments();
} catch(IllegalStateException e){ } catch (final IllegalStateException e) {
e.printStackTrace(); e.printStackTrace();
//do nothing // do nothing
} }
Collections.reverse(this.mFragments); Collections.reverse(mFragments);
super.onPause(); super.onPause();
} }
/** /**
* (non-Javadoc) * (non-Javadoc)
*
* @see android.support.v4.app.Fragment#onResume() * @see android.support.v4.app.Fragment#onResume()
*/ */
@Override @Override
@@ -153,26 +165,27 @@ public abstract class BaseFragmentListFragment extends Fragment {
/** /**
* Removes a fragment from the list * Removes a fragment from the list
*
* @param fragment * @param fragment
* @author ricky barrette * @author ricky barrette
*/ */
public void remove(final Fragment fragment){ public void remove(final Fragment fragment) {
this.mFragments.remove(fragment); mFragments.remove(fragment);
final FragmentTransaction transaction = this.getFragmentManager().beginTransaction(); final FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.remove(fragment); transaction.remove(fragment);
transaction.commit(); transaction.commit();
} }
/** /**
* Removes all fragments from the the view * Removes all fragments from the the view
*
* @throws IllegalStateException * @throws IllegalStateException
* @author ricky barrette * @author ricky barrette
*/ */
private void removeFragments() throws IllegalStateException { private void removeFragments() throws IllegalStateException {
final FragmentTransaction transaction = this.getFragmentManager().beginTransaction(); final FragmentTransaction transaction = getFragmentManager().beginTransaction();
for(Fragment fragment : this.mFragments){ for (final Fragment fragment : mFragments)
transaction.remove(fragment); transaction.remove(fragment);
}
transaction.commit(); transaction.commit();
} }
} }

View File

@@ -30,11 +30,12 @@ import com.TwentyCodes.android.LocationRinger.db.RingerDatabase;
/** /**
* This fragment will be used to display a list of features * This fragment will be used to display a list of features
*
* @author ricky * @author ricky
*/ */
@SuppressLint("ValidFragment") @SuppressLint("ValidFragment")
public class FeatureListFragment extends BaseFragmentListFragment implements OnClickListener, android.content.DialogInterface.OnClickListener, FeatureRemovedListener { public class FeatureListFragment extends BaseFragmentListFragment implements OnClickListener, android.content.DialogInterface.OnClickListener, FeatureRemovedListener {
private static final int KEY_ADDED_RINGTONE = 0; private static final int KEY_ADDED_RINGTONE = 0;
private static final int KEY_ADDED_NOTIFICATIONTONE = 1; private static final int KEY_ADDED_NOTIFICATIONTONE = 1;
private static final int KEY_ADDED_ALARM_VOLUME = 2; private static final int KEY_ADDED_ALARM_VOLUME = 2;
@@ -45,234 +46,236 @@ public class FeatureListFragment extends BaseFragmentListFragment implements OnC
private final OnContentChangedListener mListener; private final OnContentChangedListener mListener;
private final ArrayList<Integer> mAdded; private final ArrayList<Integer> mAdded;
/**
* Creates a new empty feature list fragment
*
* @param info
* @param listener
* @author ricky barrette
*/
public FeatureListFragment(final ContentValues info, final OnContentChangedListener listener) {
this(info, listener, new ArrayList<Fragment>(), new ArrayList<Integer>());
}
/** /**
* Creates a new populated FeatureListFragment * Creates a new populated FeatureListFragment
*
* @param info * @param info
* @param listener * @param listener
* @param fragments * @param fragments
* @author ricky barrette * @author ricky barrette
*/ */
public FeatureListFragment(ContentValues info, OnContentChangedListener listener, ArrayList<Fragment> fragments, ArrayList<Integer> added) { public FeatureListFragment(final ContentValues info, final OnContentChangedListener listener, final ArrayList<Fragment> fragments, final ArrayList<Integer> added) {
super(R.layout.fragment_list_contianer, R.id.fragment_list_contianer); super(R.layout.fragment_list_contianer, R.id.fragment_list_contianer);
if ( info == null ) if (info == null)
throw new NullPointerException(); throw new NullPointerException();
if ( listener == null ) if (listener == null)
throw new NullPointerException(); throw new NullPointerException();
if ( fragments == null ) if (fragments == null)
throw new NullPointerException(); throw new NullPointerException();
if ( added == null ) if (added == null)
throw new NullPointerException(); throw new NullPointerException();
mInfo = info; mInfo = info;
mListener = listener; mListener = listener;
mAdded = added; mAdded = added;
} }
/**
* Creates a new empty feature list fragment
* @param info
* @param listener
* @author ricky barrette
*/
public FeatureListFragment(ContentValues info, OnContentChangedListener listener){
this(info, listener, new ArrayList<Fragment>(), new ArrayList<Integer>());
}
/** /**
* Initializes a feature fragment * Initializes a feature fragment
*
* @param fragmentCode * @param fragmentCode
* @return * @return
* @author ricky barrette * @author ricky barrette
*/ */
public Fragment initFeatureFragment(int fragmentCode){ public Fragment initFeatureFragment(final int fragmentCode) {
Fragment f = null; Fragment f = null;
switch(fragmentCode){ switch (fragmentCode) {
case KEY_ADDED_RINGTONE: case KEY_ADDED_RINGTONE:
f= new RingtoneFragment(this.mInfo, this.mListener, this, AudioManager.STREAM_RING, KEY_ADDED_RINGTONE); f = new RingtoneFragment(mInfo, mListener, this, AudioManager.STREAM_RING, KEY_ADDED_RINGTONE);
mAdded.add(KEY_ADDED_RINGTONE); mAdded.add(KEY_ADDED_RINGTONE);
break; break;
case KEY_ADDED_NOTIFICATIONTONE: case KEY_ADDED_NOTIFICATIONTONE:
f = new RingtoneFragment(this.mInfo, this.mListener, this, AudioManager.STREAM_NOTIFICATION, KEY_ADDED_NOTIFICATIONTONE); f = new RingtoneFragment(mInfo, mListener, this, AudioManager.STREAM_NOTIFICATION, KEY_ADDED_NOTIFICATIONTONE);
mAdded.add(KEY_ADDED_NOTIFICATIONTONE); mAdded.add(KEY_ADDED_NOTIFICATIONTONE);
break; break;
case KEY_ADDED_ALARM_VOLUME: case KEY_ADDED_ALARM_VOLUME:
f = new VolumeFragment(this.mInfo, this.getActivity(), this.mListener, this, AudioManager.STREAM_ALARM, KEY_ADDED_ALARM_VOLUME); f = new VolumeFragment(mInfo, getActivity(), mListener, this, AudioManager.STREAM_ALARM, KEY_ADDED_ALARM_VOLUME);
mAdded.add(KEY_ADDED_ALARM_VOLUME); mAdded.add(KEY_ADDED_ALARM_VOLUME);
break; break;
case KEY_ADDED_MUSIC_VOLUME: case KEY_ADDED_MUSIC_VOLUME:
f = new VolumeFragment(this.mInfo, this.getActivity(), this.mListener, this, AudioManager.STREAM_MUSIC, KEY_ADDED_MUSIC_VOLUME); f = new VolumeFragment(mInfo, getActivity(), mListener, this, AudioManager.STREAM_MUSIC, KEY_ADDED_MUSIC_VOLUME);
mAdded.add(KEY_ADDED_MUSIC_VOLUME); mAdded.add(KEY_ADDED_MUSIC_VOLUME);
break; break;
case KEY_ADDED_BT: case KEY_ADDED_BT:
f = new ToggleButtonFragment(R.drawable.ic_action_bluetooth, this.getString(R.string.bluetooth), RingerDatabase.KEY_BT, this.mInfo, this.mListener, this, KEY_ADDED_BT); f = new ToggleButtonFragment(R.drawable.ic_action_bluetooth, this.getString(R.string.bluetooth), RingerDatabase.KEY_BT, mInfo, mListener, this, KEY_ADDED_BT);
mAdded.add(KEY_ADDED_BT); mAdded.add(KEY_ADDED_BT);
break; break;
case KEY_ADDED_WIFI: case KEY_ADDED_WIFI:
f = new ToggleButtonFragment(R.drawable.ic_action_wifi, this.getString(R.string.wifi), RingerDatabase.KEY_WIFI, this.mInfo, this.mListener, this, KEY_ADDED_WIFI); f = new ToggleButtonFragment(R.drawable.ic_action_wifi, this.getString(R.string.wifi), RingerDatabase.KEY_WIFI, mInfo, mListener, this, KEY_ADDED_WIFI);
mAdded.add(KEY_ADDED_WIFI); mAdded.add(KEY_ADDED_WIFI);
break; break;
} }
return f; return f;
} }
/** /**
* Initializes feature fragments based upon current records * Initializes feature fragments based upon current records
*
* @author ricky barrette * @author ricky barrette
*/ */
private ArrayList<Fragment> initList() { private ArrayList<Fragment> initList() {
ArrayList<Fragment> what = new ArrayList<Fragment>(); final ArrayList<Fragment> what = new ArrayList<Fragment>();
if(this.mInfo.containsKey(RingerDatabase.KEY_RINGTONE_VOLUME)){ if (mInfo.containsKey(RingerDatabase.KEY_RINGTONE_VOLUME))
what.add(initFeatureFragment(KEY_ADDED_RINGTONE)); what.add(initFeatureFragment(KEY_ADDED_RINGTONE));
}
if (mInfo.containsKey(RingerDatabase.KEY_NOTIFICATION_RINGTONE_VOLUME))
if(this.mInfo.containsKey(RingerDatabase.KEY_NOTIFICATION_RINGTONE_VOLUME)){
what.add(initFeatureFragment(KEY_ADDED_NOTIFICATIONTONE)); what.add(initFeatureFragment(KEY_ADDED_NOTIFICATIONTONE));
}
if (mInfo.containsKey(RingerDatabase.KEY_ALARM_VOLUME))
if(this.mInfo.containsKey(RingerDatabase.KEY_ALARM_VOLUME)){
what.add(initFeatureFragment(KEY_ADDED_ALARM_VOLUME)); what.add(initFeatureFragment(KEY_ADDED_ALARM_VOLUME));
}
if (mInfo.containsKey(RingerDatabase.KEY_MUSIC_VOLUME))
if(this.mInfo.containsKey(RingerDatabase.KEY_MUSIC_VOLUME)){
what.add(initFeatureFragment(KEY_ADDED_MUSIC_VOLUME)); what.add(initFeatureFragment(KEY_ADDED_MUSIC_VOLUME));
}
if (mInfo.containsKey(RingerDatabase.KEY_BT))
if(this.mInfo.containsKey(RingerDatabase.KEY_BT)){
what.add(initFeatureFragment(KEY_ADDED_BT)); what.add(initFeatureFragment(KEY_ADDED_BT));
}
if (mInfo.containsKey(RingerDatabase.KEY_WIFI))
if(this.mInfo.containsKey(RingerDatabase.KEY_WIFI)){
what.add(initFeatureFragment(KEY_ADDED_WIFI)); what.add(initFeatureFragment(KEY_ADDED_WIFI));
}
return what; return what;
} }
/** /**
* Called when an item is picked from the add featue list * Called when an item is picked from the add featue list (non-Javadoc)
* (non-Javadoc) *
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int) * @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface,
* int)
*/ */
@Override @Override
public void onClick(DialogInterface dialog, int which) { public void onClick(final DialogInterface dialog, final int which) {
final Fragment f = initFeatureFragment(which); final Fragment f = initFeatureFragment(which);
if(f != null) if (f != null)
add(f); add(f);
} }
/** /**
* Called when the add feature button is clicked * Called when the add feature button is clicked (non-Javadoc)
* (non-Javadoc) *
* @see android.view.View.OnClickListener#onClick(android.view.View) * @see android.view.View.OnClickListener#onClick(android.view.View)
*/ */
@Override @Override
public void onClick(View v) { public void onClick(final View v) {
new AlertDialog.Builder(this.getActivity()) new AlertDialog.Builder(getActivity()).setTitle(R.string.add_feature)
.setTitle(R.string.add_feature) .setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.features)) {
.setAdapter(
new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1, this.getResources().getStringArray(R.array.features)){ /**
* we override this, because we want to filter which items
/** * are enabled (non-Javadoc)
* we override this, because we want to filter which items are enabled *
* (non-Javadoc) * @see android.widget.BaseAdapter#areAllItemsEnabled()
* @see android.widget.BaseAdapter#areAllItemsEnabled() */
*/ @Override
@Override public boolean areAllItemsEnabled() {
public boolean areAllItemsEnabled(){ return false;
return false; }
/**
* here we want to grey out disabled items in the list
* (non-Javadoc)
*
* @see android.widget.ArrayAdapter#getView(int,
* android.view.View, android.view.ViewGroup)
*/
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
final View v = super.getView(position, convertView, parent);
v.setEnabled(isEnabled(position));
if (Integer.valueOf(android.os.Build.VERSION.SDK_INT) < 11) {
final TextView t = (TextView) v.findViewById(android.R.id.text1);
t.setTextColor(isEnabled(position) ? Color.BLACK : Color.GRAY);
} }
/** return v;
* here we want to grey out disabled items in the list }
* (non-Javadoc)
* @see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup) /**
*/ * here we can notify the adaptor if an item should be
@Override * enabled or not (non-Javadoc)
public View getView(int position, View convertView, ViewGroup parent){ *
final View v = super.getView(position, convertView, parent); * @see android.widget.BaseAdapter#isEnabled(int)
v.setEnabled(isEnabled(position)); */
@Override
if(Integer.valueOf(android.os.Build.VERSION.SDK_INT) < 11){ public boolean isEnabled(final int position) {
final TextView t = (TextView) v.findViewById(android.R.id.text1); return !mAdded.contains(position);
t.setTextColor(isEnabled(position) ? Color.BLACK : Color.GRAY); }
} }, this).show();
return v;
}
/**
* here we can notify the adaptor if an item should be enabled or not
* (non-Javadoc)
* @see android.widget.BaseAdapter#isEnabled(int)
*/
@Override
public boolean isEnabled(int position){
return ! mAdded.contains(position);
}
}, this)
.show();
} }
/** /**
* Called when the activity is first created * Called when the activity is first created (non-Javadoc)
* (non-Javadoc) *
* @see android.support.v4.app.Fragment#onCreate(android.os.Bundle) * @see android.support.v4.app.Fragment#onCreate(android.os.Bundle)
*/ */
@Override @Override
public void onCreate(Bundle arg0) { public void onCreate(final Bundle arg0) {
addAllInit(initList()); addAllInit(initList());
super.onCreate(arg0); super.onCreate(arg0);
} }
/** /**
* Called when the view needs to be created * Called when the view needs to be created (non-Javadoc)
* (non-Javadoc) *
* @see com.TwentyCodes.android.LocationRinger.ui.fragments.BaseFragmentListFragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle) * @see com.TwentyCodes.android.LocationRinger.ui.fragments.BaseFragmentListFragment#onCreateView(android.view.LayoutInflater,
* android.view.ViewGroup, android.os.Bundle)
*/ */
@Override @Override
public View onCreateView(LayoutInflater inflator, ViewGroup container, Bundle bundle) { public View onCreateView(final LayoutInflater inflator, final ViewGroup container, final Bundle bundle) {
final View v = super.onCreateView(inflator, container, bundle); final View v = super.onCreateView(inflator, container, bundle);
v.findViewById(R.id.add_feature_button).setOnClickListener(this); v.findViewById(R.id.add_feature_button).setOnClickListener(this);
return v; return v;
} }
/** /**
* Called when a fragment needs to be removed * Called when a fragment needs to be removed (non-Javadoc)
* (non-Javadoc) *
* @see com.TwentyCodes.android.LocationRinger.FeatureRemovedListener#onFeatureRemoved(android.support.v4.app.Fragment) * @see com.TwentyCodes.android.LocationRinger.FeatureRemovedListener#onFeatureRemoved(android.support.v4.app.Fragment)
*/ */
@Override @Override
public void onFeatureRemoved(Fragment f) { public void onFeatureRemoved(final Fragment f) {
this.remove(f); remove(f);
if(f instanceof BaseFeatureFragment){ if (f instanceof BaseFeatureFragment) {
final int id = ((BaseFeatureFragment) f).getFragmentId(); final int id = ((BaseFeatureFragment) f).getFragmentId();
mAdded.remove(Integer.valueOf(id)); mAdded.remove(Integer.valueOf(id));
/* /*
* we need to notify our parent activity that the feature have been removed. * we need to notify our parent activity that the feature have been
* removed.
*/ */
switch(id){ switch (id) {
case KEY_ADDED_RINGTONE: case KEY_ADDED_RINGTONE:
this.mListener.onInfoContentRemoved(RingerDatabase.KEY_RINGTONE_URI, RingerDatabase.KEY_RINGTONE_VOLUME); mListener.onInfoContentRemoved(RingerDatabase.KEY_RINGTONE_URI, RingerDatabase.KEY_RINGTONE_VOLUME);
break; break;
case KEY_ADDED_NOTIFICATIONTONE: case KEY_ADDED_NOTIFICATIONTONE:
this.mListener.onInfoContentRemoved(RingerDatabase.KEY_NOTIFICATION_RINGTONE_URI, RingerDatabase.KEY_NOTIFICATION_RINGTONE_VOLUME); mListener.onInfoContentRemoved(RingerDatabase.KEY_NOTIFICATION_RINGTONE_URI, RingerDatabase.KEY_NOTIFICATION_RINGTONE_VOLUME);
break; break;
case KEY_ADDED_ALARM_VOLUME: case KEY_ADDED_ALARM_VOLUME:
this.mListener.onInfoContentRemoved(RingerDatabase.KEY_ALARM_VOLUME); mListener.onInfoContentRemoved(RingerDatabase.KEY_ALARM_VOLUME);
break; break;
case KEY_ADDED_MUSIC_VOLUME: case KEY_ADDED_MUSIC_VOLUME:
this.mListener.onInfoContentRemoved(RingerDatabase.KEY_MUSIC_VOLUME); mListener.onInfoContentRemoved(RingerDatabase.KEY_MUSIC_VOLUME);
break; break;
case KEY_ADDED_BT: case KEY_ADDED_BT:
this.mListener.onInfoContentRemoved(RingerDatabase.KEY_BT); mListener.onInfoContentRemoved(RingerDatabase.KEY_BT);
break; break;
case KEY_ADDED_WIFI: case KEY_ADDED_WIFI:
this.mListener.onInfoContentRemoved(RingerDatabase.KEY_WIFI); mListener.onInfoContentRemoved(RingerDatabase.KEY_WIFI);
break; break;
} }
} }
} }

View File

@@ -36,11 +36,14 @@ import com.TwentyCodes.android.overlays.RadiusOverlay;
import com.google.android.maps.GeoPoint; import com.google.android.maps.GeoPoint;
/** /**
* This fragment will be used to display and allow the user to edit the ringers location trigger * This fragment will be used to display and allow the user to edit the ringers
* location trigger
*
* @author ricky * @author ricky
*/ */
@SuppressLint("ValidFragment") @SuppressLint("ValidFragment")
public class LocationInfomationFragment extends Fragment implements GeoPointLocationListener, OnClickListener, OnCheckedChangeListener, OnSeekBarChangeListener, OnLocationSelectedListener, SearchRequestedListener { public class LocationInfomationFragment extends Fragment implements GeoPointLocationListener, OnClickListener, OnCheckedChangeListener, OnSeekBarChangeListener,
OnLocationSelectedListener, SearchRequestedListener {
private static final String TAG = "RingerInformationHowActivity"; private static final String TAG = "RingerInformationHowActivity";
private final ContentValues mInfo; private final ContentValues mInfo;
@@ -53,177 +56,177 @@ public class LocationInfomationFragment extends Fragment implements GeoPointLoca
private GeoPoint mPoint; private GeoPoint mPoint;
private SkyHook mSkyHook; private SkyHook mSkyHook;
private View view; private View view;
/** /**
* Creates a new MapFragment * Creates a new MapFragment
*
* @author ricky barrette * @author ricky barrette
* @param ringerInformationActivity * @param ringerInformationActivity
*/ */
public LocationInfomationFragment(final ContentValues info, final OnContentChangedListener listener, final EnableScrollingListener enabledListener) { public LocationInfomationFragment(final ContentValues info, final OnContentChangedListener listener, final EnableScrollingListener enabledListener) {
this.mInfo = info; mInfo = info;
this.mListener = listener; mListener = listener;
this.mEnableScrollingListener = enabledListener; mEnableScrollingListener = enabledListener;
} }
/** /**
* Called when a toggle button's state is changed * Called when a toggle button's state is changed
*
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) { public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
view.findViewById(R.id.buttons).setVisibility(isChecked ? View.VISIBLE : View.GONE); view.findViewById(R.id.buttons).setVisibility(isChecked ? View.VISIBLE : View.GONE);
if(mEnableScrollingListener != null) if (mEnableScrollingListener != null)
mEnableScrollingListener.setScrollEnabled(!isChecked); mEnableScrollingListener.setScrollEnabled(!isChecked);
if(isChecked) if (isChecked)
this.mSkyHook.getUpdates(); mSkyHook.getUpdates();
else else
this.mSkyHook.removeUpdates(); mSkyHook.removeUpdates();
this.mMap.setDoubleTapZoonEnabled(isChecked); mMap.setDoubleTapZoonEnabled(isChecked);
//buttons // buttons
this.mMap.setBuiltInZoomControls(isChecked); mMap.setBuiltInZoomControls(isChecked);
this.mMap.setClickable(isChecked); mMap.setClickable(isChecked);
this.mRadius.setEnabled(isChecked); mRadius.setEnabled(isChecked);
Toast.makeText(this.getActivity(), isChecked ? getString(R.string.map_editing_enabled) : getString(R.string.map_editiing_disabled), Toast.LENGTH_SHORT).show(); Toast.makeText(getActivity(), isChecked ? getString(R.string.map_editing_enabled) : getString(R.string.map_editiing_disabled), Toast.LENGTH_SHORT).show();
} }
/** /**
* Called when a view is clicked * Called when a view is clicked
*
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onClick(final View v) { public void onClick(final View v) {
switch (v.getId()){ switch (v.getId()) {
case R.id.mark_my_location: case R.id.mark_my_location:
if(this.mPoint != null) if (mPoint != null)
onLocationSelected(mPoint); onLocationSelected(mPoint);
break; break;
case R.id.my_location: case R.id.my_location:
if(this.mPoint != null) if (mPoint != null)
this.mMap.setMapCenter(mPoint); mMap.setMapCenter(mPoint);
break; break;
case R.id.map_mode: case R.id.map_mode:
this.mMap.setSatellite(mMap.isSatellite() ? false : true); mMap.setSatellite(mMap.isSatellite() ? false : true);
break; break;
case R.id.search: case R.id.search:
new SearchDialog(this.getActivity(), this).show(); new SearchDialog(getActivity(), this).show();
break; break;
} }
} }
@Override @Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
view = inflater.inflate(R.layout.map_info_fragment, container, false); view = inflater.inflate(R.layout.map_info_fragment, container, false);
this.mSkyHook = new SkyHook(this.getActivity()); mSkyHook = new SkyHook(getActivity());
this.mSkyHook.setLocationListener(this); mSkyHook.setLocationListener(this);
this.mMap = (MapFragment) this.getFragmentManager().findFragmentById(R.id.mapview); mMap = (MapFragment) getFragmentManager().findFragmentById(R.id.mapview);
this.mRadius = (SeekBar) view.findViewById(R.id.radius); mRadius = (SeekBar) view.findViewById(R.id.radius);
this.mRadius.setMax(Debug.MAX_RADIUS_IN_METERS); mRadius.setMax(Debug.MAX_RADIUS_IN_METERS);
this.mMap.setClickable(false); mMap.setClickable(false);
this.mMapEditToggle = (ToggleButton) view.findViewById(R.id.map_edit_toggle); mMapEditToggle = (ToggleButton) view.findViewById(R.id.map_edit_toggle);
this.mMapEditToggle.setChecked(false); mMapEditToggle.setChecked(false);
this.mMapEditToggle.setOnCheckedChangeListener(this); mMapEditToggle.setOnCheckedChangeListener(this);
this.mRadiusOverlay = new RadiusOverlay(); mRadiusOverlay = new RadiusOverlay();
this.mRadiusOverlay.setLocationSelectedListener(this); mRadiusOverlay.setLocationSelectedListener(this);
this.mRadius.setOnSeekBarChangeListener(this); mRadius.setOnSeekBarChangeListener(this);
this.mMap.addOverlay(mRadiusOverlay); mMap.addOverlay(mRadiusOverlay);
this.mRadius.setEnabled(false); mRadius.setEnabled(false);
if (this.mInfo.get(RingerDatabase.KEY_LOCATION) != null){ if (mInfo.get(RingerDatabase.KEY_LOCATION) != null) {
final String[] point = this.mInfo.getAsString(RingerDatabase.KEY_LOCATION).split(","); final String[] point = mInfo.getAsString(RingerDatabase.KEY_LOCATION).split(",");
this.mRadiusOverlay.setLocation(new GeoPoint(Integer.parseInt(point[0]), Integer.parseInt(point[1]))); mRadiusOverlay.setLocation(new GeoPoint(Integer.parseInt(point[0]), Integer.parseInt(point[1])));
} }
if (this.mInfo.get(RingerDatabase.KEY_RADIUS) != null){ if (mInfo.get(RingerDatabase.KEY_RADIUS) != null)
this.mRadius.setProgress(this.mInfo.getAsInteger(RingerDatabase.KEY_RADIUS)); mRadius.setProgress(mInfo.getAsInteger(RingerDatabase.KEY_RADIUS));
if (mRadiusOverlay.getLocation() != null) {
mMap.setMapCenter(mRadiusOverlay.getLocation());
mMap.setZoom(16);
} }
if(this.mRadiusOverlay.getLocation() != null){ mMap.setDoubleTapZoonEnabled(false);
this.mMap.setMapCenter(this.mRadiusOverlay.getLocation());
this.mMap.setZoom(16);
}
this.mMap.setDoubleTapZoonEnabled(false);
view.findViewById(R.id.my_location).setOnClickListener(this); view.findViewById(R.id.my_location).setOnClickListener(this);
view.findViewById(R.id.mark_my_location).setOnClickListener(this); view.findViewById(R.id.mark_my_location).setOnClickListener(this);
view.findViewById(R.id.search).setOnClickListener(this); view.findViewById(R.id.search).setOnClickListener(this);
view.findViewById(R.id.map_mode).setOnClickListener(this); view.findViewById(R.id.map_mode).setOnClickListener(this);
return view; return view;
} }
/** /**
* Called when the location is a first fix * Called when the location is a first fix (non-Javadoc)
* (non-Javadoc) *
* @see com.TwentyCodes.android.location.GeoPointLocationListener#onFirstFix(boolean) * @see com.TwentyCodes.android.location.GeoPointLocationListener#onFirstFix(boolean)
*/ */
@Override @Override
public void onFirstFix(final boolean isFirstFix) { public void onFirstFix(final boolean isFirstFix) {
if (isFirstFix) if (isFirstFix)
mMap.enableGPSProgess(); mMap.enableGPSProgess();
else else
mMap.disableGPSProgess(); mMap.disableGPSProgess();
if(mPoint != null){ if (mPoint != null)
/* /*
* if this is the first fix and the radius overlay does not have a point specified * if this is the first fix and the radius overlay does not have a
* then pan the map, and zoom in to the users current location * point specified then pan the map, and zoom in to the users
* current location
*/ */
if(isFirstFix) if (isFirstFix)
if(this.mRadiusOverlay.getLocation() == null){ if (mRadiusOverlay.getLocation() == null)
if(this.mMap != null){ if (mMap != null) {
this.mMap.setMapCenter(mPoint); mMap.setMapCenter(mPoint);
this.mMap.setZoom((this.mMap.getMap().getMaxZoomLevel() - 5)); mMap.setZoom(mMap.getMap().getMaxZoomLevel() - 5);
} }
}
}
} }
/** /**
* Called when skyhook has a location to report * Called when skyhook has a location to report
*
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onLocationChanged(final GeoPoint point, final int accuracy) { public void onLocationChanged(final GeoPoint point, final int accuracy) {
this.mPoint = point; mPoint = point;
} }
/** /**
* Called when a location has been selected * Called when a location has been selected (non-Javadoc)
* (non-Javadoc) *
* @see com.TwentyCodes.android.location.OnLocationSelectedListener#onLocationSelected(com.google.android.maps.GeoPoint) * @see com.TwentyCodes.android.location.OnLocationSelectedListener#onLocationSelected(com.google.android.maps.GeoPoint)
*/ */
@Override @Override
public void onLocationSelected(final GeoPoint point) { public void onLocationSelected(final GeoPoint point) {
if(point != null){ if (point != null) {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG, "onLocationSelected() "+ point.toString()); Log.d(TAG, "onLocationSelected() " + point.toString());
if(this.mRadiusOverlay != null) if (mRadiusOverlay != null)
this.mRadiusOverlay.setLocation(point); mRadiusOverlay.setLocation(point);
if(this.mMap != null) if (mMap != null)
this.mMap.setMapCenter(point); mMap.setMapCenter(point);
if(this.mListener != null){ if (mListener != null) {
final ContentValues info = new ContentValues(); final ContentValues info = new ContentValues();
info.put(RingerDatabase.KEY_LOCATION, point.toString()); info.put(RingerDatabase.KEY_LOCATION, point.toString());
this.mListener.onInfoContentChanged(info); mListener.onInfoContentChanged(info);
} }
} else if(Debug.DEBUG) } else if (Debug.DEBUG)
Log.d(TAG, "onLocationSelected() Location was null"); Log.d(TAG, "onLocationSelected() Location was null");
} }
/** /**
* (non-Javadoc) * (non-Javadoc)
*
* @see android.support.v4.app.Fragment#onPause() * @see android.support.v4.app.Fragment#onPause()
*/ */
@Override @Override
@@ -234,41 +237,44 @@ public class LocationInfomationFragment extends Fragment implements GeoPointLoca
/** /**
* Called when a seekbar is has its progress changed * Called when a seekbar is has its progress changed
*
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onProgressChanged(final SeekBar seekBar, final int progress, final boolean fromUser) { public void onProgressChanged(final SeekBar seekBar, final int progress, final boolean fromUser) {
switch (seekBar.getId()){ switch (seekBar.getId()) {
case R.id.radius: case R.id.radius:
this.mRadiusOverlay.setRadius(progress); mRadiusOverlay.setRadius(progress);
this.mMap.invalidate(); mMap.invalidate();
if(this.mListener != null){ if (mListener != null) {
final ContentValues info = new ContentValues(); final ContentValues info = new ContentValues();
info.put(RingerDatabase.KEY_RADIUS, progress); info.put(RingerDatabase.KEY_RADIUS, progress);
this.mListener.onInfoContentChanged(info); mListener.onInfoContentChanged(info);
} }
break; break;
} }
} }
/** /**
* (non-Javadoc) * (non-Javadoc)
*
* @see android.support.v4.app.Fragment#onResume() * @see android.support.v4.app.Fragment#onResume()
*/ */
@Override @Override
public void onResume() { public void onResume() {
if(mMapEditToggle.isChecked()) if (mMapEditToggle.isChecked())
mSkyHook.getUpdates(); mSkyHook.getUpdates();
super.onResume(); super.onResume();
} }
/** /**
* (non-Javadoc) * (non-Javadoc)
*
* @see com.TwentyCodes.android.LocationRinger.SearchRequestedListener#onSearchRequested() * @see com.TwentyCodes.android.LocationRinger.SearchRequestedListener#onSearchRequested()
*/ */
@Override @Override
public boolean onSearchRequested() { public boolean onSearchRequested() {
new SearchDialog(this.getActivity(), this).show(); new SearchDialog(getActivity(), this).show();
return true; return true;
} }
@@ -276,13 +282,16 @@ public class LocationInfomationFragment extends Fragment implements GeoPointLoca
public void onStartTrackingTouch(final SeekBar seekBar) { public void onStartTrackingTouch(final SeekBar seekBar) {
} }
/* (non-Javadoc) /*
* (non-Javadoc)
*
* @see com.google.android.maps.MapActivity#onDestroy() * @see com.google.android.maps.MapActivity#onDestroy()
*
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onStop() { public void onStop() {
this.mSkyHook.removeUpdates(); mSkyHook.removeUpdates();
super.onDestroy(); super.onDestroy();
} }

View File

@@ -24,10 +24,11 @@ public class MapFragment extends BaseMapFragment {
/** /**
* (non-Javadoc) * (non-Javadoc)
*
* @see com.TwentyCodes.android.fragments.BaseMapFragment#onMapViewCreate(com.TwentyCodes.android.location.MapView) * @see com.TwentyCodes.android.fragments.BaseMapFragment#onMapViewCreate(com.TwentyCodes.android.location.MapView)
*/ */
@Override @Override
public void onMapViewCreate(MapView map) { public void onMapViewCreate(final MapView map) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }

View File

@@ -36,11 +36,12 @@ import com.TwentyCodes.android.LocationRinger.debug.Debug;
/** /**
* This fragment will be for ringtone settings * This fragment will be for ringtone settings
*
* @author ricky * @author ricky
*/ */
@SuppressLint("ValidFragment") @SuppressLint("ValidFragment")
public class RingtoneFragment extends BaseFeatureFragment implements OnClickListener, OnSeekBarChangeListener { public class RingtoneFragment extends BaseFeatureFragment implements OnClickListener, OnSeekBarChangeListener {
private static final String TAG = "RingtoneFragment"; private static final String TAG = "RingtoneFragment";
private final int mStream; private final int mStream;
private final int mType; private final int mType;
@@ -52,77 +53,85 @@ public class RingtoneFragment extends BaseFeatureFragment implements OnClickList
private EditText mRingtone; private EditText mRingtone;
private Uri mRingtoneURI; private Uri mRingtoneURI;
private SeekBar mVolume; private SeekBar mVolume;
public RingtoneFragment(ContentValues info, OnContentChangedListener changedListener, FeatureRemovedListener removedListener, int stream, int id){ public RingtoneFragment(final ContentValues info, final OnContentChangedListener changedListener, final FeatureRemovedListener removedListener, final int stream,
final int id) {
super(id, R.layout.ringtone_fragment, removedListener); super(id, R.layout.ringtone_fragment, removedListener);
if ( info == null ) if (info == null)
throw new NullPointerException(); throw new NullPointerException();
if ( changedListener == null ) if (changedListener == null)
throw new NullPointerException(); throw new NullPointerException();
this.mChangedListener = changedListener; mChangedListener = changedListener;
this.mStream = stream; mStream = stream;
this.mInfo = info; mInfo = info;
switch(stream){ switch (stream) {
case AudioManager.STREAM_NOTIFICATION: case AudioManager.STREAM_NOTIFICATION:
mKeyUri = RingerDatabase.KEY_NOTIFICATION_RINGTONE_URI; mKeyUri = RingerDatabase.KEY_NOTIFICATION_RINGTONE_URI;
mKeyVolume = RingerDatabase.KEY_NOTIFICATION_RINGTONE_VOLUME; mKeyVolume = RingerDatabase.KEY_NOTIFICATION_RINGTONE_VOLUME;
mLabel = R.string.notification_ringtone; mLabel = R.string.notification_ringtone;
mType = RingtoneManager.TYPE_NOTIFICATION; mType = RingtoneManager.TYPE_NOTIFICATION;
break; break;
case AudioManager.STREAM_RING: case AudioManager.STREAM_RING:
default: default:
mKeyUri = RingerDatabase.KEY_RINGTONE_URI; mKeyUri = RingerDatabase.KEY_RINGTONE_URI;
mKeyVolume = RingerDatabase.KEY_RINGTONE_VOLUME; mKeyVolume = RingerDatabase.KEY_RINGTONE_VOLUME;
mLabel = R.string.ringtone; mLabel = R.string.ringtone;
mType = RingtoneManager.TYPE_RINGTONE; mType = RingtoneManager.TYPE_RINGTONE;
break; break;
} }
} }
/** /**
* starts the ringtone picker * starts the ringtone picker
* @param ringtoneCode RingtoneManager.TYPE_? *
* @param uri of current tone * @param ringtoneCode
* RingtoneManager.TYPE_?
* @param uri
* of current tone
* @author ricky barrette * @author ricky barrette
*/ */
private void getRingtoneURI(final int ringtoneCode, final Uri uri){ private void getRingtoneURI(final int ringtoneCode, final Uri uri) {
final Intent intent = new Intent( RingtoneManager.ACTION_RINGTONE_PICKER); final Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, ringtoneCode); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, ringtoneCode);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, R.string.select_tone); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, R.string.select_tone);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, true); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, true);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, false); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, false);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, uri); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, uri);
startActivityForResult( intent, ringtoneCode); startActivityForResult(intent, ringtoneCode);
} }
/** /**
* Notifys the listener that the ringtone has changedRingtoneManager.getActualDefaultRingtoneUri(this.getActivity(), mType) * Notifys the listener that the ringtone has
* changedRingtoneManager.getActualDefaultRingtoneUri(this.getActivity(),
* mType)
*
* @param tone * @param tone
* @author ricky barrette * @author ricky barrette
*/ */
private void notifyRingtoneChanged(Uri tone) { private void notifyRingtoneChanged(final Uri tone) {
if(this.mChangedListener != null){ if (mChangedListener != null) {
ContentValues info = new ContentValues(); final ContentValues info = new ContentValues();
info.put(this.mKeyUri, tone != null ? tone.toString() : null); info.put(mKeyUri, tone != null ? tone.toString() : null);
this.mChangedListener.onInfoContentChanged(info); mChangedListener.onInfoContentChanged(info);
} }
} }
/** /**
* Notifys the listener that the volume has changed * Notifys the listener that the volume has changed
*
* @param progress * @param progress
* @author ricky barrette * @author ricky barrette
*/ */
private void notifyVolumeChanged(int progress) { private void notifyVolumeChanged(final int progress) {
setIcon(progress == 0 ? R.drawable.ic_action_silent : R.drawable.ic_action_volume); setIcon(progress == 0 ? R.drawable.ic_action_silent : R.drawable.ic_action_volume);
if(this.mChangedListener != null){ if (mChangedListener != null) {
final ContentValues info = new ContentValues(); final ContentValues info = new ContentValues();
info.put(this.mKeyVolume, progress); info.put(mKeyVolume, progress);
this.mChangedListener.onInfoContentChanged(info); mChangedListener.onInfoContentChanged(info);
} }
} }
@@ -130,34 +139,35 @@ public class RingtoneFragment extends BaseFeatureFragment implements OnClickList
* Called when the ringtone picker activity returns it's result * Called when the ringtone picker activity returns it's result
*/ */
@Override @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
if (resultCode == Activity.RESULT_OK) { if (resultCode == Activity.RESULT_OK) {
final Uri tone = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI); final Uri tone = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
if(tone == null){ if (tone == null) {
this.mRingtone.setText(R.string.silent); mRingtone.setText(R.string.silent);
mVolume.setEnabled(false); mVolume.setEnabled(false);
mVolume.setProgress(0); mVolume.setProgress(0);
notifyVolumeChanged(0); notifyVolumeChanged(0);
} else { } else {
mVolume.setEnabled(true); mVolume.setEnabled(true);
Ringtone ringtone = RingtoneManager.getRingtone(this.getActivity(), Uri.parse(tone.toString())); final Ringtone ringtone = RingtoneManager.getRingtone(getActivity(), Uri.parse(tone.toString()));
this.mRingtone.setText(ringtone.getTitle(this.getActivity())); mRingtone.setText(ringtone.getTitle(getActivity()));
} }
notifyRingtoneChanged(tone); notifyRingtoneChanged(tone);
} }
super.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data);
} }
/** /**
* Called when a view is clicked * Called when a view is clicked
*
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onClick(View v) { public void onClick(final View v) {
switch(v.getId()){ switch (v.getId()) {
case R.id.ringtone: case R.id.ringtone:
getRingtoneURI(this.mType, mRingtoneURI); getRingtoneURI(mType, mRingtoneURI);
break; break;
default: default:
super.onClick(v); super.onClick(v);
@@ -166,81 +176,81 @@ public class RingtoneFragment extends BaseFeatureFragment implements OnClickList
} }
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
final View view = super.onCreateView(inflater, container, savedInstanceState); final View view = super.onCreateView(inflater, container, savedInstanceState);
final AudioManager audioManager = (AudioManager) this.getActivity().getSystemService(Context.AUDIO_SERVICE); final AudioManager audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
if(Debug.DEBUG) if (Debug.DEBUG)
for(Entry<String,Object> item : this.mInfo.valueSet()) for (final Entry<String, Object> item : mInfo.valueSet())
Log.d(TAG, item.getKey() +" = "+ item.getValue()); Log.d(TAG, item.getKey() + " = " + item.getValue());
/* /*
* initialize the views * initialize the views
*/ */
final TextView label = (TextView) view.findViewById(R.id.title); final TextView label = (TextView) view.findViewById(R.id.title);
label.setText(mLabel); label.setText(mLabel);
setIcon(R.drawable.ic_action_volume); setIcon(R.drawable.ic_action_volume);
this.mRingtone = (EditText) view.findViewById(R.id.ringtone); mRingtone = (EditText) view.findViewById(R.id.ringtone);
mVolume = (SeekBar) view.findViewById(R.id.ringtone_volume); mVolume = (SeekBar) view.findViewById(R.id.ringtone_volume);
this.mRingtone.setOnClickListener(this); mRingtone.setOnClickListener(this);
mVolume.setMax(audioManager.getStreamMaxVolume(mStream)); mVolume.setMax(audioManager.getStreamMaxVolume(mStream));
view.findViewById(R.id.close).setOnClickListener(this); view.findViewById(R.id.close).setOnClickListener(this);
/* /*
* volume * volume
*/ */
if(this.mInfo.containsKey(this.mKeyVolume)) if (mInfo.containsKey(mKeyVolume))
mVolume.setProgress(Integer.parseInt(this.mInfo.getAsString(this.mKeyVolume))); mVolume.setProgress(Integer.parseInt(mInfo.getAsString(mKeyVolume)));
else { else {
mVolume.setProgress(audioManager.getStreamVolume(mStream)); mVolume.setProgress(audioManager.getStreamVolume(mStream));
notifyVolumeChanged(audioManager.getStreamVolume(mStream)); notifyVolumeChanged(audioManager.getStreamVolume(mStream));
} }
/* /*
* ringtone & uri * ringtone & uri
*/ */
if(this.mInfo.containsKey(this.mKeyUri)){ if (mInfo.containsKey(mKeyUri)) {
try{ try {
this.mRingtoneURI = Uri.parse(this.mInfo.getAsString(this.mKeyUri)); mRingtoneURI = Uri.parse(mInfo.getAsString(mKeyUri));
} catch (NullPointerException e){ } catch (final NullPointerException e) {
this.mRingtoneURI = null; mRingtoneURI = null;
} }
this.mVolume.setEnabled(this.mInfo.getAsString(this.mKeyUri) != null); mVolume.setEnabled(mInfo.getAsString(mKeyUri) != null);
} else { } else {
this.mRingtoneURI = RingtoneManager.getActualDefaultRingtoneUri(this.getActivity(), mType); mRingtoneURI = RingtoneManager.getActualDefaultRingtoneUri(getActivity(), mType);
notifyRingtoneChanged(this.mRingtoneURI); notifyRingtoneChanged(mRingtoneURI);
} }
try { try {
this.mRingtone.setText(RingtoneManager.getRingtone(this.getActivity(), mRingtoneURI).getTitle(this.getActivity())); mRingtone.setText(RingtoneManager.getRingtone(getActivity(), mRingtoneURI).getTitle(getActivity()));
} catch (NullPointerException e) { } catch (final NullPointerException e) {
mVolume.setEnabled(false); mVolume.setEnabled(false);
mRingtone.setText(R.string.silent); mRingtone.setText(R.string.silent);
mVolume.setProgress(0); mVolume.setProgress(0);
} }
setIcon(mVolume.getProgress() == 0 ? R.drawable.ic_action_silent : R.drawable.ic_action_volume); setIcon(mVolume.getProgress() == 0 ? R.drawable.ic_action_silent : R.drawable.ic_action_volume);
mVolume.setOnSeekBarChangeListener(this); mVolume.setOnSeekBarChangeListener(this);
return view; return view;
} }
@Override @Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { public void onProgressChanged(final SeekBar seekBar, final int progress, final boolean fromUser) {
if(fromUser) if (fromUser)
notifyVolumeChanged(progress); notifyVolumeChanged(progress);
} }
@Override @Override
public void onStartTrackingTouch(SeekBar seekBar) { public void onStartTrackingTouch(final SeekBar seekBar) {
} }
@Override @Override
public void onStopTrackingTouch(SeekBar seekBar) { public void onStopTrackingTouch(final SeekBar seekBar) {
} }
} }

View File

@@ -24,6 +24,7 @@ import com.TwentyCodes.android.LocationRinger.db.RingerDatabase;
/** /**
* A simple fragment that displays a toggle button and a title label * A simple fragment that displays a toggle button and a title label
*
* @author ricky * @author ricky
*/ */
@SuppressLint("ValidFragment") @SuppressLint("ValidFragment")
@@ -36,55 +37,59 @@ public class ToggleButtonFragment extends BaseFeatureFragment implements OnCheck
/** /**
* Creates a new ToggleButtonFtagment * Creates a new ToggleButtonFtagment
*
* @author ricky barrette * @author ricky barrette
*/ */
public ToggleButtonFragment(int icon, String title, String key, ContentValues info, OnContentChangedListener changedListener, FeatureRemovedListener removedListener, int id) { public ToggleButtonFragment(final int icon, final String title, final String key, final ContentValues info, final OnContentChangedListener changedListener,
final FeatureRemovedListener removedListener, final int id) {
super(id, R.layout.toggle_button_fragment, icon, removedListener); super(id, R.layout.toggle_button_fragment, icon, removedListener);
if ( info == null ) if (info == null)
throw new NullPointerException(); throw new NullPointerException();
if (title == null ) if (title == null)
throw new NullPointerException(); throw new NullPointerException();
if ( key == null ) if (key == null)
throw new NullPointerException(); throw new NullPointerException();
if ( changedListener == null ) if (changedListener == null)
throw new NullPointerException(); throw new NullPointerException();
this.mTitle = title; mTitle = title;
this.mKey = key; mKey = key;
this.mInfo = info; mInfo = info;
this.mChangedListener = changedListener; mChangedListener = changedListener;
} }
/** /**
* Called when the fragment's view needs to be created * Called when the toggle button is clicked (non-Javadoc)
* (non-Javadoc) *
* @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle) * @see android.widget.CompoundButton.OnCheckedChangeListener#onCheckedChanged(android.widget.CompoundButton,
* boolean)
*/ */
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
if (mChangedListener != null) {
final ContentValues info = new ContentValues();
info.put(mKey, isChecked);
mChangedListener.onInfoContentChanged(info);
}
}
/**
* Called when the fragment's view needs to be created (non-Javadoc)
*
* @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater,
* android.view.ViewGroup, android.os.Bundle)
*/
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
final View view = super.onCreateView(inflater, container, savedInstanceState); final View view = super.onCreateView(inflater, container, savedInstanceState);
final TextView t = (TextView) view.findViewById(R.id.title); final TextView t = (TextView) view.findViewById(R.id.title);
t.setText(this.mTitle); t.setText(mTitle);
final ToggleButton b = (ToggleButton) view.findViewById(R.id.toggle); final ToggleButton b = (ToggleButton) view.findViewById(R.id.toggle);
if(this.mInfo.containsKey(this.mKey)) if (mInfo.containsKey(mKey))
b.setChecked(RingerDatabase.parseBoolean(this.mInfo.getAsString(this.mKey))); b.setChecked(RingerDatabase.parseBoolean(mInfo.getAsString(mKey)));
b.setOnCheckedChangeListener(this); b.setOnCheckedChangeListener(this);
return view; return view;
} }
/**
* Called when the toggle button is clicked
* (non-Javadoc)
* @see android.widget.CompoundButton.OnCheckedChangeListener#onCheckedChanged(android.widget.CompoundButton, boolean)
*/
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(this.mChangedListener != null){
ContentValues info = new ContentValues();
info.put(this.mKey, isChecked);
this.mChangedListener.onInfoContentChanged(info);
}
}
} }

View File

@@ -29,6 +29,7 @@ import com.TwentyCodes.android.LocationRinger.debug.Debug;
/** /**
* This fragment will represent the volume fragments * This fragment will represent the volume fragments
*
* @author ricky * @author ricky
*/ */
@SuppressLint("ValidFragment") @SuppressLint("ValidFragment")
@@ -41,122 +42,126 @@ public class VolumeFragment extends BaseFeatureFragment implements OnSeekBarChan
private final String mKey; private final String mKey;
private final ContentValues mInfo; private final ContentValues mInfo;
private final int mLabel; private final int mLabel;
/** /**
* Creates a new Volume Fragment * Creates a new Volume Fragment
*
* @param info * @param info
* @param context * @param context
* @param changedListener * @param changedListener
* @param stream * @param stream
* @author ricky barrette * @author ricky barrette
*/ */
public VolumeFragment(ContentValues info, Context context, OnContentChangedListener changedListener, FeatureRemovedListener removedListener, int stream, int id){ public VolumeFragment(final ContentValues info, final Context context, final OnContentChangedListener changedListener, final FeatureRemovedListener removedListener,
final int stream, final int id) {
super(id, R.layout.volume_fragment, removedListener); super(id, R.layout.volume_fragment, removedListener);
if ( info == null )
throw new NullPointerException();
if ( context == null )
throw new NullPointerException();
if ( changedListener == null )
throw new NullPointerException();
this.mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
this.mStream = stream;
this.mChangedListener = changedListener;
this.mInfo = info;
switch(this.mStream){
case AudioManager.STREAM_ALARM:
this.mLabel = R.string.alarm_volume;
this.mKey = RingerDatabase.KEY_ALARM_VOLUME;
break;
case AudioManager.STREAM_DTMF:
this.mLabel = R.string.dtmf_volume;
this.mKey = RingerDatabase.KEY_DTMF_VOLUME;
break;
case AudioManager.STREAM_MUSIC:
this.mLabel = R.string.music_volume;
this.mKey = RingerDatabase.KEY_MUSIC_VOLUME;
break;
case AudioManager.STREAM_NOTIFICATION:
this.mLabel = R.string.notification_volume;
this.mKey = RingerDatabase.KEY_NOTIFICATION_RINGTONE_VOLUME;
break;
case AudioManager.STREAM_RING:
this.mLabel = R.string.ringtone_volume;
this.mKey = RingerDatabase.KEY_RINGTONE_VOLUME;
break;
case AudioManager.STREAM_SYSTEM:
this.mLabel = R.string.system_volume;
this.mKey = RingerDatabase.KEY_SYSTEM_VOLUME;
break;
case AudioManager.STREAM_VOICE_CALL:
this.mLabel = R.string.call_volume;
this.mKey = RingerDatabase.KEY_CALL_VOLUME;
break;
default:
this.mLabel = R.string.volume;
this.mKey = RingerDatabase.KEY_RINGTONE_VOLUME;
break;
}
}
/** if (info == null)
* Called when the fragment's view needs to be created throw new NullPointerException();
* (non-Javadoc) if (context == null)
* @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle) throw new NullPointerException();
*/ if (changedListener == null)
@Override throw new NullPointerException();
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(Debug.DEBUG)
for(Entry<String,Object> item : this.mInfo.valueSet())
Log.d(TAG, item.getKey() +" = "+ item.getValue());
final View view = super.onCreateView(inflater, container, savedInstanceState);
final TextView label = (TextView) view.findViewById(R.id.title);
final SeekBar volume = (SeekBar) view.findViewById(R.id.volume);
volume.setMax(this.mAudioManager.getStreamMaxVolume(mStream));
volume.setProgress(this.mAudioManager.getStreamVolume(mStream));
volume.setOnSeekBarChangeListener(this);
label.setText(mLabel);
if(this.mInfo.containsKey(this.mKey))
volume.setProgress(Integer.parseInt(this.mInfo.getAsString(this.mKey)));
else
notifyListener(this.mAudioManager.getStreamVolume(mStream));
setIcon(volume.getProgress() == 0 ? R.drawable.ic_action_silent : R.drawable.ic_action_volume);
return view;
}
@Override mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { mStream = stream;
if(fromUser){ mChangedListener = changedListener;
notifyListener(progress); mInfo = info;
setIcon(progress == 0 ? R.drawable.ic_action_silent : R.drawable.ic_action_volume);
switch (mStream) {
case AudioManager.STREAM_ALARM:
mLabel = R.string.alarm_volume;
mKey = RingerDatabase.KEY_ALARM_VOLUME;
break;
case AudioManager.STREAM_DTMF:
mLabel = R.string.dtmf_volume;
mKey = RingerDatabase.KEY_DTMF_VOLUME;
break;
case AudioManager.STREAM_MUSIC:
mLabel = R.string.music_volume;
mKey = RingerDatabase.KEY_MUSIC_VOLUME;
break;
case AudioManager.STREAM_NOTIFICATION:
mLabel = R.string.notification_volume;
mKey = RingerDatabase.KEY_NOTIFICATION_RINGTONE_VOLUME;
break;
case AudioManager.STREAM_RING:
mLabel = R.string.ringtone_volume;
mKey = RingerDatabase.KEY_RINGTONE_VOLUME;
break;
case AudioManager.STREAM_SYSTEM:
mLabel = R.string.system_volume;
mKey = RingerDatabase.KEY_SYSTEM_VOLUME;
break;
case AudioManager.STREAM_VOICE_CALL:
mLabel = R.string.call_volume;
mKey = RingerDatabase.KEY_CALL_VOLUME;
break;
default:
mLabel = R.string.volume;
mKey = RingerDatabase.KEY_RINGTONE_VOLUME;
break;
} }
} }
/** /**
* Notifys the listener of changes made to the volume * Notifys the listener of changes made to the volume
*
* @param progress * @param progress
* @author ricky barrette * @author ricky barrette
*/ */
private void notifyListener(final int progress) { private void notifyListener(final int progress) {
if(this.mChangedListener != null){ if (mChangedListener != null) {
final ContentValues info = new ContentValues(); final ContentValues info = new ContentValues();
info.put(this.mKey, progress); info.put(mKey, progress);
this.mChangedListener.onInfoContentChanged(info); mChangedListener.onInfoContentChanged(info);
}
}
/**
* Called when the fragment's view needs to be created (non-Javadoc)
*
* @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater,
* android.view.ViewGroup, android.os.Bundle)
*/
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
if (Debug.DEBUG)
for (final Entry<String, Object> item : mInfo.valueSet())
Log.d(TAG, item.getKey() + " = " + item.getValue());
final View view = super.onCreateView(inflater, container, savedInstanceState);
final TextView label = (TextView) view.findViewById(R.id.title);
final SeekBar volume = (SeekBar) view.findViewById(R.id.volume);
volume.setMax(mAudioManager.getStreamMaxVolume(mStream));
volume.setProgress(mAudioManager.getStreamVolume(mStream));
volume.setOnSeekBarChangeListener(this);
label.setText(mLabel);
if (mInfo.containsKey(mKey))
volume.setProgress(Integer.parseInt(mInfo.getAsString(mKey)));
else
notifyListener(mAudioManager.getStreamVolume(mStream));
setIcon(volume.getProgress() == 0 ? R.drawable.ic_action_silent : R.drawable.ic_action_volume);
return view;
}
@Override
public void onProgressChanged(final SeekBar seekBar, final int progress, final boolean fromUser) {
if (fromUser) {
notifyListener(progress);
setIcon(progress == 0 ? R.drawable.ic_action_silent : R.drawable.ic_action_volume);
} }
} }
@Override @Override
public void onStartTrackingTouch(SeekBar seekBar) { public void onStartTrackingTouch(final SeekBar seekBar) {
} }
@Override @Override
public void onStopTrackingTouch(SeekBar seekBar) { public void onStopTrackingTouch(final SeekBar seekBar) {
} }
} }

View File

@@ -14,32 +14,34 @@ import android.support.v4.app.FragmentPagerAdapter;
/** /**
* This adaptor maintains the How and What fragments * This adaptor maintains the How and What fragments
*
* @author ricky * @author ricky
*/ */
class FragmentAdapter extends FragmentPagerAdapter { class FragmentAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> mFragments; private final ArrayList<Fragment> mFragments;
/** /**
* Creates a new FragmentAdaptor * Creates a new FragmentAdaptor
*
* @param fm * @param fm
* @param fragments to be displayed * @param fragments
* to be displayed
* @author ricky barrette * @author ricky barrette
*/ */
public FragmentAdapter(FragmentManager fm, ArrayList<Fragment> fragments) { public FragmentAdapter(final FragmentManager fm, final ArrayList<Fragment> fragments) {
super(fm); super(fm);
this.mFragments = fragments; mFragments = fragments;
}
@Override
public Fragment getItem(int position) {
return this.mFragments.get(position);
} }
@Override @Override
public int getCount() { public int getCount() {
return this.mFragments.size(); return mFragments.size();
} }
@Override
public Fragment getItem(final int position) {
return mFragments.get(position);
}
} }

View File

@@ -24,35 +24,39 @@ import android.support.v4.view.ViewPager;
* number and the current visible view. * number and the current visible view.
*/ */
public interface PageIndicator extends ViewPager.OnPageChangeListener { public interface PageIndicator extends ViewPager.OnPageChangeListener {
/** /**
* Bind the indicator to a ViewPager. * <p>
* * Set the current page of both the ViewPager and indicator.
* @param view * </p>
*/ *
public void setViewPager(ViewPager view); * <p>
* This <strong>must</strong> be used if you need to set the page before the
* views are drawn on screen (e.g., default start page).
* </p>
*
* @param item
*/
public void setCurrentItem(int item);
/** /**
* Bind the indicator to a ViewPager. * Set a page change listener which will receive forwarded events.
* *
* @param view * @param listener
* @param initialPosition */
*/ public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener);
public void setViewPager(ViewPager view, int initialPosition);
/** /**
* <p>Set the current page of both the ViewPager and indicator.</p> * Bind the indicator to a ViewPager.
* *
* <p>This <strong>must</strong> be used if you need to set the page before * @param view
* the views are drawn on screen (e.g., default start page).</p> */
* public void setViewPager(ViewPager view);
* @param item
*/
public void setCurrentItem(int item);
/** /**
* Set a page change listener which will receive forwarded events. * Bind the indicator to a ViewPager.
* *
* @param listener * @param view
*/ * @param initialPosition
public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener); */
public void setViewPager(ViewPager view, int initialPosition);
} }

View File

@@ -19,10 +19,11 @@ package com.jakewharton.android.viewpagerindicator;
* A TitleProvider provides the title to display according to a view. * A TitleProvider provides the title to display according to a view.
*/ */
public interface TitleProvider { public interface TitleProvider {
/** /**
* Returns the title of the view at position * Returns the title of the view at position
* @param position *
* @return * @param position
*/ * @return
public String getTitle(int position); */
public String getTitle(int position);
} }

View File

@@ -13,26 +13,30 @@ import android.support.v4.app.FragmentManager;
/** /**
* This adaptor maintains a ViewPager title indicator. * This adaptor maintains a ViewPager title indicator.
*
* @author ricky * @author ricky
*/ */
public class TitledFragmentAdapter extends FragmentAdapter implements TitleProvider { public class TitledFragmentAdapter extends FragmentAdapter implements TitleProvider {
private String[] mTitles; private final String[] mTitles;
/** /**
* Creates a new TitleFragmentAdapter * Creates a new TitleFragmentAdapter
*
* @param fm * @param fm
* @param fragments to be displayed * @param fragments
* @param titles for the fragments * to be displayed
* @param titles
* for the fragments
* @author ricky barrette * @author ricky barrette
*/ */
public TitledFragmentAdapter(FragmentManager fm, ArrayList<Fragment> fragments, String[] titles) { public TitledFragmentAdapter(final FragmentManager fm, final ArrayList<Fragment> fragments, final String[] titles) {
super(fm, fragments); super(fm, fragments);
this.mTitles = titles; mTitles = titles;
} }
@Override @Override
public String getTitle(int position) { public String getTitle(final int position) {
return this.mTitles[position]; return mTitles[position];
} }
} }