code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import static com.google.android.gcm.demo.app.CommonUtilities.DISPLAY_MESSAGE_ACTION; import static com.google.android.gcm.demo.app.CommonUtilities.EXTRA_MESSAGE; import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID; import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL; import com.google.android.gcm.GCMRegistrar; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.TextView; /** * Main UI for the demo app. */ public class DemoActivity extends Activity { TextView mDisplay; AsyncTask<Void, Void, Void> mRegisterTask; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); checkNotNull(SERVER_URL, "SERVER_URL"); checkNotNull(SENDER_ID, "SENDER_ID"); // Make sure the device has the proper dependencies. GCMRegistrar.checkDevice(this); // Make sure the manifest was properly set - comment out this line // while developing the app, then uncomment it when it's ready. GCMRegistrar.checkManifest(this); setContentView(R.layout.main); mDisplay = (TextView) findViewById(R.id.display); registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION)); final String regId = GCMRegistrar.getRegistrationId(this); if (regId.equals("")) { // Automatically registers application on startup. GCMRegistrar.register(this, SENDER_ID); } else { // Device is already registered on GCM, check server. if (GCMRegistrar.isRegisteredOnServer(this)) { // Skips registration. mDisplay.append(getString(R.string.already_registered) + "\n"); } else { // Try to register again, but not in the UI thread. // It's also necessary to cancel the thread onDestroy(), // hence the use of AsyncTask instead of a raw thread. final Context context = this; mRegisterTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { ServerUtilities.register(context, regId); return null; } @Override protected void onPostExecute(Void result) { mRegisterTask = null; } }; mRegisterTask.execute(null, null, null); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.options_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { /* * Typically, an application registers automatically, so options * below are disabled. Uncomment them if you want to manually * register or unregister the device (you will also need to * uncomment the equivalent options on options_menu.xml). */ /* case R.id.options_register: GCMRegistrar.register(this, SENDER_ID); return true; case R.id.options_unregister: GCMRegistrar.unregister(this); return true; */ case R.id.options_clear: mDisplay.setText(null); return true; case R.id.options_exit: finish(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onDestroy() { if (mRegisterTask != null) { mRegisterTask.cancel(true); } unregisterReceiver(mHandleMessageReceiver); GCMRegistrar.onDestroy(this); super.onDestroy(); } private void checkNotNull(Object reference, String name) { if (reference == null) { throw new NullPointerException( getString(R.string.error_config, name)); } } private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String newMessage = intent.getExtras().getString(EXTRA_MESSAGE); mDisplay.append(newMessage + "\n"); } }; }
Java
/** Automatically generated file. DO NOT MODIFY */ package com.google.android.gcm; public final class BuildConfig { public final static boolean DEBUG = true; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; /** * Constants used by the GCM library. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated public final class GCMConstants { /** * Intent sent to GCM to register the application. */ public static final String INTENT_TO_GCM_REGISTRATION = "com.google.android.c2dm.intent.REGISTER"; /** * Intent sent to GCM to unregister the application. */ public static final String INTENT_TO_GCM_UNREGISTRATION = "com.google.android.c2dm.intent.UNREGISTER"; /** * Intent sent by GCM indicating with the result of a registration request. */ public static final String INTENT_FROM_GCM_REGISTRATION_CALLBACK = "com.google.android.c2dm.intent.REGISTRATION"; /** * Intent used by the GCM library to indicate that the registration call * should be retried. */ public static final String INTENT_FROM_GCM_LIBRARY_RETRY = "com.google.android.gcm.intent.RETRY"; /** * Intent sent by GCM containing a message. */ public static final String INTENT_FROM_GCM_MESSAGE = "com.google.android.c2dm.intent.RECEIVE"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_TO_GCM_REGISTRATION} * to indicate which senders (Google API project ids) can send messages to * the application. */ public static final String EXTRA_SENDER = "sender"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_TO_GCM_REGISTRATION} * to get the application info. */ public static final String EXTRA_APPLICATION_PENDING_INTENT = "app"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} * to indicate that the application has been unregistered. */ public static final String EXTRA_UNREGISTERED = "unregistered"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} * to indicate an error when the registration fails. * See constants starting with ERROR_ for possible values. */ public static final String EXTRA_ERROR = "error"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} * to indicate the registration id when the registration succeeds. */ public static final String EXTRA_REGISTRATION_ID = "registration_id"; /** * Type of message present in the * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE} * intent. * This extra is only set for special messages sent from GCM, not for * messages originated from the application. */ public static final String EXTRA_SPECIAL_MESSAGE = "message_type"; /** * Special message indicating the server deleted the pending messages. */ public static final String VALUE_DELETED_MESSAGES = "deleted_messages"; /** * Number of messages deleted by the server because the device was idle. * Present only on messages of special type * {@value com.google.android.gcm.GCMConstants#VALUE_DELETED_MESSAGES} */ public static final String EXTRA_TOTAL_DELETED = "total_deleted"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE} * to indicate which sender (Google API project id) sent the message. */ public static final String EXTRA_FROM = "from"; /** * Permission necessary to receive GCM intents. */ public static final String PERMISSION_GCM_INTENTS = "com.google.android.c2dm.permission.SEND"; /** * @see GCMBroadcastReceiver */ public static final String DEFAULT_INTENT_SERVICE_CLASS_NAME = ".GCMIntentService"; /** * The device can't read the response, or there was a 500/503 from the * server that can be retried later. The application should use exponential * back off and retry. */ public static final String ERROR_SERVICE_NOT_AVAILABLE = "SERVICE_NOT_AVAILABLE"; /** * There is no Google account on the phone. The application should ask the * user to open the account manager and add a Google account. */ public static final String ERROR_ACCOUNT_MISSING = "ACCOUNT_MISSING"; /** * Bad password. The application should ask the user to enter his/her * password, and let user retry manually later. Fix on the device side. */ public static final String ERROR_AUTHENTICATION_FAILED = "AUTHENTICATION_FAILED"; /** * The request sent by the phone does not contain the expected parameters. * This phone doesn't currently support GCM. */ public static final String ERROR_INVALID_PARAMETERS = "INVALID_PARAMETERS"; /** * The sender account is not recognized. Fix on the device side. */ public static final String ERROR_INVALID_SENDER = "INVALID_SENDER"; /** * Incorrect phone registration with Google. This phone doesn't currently * support GCM. */ public static final String ERROR_PHONE_REGISTRATION_ERROR = "PHONE_REGISTRATION_ERROR"; private GCMConstants() { throw new UnsupportedOperationException(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; import android.util.Log; /** * Custom logger. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated class GCMLogger { private final String mTag; // can't use class name on TAG since size is limited to 23 chars private final String mLogPrefix; GCMLogger(String tag, String logPrefix) { mTag = tag; mLogPrefix = logPrefix; } /** * Logs a message on logcat. * * @param priority logging priority * @param template message's template * @param args list of arguments */ protected void log(int priority, String template, Object... args) { if (Log.isLoggable(mTag, priority)) { String message = String.format(template, args); Log.println(priority, mTag, mLogPrefix + message); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; import static com.google.android.gcm.GCMConstants.ERROR_SERVICE_NOT_AVAILABLE; import static com.google.android.gcm.GCMConstants.EXTRA_ERROR; import static com.google.android.gcm.GCMConstants.EXTRA_REGISTRATION_ID; import static com.google.android.gcm.GCMConstants.EXTRA_SPECIAL_MESSAGE; import static com.google.android.gcm.GCMConstants.EXTRA_TOTAL_DELETED; import static com.google.android.gcm.GCMConstants.EXTRA_UNREGISTERED; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_MESSAGE; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK; import static com.google.android.gcm.GCMConstants.VALUE_DELETED_MESSAGES; import android.app.AlarmManager; import android.app.IntentService; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.PowerManager; import android.os.SystemClock; import android.util.Log; import java.util.Random; import java.util.concurrent.TimeUnit; /** * Skeleton for application-specific {@link IntentService}s responsible for * handling communication from Google Cloud Messaging service. * <p> * The abstract methods in this class are called from its worker thread, and * hence should run in a limited amount of time. If they execute long * operations, they should spawn new threads, otherwise the worker thread will * be blocked. * <p> * Subclasses must provide a public no-arg constructor. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated public abstract class GCMBaseIntentService extends IntentService { /** * Old TAG used for logging. Marked as deprecated since it should have * been private at first place. */ @Deprecated public static final String TAG = "GCMBaseIntentService"; private final GCMLogger mLogger = new GCMLogger("GCMBaseIntentService", "[" + getClass().getName() + "]: "); // wakelock private static final String WAKELOCK_KEY = "GCM_LIB"; private static PowerManager.WakeLock sWakeLock; // Java lock used to synchronize access to sWakelock private static final Object LOCK = GCMBaseIntentService.class; private final String[] mSenderIds; // instance counter private static int sCounter = 0; private static final Random sRandom = new Random(); private static final int MAX_BACKOFF_MS = (int) TimeUnit.SECONDS.toMillis(3600); // 1 hour /** * Constructor that does not set a sender id, useful when the sender id * is context-specific. * <p> * When using this constructor, the subclass <strong>must</strong> * override {@link #getSenderIds(Context)}, otherwise methods such as * {@link #onHandleIntent(Intent)} will throw an * {@link IllegalStateException} on runtime. */ protected GCMBaseIntentService() { this(getName("DynamicSenderIds"), null); } /** * Constructor used when the sender id(s) is fixed. */ protected GCMBaseIntentService(String... senderIds) { this(getName(senderIds), senderIds); } private GCMBaseIntentService(String name, String[] senderIds) { super(name); // name is used as base name for threads, etc. mSenderIds = senderIds; mLogger.log(Log.VERBOSE, "Intent service name: %s", name); } private static String getName(String senderId) { String name = "GCMIntentService-" + senderId + "-" + (++sCounter); return name; } private static String getName(String[] senderIds) { String flatSenderIds = GCMRegistrar.getFlatSenderIds(senderIds); return getName(flatSenderIds); } /** * Gets the sender ids. * * <p>By default, it returns the sender ids passed in the constructor, but * it could be overridden to provide a dynamic sender id. * * @throws IllegalStateException if sender id was not set on constructor. */ protected String[] getSenderIds(Context context) { if (mSenderIds == null) { throw new IllegalStateException("sender id not set on constructor"); } return mSenderIds; } /** * Called when a cloud message has been received. * * @param context application's context. * @param intent intent containing the message payload as extras. */ protected abstract void onMessage(Context context, Intent intent); /** * Called when the GCM server tells pending messages have been deleted * because the device was idle. * * @param context application's context. * @param total total number of collapsed messages */ protected void onDeletedMessages(Context context, int total) { } /** * Called on a registration error that could be retried. * * <p>By default, it does nothing and returns {@literal true}, but could be * overridden to change that behavior and/or display the error. * * @param context application's context. * @param errorId error id returned by the GCM service. * * @return if {@literal true}, failed operation will be retried (using * exponential backoff). */ protected boolean onRecoverableError(Context context, String errorId) { return true; } /** * Called on registration or unregistration error. * * @param context application's context. * @param errorId error id returned by the GCM service. */ protected abstract void onError(Context context, String errorId); /** * Called after a device has been registered. * * @param context application's context. * @param registrationId the registration id returned by the GCM service. */ protected abstract void onRegistered(Context context, String registrationId); /** * Called after a device has been unregistered. * * @param registrationId the registration id that was previously registered. * @param context application's context. */ protected abstract void onUnregistered(Context context, String registrationId); @Override public final void onHandleIntent(Intent intent) { try { Context context = getApplicationContext(); String action = intent.getAction(); if (action.equals(INTENT_FROM_GCM_REGISTRATION_CALLBACK)) { GCMRegistrar.setRetryBroadcastReceiver(context); handleRegistration(context, intent); } else if (action.equals(INTENT_FROM_GCM_MESSAGE)) { // checks for special messages String messageType = intent.getStringExtra(EXTRA_SPECIAL_MESSAGE); if (messageType != null) { if (messageType.equals(VALUE_DELETED_MESSAGES)) { String sTotal = intent.getStringExtra(EXTRA_TOTAL_DELETED); if (sTotal != null) { try { int total = Integer.parseInt(sTotal); mLogger.log(Log.VERBOSE, "Received notification for %d deleted" + "messages", total); onDeletedMessages(context, total); } catch (NumberFormatException e) { mLogger.log(Log.ERROR, "GCM returned invalid " + "number of deleted messages (%d)", sTotal); } } } else { // application is not using the latest GCM library mLogger.log(Log.ERROR, "Received unknown special message: %s", messageType); } } else { onMessage(context, intent); } } else if (action.equals(INTENT_FROM_GCM_LIBRARY_RETRY)) { String packageOnIntent = intent.getPackage(); if (packageOnIntent == null || !packageOnIntent.equals( getApplicationContext().getPackageName())) { mLogger.log(Log.ERROR, "Ignoring retry intent from another package (%s)", packageOnIntent); return; } // retry last call if (GCMRegistrar.isRegistered(context)) { GCMRegistrar.internalUnregister(context); } else { String[] senderIds = getSenderIds(context); GCMRegistrar.internalRegister(context, senderIds); } } } finally { // Release the power lock, so phone can get back to sleep. // The lock is reference-counted by default, so multiple // messages are ok. // If onMessage() needs to spawn a thread or do something else, // it should use its own lock. synchronized (LOCK) { // sanity check for null as this is a public method if (sWakeLock != null) { sWakeLock.release(); } else { // should never happen during normal workflow mLogger.log(Log.ERROR, "Wakelock reference is null"); } } } } /** * Called from the broadcast receiver. * <p> * Will process the received intent, call handleMessage(), registered(), * etc. in background threads, with a wake lock, while keeping the service * alive. */ static void runIntentInService(Context context, Intent intent, String className) { synchronized (LOCK) { if (sWakeLock == null) { // This is called from BroadcastReceiver, there is no init. PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY); } } sWakeLock.acquire(); intent.setClassName(context, className); context.startService(intent); } private void handleRegistration(final Context context, Intent intent) { GCMRegistrar.cancelAppPendingIntent(); String registrationId = intent.getStringExtra(EXTRA_REGISTRATION_ID); String error = intent.getStringExtra(EXTRA_ERROR); String unregistered = intent.getStringExtra(EXTRA_UNREGISTERED); mLogger.log(Log.DEBUG, "handleRegistration: registrationId = %s, " + "error = %s, unregistered = %s", registrationId, error, unregistered); // registration succeeded if (registrationId != null) { GCMRegistrar.resetBackoff(context); GCMRegistrar.setRegistrationId(context, registrationId); onRegistered(context, registrationId); return; } // unregistration succeeded if (unregistered != null) { // Remember we are unregistered GCMRegistrar.resetBackoff(context); String oldRegistrationId = GCMRegistrar.clearRegistrationId(context); onUnregistered(context, oldRegistrationId); return; } // last operation (registration or unregistration) returned an error; // Registration failed if (ERROR_SERVICE_NOT_AVAILABLE.equals(error)) { boolean retry = onRecoverableError(context, error); if (retry) { int backoffTimeMs = GCMRegistrar.getBackoff(context); int nextAttempt = backoffTimeMs / 2 + sRandom.nextInt(backoffTimeMs); mLogger.log(Log.DEBUG, "Scheduling registration retry, backoff = %d (%d)", nextAttempt, backoffTimeMs); Intent retryIntent = new Intent(INTENT_FROM_GCM_LIBRARY_RETRY); retryIntent.setPackage(context.getPackageName()); PendingIntent retryPendingIntent = PendingIntent .getBroadcast(context, 0, retryIntent, 0); AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); am.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + nextAttempt, retryPendingIntent); // Next retry should wait longer. if (backoffTimeMs < MAX_BACKOFF_MS) { GCMRegistrar.setBackoff(context, backoffTimeMs * 2); } } else { mLogger.log(Log.VERBOSE, "Not retrying failed operation"); } } else { // Unrecoverable error, notify app onError(context, error); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; import static com.google.android.gcm.GCMConstants.DEFAULT_INTENT_SERVICE_CLASS_NAME; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * {@link BroadcastReceiver} that receives GCM messages and delivers them to * an application-specific {@link GCMBaseIntentService} subclass. * <p> * By default, the {@link GCMBaseIntentService} class belongs to the application * main package and is named * {@link GCMConstants#DEFAULT_INTENT_SERVICE_CLASS_NAME}. To use a new class, * the {@link #getGCMIntentServiceClassName(Context)} must be overridden. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated public class GCMBroadcastReceiver extends BroadcastReceiver { private static boolean mReceiverSet = false; private final GCMLogger mLogger = new GCMLogger("GCMBroadcastReceiver", "[" + getClass().getName() + "]: "); @Override public final void onReceive(Context context, Intent intent) { mLogger.log(Log.VERBOSE, "onReceive: %s", intent.getAction()); // do a one-time check if app is using a custom GCMBroadcastReceiver if (!mReceiverSet) { mReceiverSet = true; GCMRegistrar.setRetryReceiverClassName(context, getClass().getName()); } String className = getGCMIntentServiceClassName(context); mLogger.log(Log.VERBOSE, "GCM IntentService class: %s", className); // Delegates to the application-specific intent service. GCMBaseIntentService.runIntentInService(context, intent, className); setResult(Activity.RESULT_OK, null /* data */, null /* extra */); } /** * Gets the class name of the intent service that will handle GCM messages. */ protected String getGCMIntentServiceClassName(Context context) { return getDefaultIntentServiceClassName(context); } /** * Gets the default class name of the intent service that will handle GCM * messages. */ static final String getDefaultIntentServiceClassName(Context context) { String className = context.getPackageName() + DEFAULT_INTENT_SERVICE_CLASS_NAME; return className; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.os.Build; import android.util.Log; import java.sql.Timestamp; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Utilities for device registration. * <p> * <strong>Note:</strong> this class uses a private {@link SharedPreferences} * object to keep track of the registration token. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated public final class GCMRegistrar { /** * Default lifespan (7 days) of the {@link #isRegisteredOnServer(Context)} * flag until it is considered expired. */ // NOTE: cannot use TimeUnit.DAYS because it's not available on API Level 8 public static final long DEFAULT_ON_SERVER_LIFESPAN_MS = 1000 * 3600 * 24 * 7; private static final String TAG = "GCMRegistrar"; private static final String BACKOFF_MS = "backoff_ms"; private static final String GSF_PACKAGE = "com.google.android.gsf"; private static final String PREFERENCES = "com.google.android.gcm"; private static final int DEFAULT_BACKOFF_MS = 3000; private static final String PROPERTY_REG_ID = "regId"; private static final String PROPERTY_APP_VERSION = "appVersion"; private static final String PROPERTY_ON_SERVER = "onServer"; private static final String PROPERTY_ON_SERVER_EXPIRATION_TIME = "onServerExpirationTime"; private static final String PROPERTY_ON_SERVER_LIFESPAN = "onServerLifeSpan"; /** * {@link GCMBroadcastReceiver} instance used to handle the retry intent. * * <p> * This instance cannot be the same as the one defined in the manifest * because it needs a different permission. */ // guarded by GCMRegistrar.class private static GCMBroadcastReceiver sRetryReceiver; // guarded by GCMRegistrar.class private static Context sRetryReceiverContext; // guarded by GCMRegistrar.class private static String sRetryReceiverClassName; // guarded by GCMRegistrar.class private static PendingIntent sAppPendingIntent; /** * Checks if the device has the proper dependencies installed. * <p> * This method should be called when the application starts to verify that * the device supports GCM. * * @param context application context. * @throws UnsupportedOperationException if the device does not support GCM. */ public static void checkDevice(Context context) { int version = Build.VERSION.SDK_INT; if (version < 8) { throw new UnsupportedOperationException("Device must be at least " + "API Level 8 (instead of " + version + ")"); } PackageManager packageManager = context.getPackageManager(); try { packageManager.getPackageInfo(GSF_PACKAGE, 0); } catch (NameNotFoundException e) { throw new UnsupportedOperationException( "Device does not have package " + GSF_PACKAGE); } } /** * Checks that the application manifest is properly configured. * <p> * A proper configuration means: * <ol> * <li>It creates a custom permission called * {@code PACKAGE_NAME.permission.C2D_MESSAGE}. * <li>It defines at least one {@link BroadcastReceiver} with category * {@code PACKAGE_NAME}. * <li>The {@link BroadcastReceiver}(s) uses the * {@value com.google.android.gcm.GCMConstants#PERMISSION_GCM_INTENTS} * permission. * <li>The {@link BroadcastReceiver}(s) handles the 2 GCM intents * ({@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE} * and * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}). * </ol> * ...where {@code PACKAGE_NAME} is the application package. * <p> * This method should be used during development time to verify that the * manifest is properly set up, but it doesn't need to be called once the * application is deployed to the users' devices. * * @param context application context. * @throws IllegalStateException if any of the conditions above is not met. */ public static void checkManifest(Context context) { PackageManager packageManager = context.getPackageManager(); String packageName = context.getPackageName(); String permissionName = packageName + ".permission.C2D_MESSAGE"; // check permission try { packageManager.getPermissionInfo(permissionName, PackageManager.GET_PERMISSIONS); } catch (NameNotFoundException e) { throw new IllegalStateException( "Application does not define permission " + permissionName); } // check receivers PackageInfo receiversInfo; try { receiversInfo = packageManager.getPackageInfo( packageName, PackageManager.GET_RECEIVERS); } catch (NameNotFoundException e) { throw new IllegalStateException( "Could not get receivers for package " + packageName); } ActivityInfo[] receivers = receiversInfo.receivers; if (receivers == null || receivers.length == 0) { throw new IllegalStateException("No receiver for package " + packageName); } log(context, Log.VERBOSE, "number of receivers for %s: %d", packageName, receivers.length); Set<String> allowedReceivers = new HashSet<String>(); for (ActivityInfo receiver : receivers) { if (GCMConstants.PERMISSION_GCM_INTENTS.equals( receiver.permission)) { allowedReceivers.add(receiver.name); } } if (allowedReceivers.isEmpty()) { throw new IllegalStateException("No receiver allowed to receive " + GCMConstants.PERMISSION_GCM_INTENTS); } checkReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK); checkReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_MESSAGE); } private static void checkReceiver(Context context, Set<String> allowedReceivers, String action) { PackageManager pm = context.getPackageManager(); String packageName = context.getPackageName(); Intent intent = new Intent(action); intent.setPackage(packageName); List<ResolveInfo> receivers = pm.queryBroadcastReceivers(intent, PackageManager.GET_INTENT_FILTERS); if (receivers.isEmpty()) { throw new IllegalStateException("No receivers for action " + action); } log(context, Log.VERBOSE, "Found %d receivers for action %s", receivers.size(), action); // make sure receivers match for (ResolveInfo receiver : receivers) { String name = receiver.activityInfo.name; if (!allowedReceivers.contains(name)) { throw new IllegalStateException("Receiver " + name + " is not set with permission " + GCMConstants.PERMISSION_GCM_INTENTS); } } } /** * Initiate messaging registration for the current application. * <p> * The result will be returned as an * {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with * either a {@link GCMConstants#EXTRA_REGISTRATION_ID} or * {@link GCMConstants#EXTRA_ERROR}. * * @param context application context. * @param senderIds Google Project ID of the accounts authorized to send * messages to this application. * @throws IllegalStateException if device does not have all GCM * dependencies installed. */ public static void register(Context context, String... senderIds) { GCMRegistrar.resetBackoff(context); internalRegister(context, senderIds); } static void internalRegister(Context context, String... senderIds) { String flatSenderIds = getFlatSenderIds(senderIds); log(context, Log.VERBOSE, "Registering app for senders %s", flatSenderIds); Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_REGISTRATION); intent.setPackage(GSF_PACKAGE); setPackageNameExtra(context, intent); intent.putExtra(GCMConstants.EXTRA_SENDER, flatSenderIds); context.startService(intent); } /** * Unregister the application. * <p> * The result will be returned as an * {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with an * {@link GCMConstants#EXTRA_UNREGISTERED} extra. */ public static void unregister(Context context) { GCMRegistrar.resetBackoff(context); internalUnregister(context); } static void internalUnregister(Context context) { log(context, Log.VERBOSE, "Unregistering app"); Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_UNREGISTRATION); intent.setPackage(GSF_PACKAGE); setPackageNameExtra(context, intent); context.startService(intent); } static String getFlatSenderIds(String... senderIds) { if (senderIds == null || senderIds.length == 0) { throw new IllegalArgumentException("No senderIds"); } StringBuilder builder = new StringBuilder(senderIds[0]); for (int i = 1; i < senderIds.length; i++) { builder.append(',').append(senderIds[i]); } return builder.toString(); } /** * Clear internal resources. * * <p> * This method should be called by the main activity's {@code onDestroy()} * method. */ public static synchronized void onDestroy(Context context) { if (sRetryReceiver != null) { log(context, Log.VERBOSE, "Unregistering retry receiver"); sRetryReceiverContext.unregisterReceiver(sRetryReceiver); sRetryReceiver = null; sRetryReceiverContext = null; } } static synchronized void cancelAppPendingIntent() { if (sAppPendingIntent != null) { sAppPendingIntent.cancel(); sAppPendingIntent = null; } } private synchronized static void setPackageNameExtra(Context context, Intent intent) { if (sAppPendingIntent == null) { log(context, Log.VERBOSE, "Creating pending intent to get package name"); sAppPendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(), 0); } intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT, sAppPendingIntent); } /** * Lazy initializes the {@link GCMBroadcastReceiver} instance. */ static synchronized void setRetryBroadcastReceiver(Context context) { if (sRetryReceiver == null) { if (sRetryReceiverClassName == null) { // should never happen log(context, Log.ERROR, "internal error: retry receiver class not set yet"); sRetryReceiver = new GCMBroadcastReceiver(); } else { Class<?> clazz; try { clazz = Class.forName(sRetryReceiverClassName); sRetryReceiver = (GCMBroadcastReceiver) clazz.newInstance(); } catch (Exception e) { log(context, Log.ERROR, "Could not create instance of %s. " + "Using %s directly.", sRetryReceiverClassName, GCMBroadcastReceiver.class.getName()); sRetryReceiver = new GCMBroadcastReceiver(); } } String category = context.getPackageName(); IntentFilter filter = new IntentFilter( GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY); filter.addCategory(category); log(context, Log.VERBOSE, "Registering retry receiver"); sRetryReceiverContext = context; sRetryReceiverContext.registerReceiver(sRetryReceiver, filter); } } /** * Sets the name of the retry receiver class. */ static synchronized void setRetryReceiverClassName(Context context, String className) { log(context, Log.VERBOSE, "Setting the name of retry receiver class to %s", className); sRetryReceiverClassName = className; } /** * Gets the current registration id for application on GCM service. * <p> * If result is empty, the registration has failed. * * @return registration id, or empty string if the registration is not * complete. */ public static String getRegistrationId(Context context) { final SharedPreferences prefs = getGCMPreferences(context); String registrationId = prefs.getString(PROPERTY_REG_ID, ""); // check if app was updated; if so, it must clear registration id to // avoid a race condition if GCM sends a message int oldVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); int newVersion = getAppVersion(context); if (oldVersion != Integer.MIN_VALUE && oldVersion != newVersion) { log(context, Log.VERBOSE, "App version changed from %d to %d;" + "resetting registration id", oldVersion, newVersion); clearRegistrationId(context); registrationId = ""; } return registrationId; } /** * Checks whether the application was successfully registered on GCM * service. */ public static boolean isRegistered(Context context) { return getRegistrationId(context).length() > 0; } /** * Clears the registration id in the persistence store. * * <p>As a side-effect, it also expires the registeredOnServer property. * * @param context application's context. * @return old registration id. */ static String clearRegistrationId(Context context) { setRegisteredOnServer(context, null, 0); return setRegistrationId(context, ""); } /** * Sets the registration id in the persistence store. * * @param context application's context. * @param regId registration id */ static String setRegistrationId(Context context, String regId) { final SharedPreferences prefs = getGCMPreferences(context); String oldRegistrationId = prefs.getString(PROPERTY_REG_ID, ""); int appVersion = getAppVersion(context); log(context, Log.VERBOSE, "Saving regId on app version %d", appVersion); Editor editor = prefs.edit(); editor.putString(PROPERTY_REG_ID, regId); editor.putInt(PROPERTY_APP_VERSION, appVersion); editor.commit(); return oldRegistrationId; } /** * Sets whether the device was successfully registered in the server side. */ public static void setRegisteredOnServer(Context context, boolean flag) { // set the flag's expiration date long lifespan = getRegisterOnServerLifespan(context); long expirationTime = System.currentTimeMillis() + lifespan; setRegisteredOnServer(context, flag, expirationTime); } private static void setRegisteredOnServer(Context context, Boolean flag, long expirationTime) { final SharedPreferences prefs = getGCMPreferences(context); Editor editor = prefs.edit(); if (flag != null) { editor.putBoolean(PROPERTY_ON_SERVER, flag); log(context, Log.VERBOSE, "Setting registeredOnServer flag as %b until %s", flag, new Timestamp(expirationTime)); } else { log(context, Log.VERBOSE, "Setting registeredOnServer expiration to %s", new Timestamp(expirationTime)); } editor.putLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, expirationTime); editor.commit(); } /** * Checks whether the device was successfully registered in the server side, * as set by {@link #setRegisteredOnServer(Context, boolean)}. * * <p>To avoid the scenario where the device sends the registration to the * server but the server loses it, this flag has an expiration date, which * is {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} by default (but can be changed * by {@link #setRegisterOnServerLifespan(Context, long)}). */ public static boolean isRegisteredOnServer(Context context) { final SharedPreferences prefs = getGCMPreferences(context); boolean isRegistered = prefs.getBoolean(PROPERTY_ON_SERVER, false); log(context, Log.VERBOSE, "Is registered on server: %b", isRegistered); if (isRegistered) { // checks if the information is not stale long expirationTime = prefs.getLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, -1); if (System.currentTimeMillis() > expirationTime) { log(context, Log.VERBOSE, "flag expired on: %s", new Timestamp(expirationTime)); return false; } } return isRegistered; } /** * Gets how long (in milliseconds) the {@link #isRegistered(Context)} * property is valid. * * @return value set by {@link #setRegisteredOnServer(Context, boolean)} or * {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} if not set. */ public static long getRegisterOnServerLifespan(Context context) { final SharedPreferences prefs = getGCMPreferences(context); long lifespan = prefs.getLong(PROPERTY_ON_SERVER_LIFESPAN, DEFAULT_ON_SERVER_LIFESPAN_MS); return lifespan; } /** * Sets how long (in milliseconds) the {@link #isRegistered(Context)} * flag is valid. */ public static void setRegisterOnServerLifespan(Context context, long lifespan) { final SharedPreferences prefs = getGCMPreferences(context); Editor editor = prefs.edit(); editor.putLong(PROPERTY_ON_SERVER_LIFESPAN, lifespan); editor.commit(); } /** * Gets the application version. */ private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.versionCode; } catch (NameNotFoundException e) { // should never happen throw new RuntimeException("Coult not get package name: " + e); } } /** * Resets the backoff counter. * <p> * This method should be called after a GCM call succeeds. * * @param context application's context. */ static void resetBackoff(Context context) { log(context, Log.VERBOSE, "Resetting backoff"); setBackoff(context, DEFAULT_BACKOFF_MS); } /** * Gets the current backoff counter. * * @param context application's context. * @return current backoff counter, in milliseconds. */ static int getBackoff(Context context) { final SharedPreferences prefs = getGCMPreferences(context); return prefs.getInt(BACKOFF_MS, DEFAULT_BACKOFF_MS); } /** * Sets the backoff counter. * <p> * This method should be called after a GCM call fails, passing an * exponential value. * * @param context application's context. * @param backoff new backoff counter, in milliseconds. */ static void setBackoff(Context context, int backoff) { final SharedPreferences prefs = getGCMPreferences(context); Editor editor = prefs.edit(); editor.putInt(BACKOFF_MS, backoff); editor.commit(); } private static SharedPreferences getGCMPreferences(Context context) { return context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE); } /** * Logs a message on logcat. * * @param context application's context. * @param priority logging priority * @param template message's template * @param args list of arguments */ private static void log(Context context, int priority, String template, Object... args) { if (Log.isLoggable(TAG, priority)) { String message = String.format(template, args); Log.println(priority, TAG, "[" + context.getPackageName() + "]: " + message); } } private GCMRegistrar() { throw new UnsupportedOperationException(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import java.io.Serializable; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; /** * GCM message. * * <p> * Instances of this class are immutable and should be created using a * {@link Builder}. Examples: * * <strong>Simplest message:</strong> * <pre><code> * Message message = new Message.Builder().build(); * </pre></code> * * <strong>Message with optional attributes:</strong> * <pre><code> * Message message = new Message.Builder() * .collapseKey(collapseKey) * .timeToLive(3) * .delayWhileIdle(true) * .dryRun(true) * .restrictedPackageName(restrictedPackageName) * .build(); * </pre></code> * * <strong>Message with optional attributes and payload data:</strong> * <pre><code> * Message message = new Message.Builder() * .collapseKey(collapseKey) * .timeToLive(3) * .delayWhileIdle(true) * .dryRun(true) * .restrictedPackageName(restrictedPackageName) * .addData("key1", "value1") * .addData("key2", "value2") * .build(); * </pre></code> */ public final class Message implements Serializable { private final String collapseKey; private final Boolean delayWhileIdle; private final Integer timeToLive; private final Map<String, String> data; private final Boolean dryRun; private final String restrictedPackageName; public static final class Builder { private final Map<String, String> data; // optional parameters private String collapseKey; private Boolean delayWhileIdle; private Integer timeToLive; private Boolean dryRun; private String restrictedPackageName; public Builder() { this.data = new LinkedHashMap<String, String>(); } /** * Sets the collapseKey property. */ public Builder collapseKey(String value) { collapseKey = value; return this; } /** * Sets the delayWhileIdle property (default value is {@literal false}). */ public Builder delayWhileIdle(boolean value) { delayWhileIdle = value; return this; } /** * Sets the time to live, in seconds. */ public Builder timeToLive(int value) { timeToLive = value; return this; } /** * Adds a key/value pair to the payload data. */ public Builder addData(String key, String value) { data.put(key, value); return this; } /** * Sets the dryRun property (default value is {@literal false}). */ public Builder dryRun(boolean value) { dryRun = value; return this; } /** * Sets the restrictedPackageName property. */ public Builder restrictedPackageName(String value) { restrictedPackageName = value; return this; } public Message build() { return new Message(this); } } private Message(Builder builder) { collapseKey = builder.collapseKey; delayWhileIdle = builder.delayWhileIdle; data = Collections.unmodifiableMap(builder.data); timeToLive = builder.timeToLive; dryRun = builder.dryRun; restrictedPackageName = builder.restrictedPackageName; } /** * Gets the collapse key. */ public String getCollapseKey() { return collapseKey; } /** * Gets the delayWhileIdle flag. */ public Boolean isDelayWhileIdle() { return delayWhileIdle; } /** * Gets the time to live (in seconds). */ public Integer getTimeToLive() { return timeToLive; } /** * Gets the dryRun flag. */ public Boolean isDryRun() { return dryRun; } /** * Gets the restricted package name. */ public String getRestrictedPackageName() { return restrictedPackageName; } /** * Gets the payload data, which is immutable. */ public Map<String, String> getData() { return data; } @Override public String toString() { StringBuilder builder = new StringBuilder("Message("); if (collapseKey != null) { builder.append("collapseKey=").append(collapseKey).append(", "); } if (timeToLive != null) { builder.append("timeToLive=").append(timeToLive).append(", "); } if (delayWhileIdle != null) { builder.append("delayWhileIdle=").append(delayWhileIdle).append(", "); } if (dryRun != null) { builder.append("dryRun=").append(dryRun).append(", "); } if (restrictedPackageName != null) { builder.append("restrictedPackageName=").append(restrictedPackageName).append(", "); } if (!data.isEmpty()) { builder.append("data: {"); for (Map.Entry<String, String> entry : data.entrySet()) { builder.append(entry.getKey()).append("=").append(entry.getValue()) .append(","); } builder.delete(builder.length() - 1, builder.length()); builder.append("}"); } if (builder.charAt(builder.length() - 1) == ' ') { builder.delete(builder.length() - 2, builder.length()); } builder.append(")"); return builder.toString(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import java.io.IOException; /** * Exception thrown when GCM returned an error due to an invalid request. * <p> * This is equivalent to GCM posts that return an HTTP error different of 200. */ public final class InvalidRequestException extends IOException { private final int status; private final String description; public InvalidRequestException(int status) { this(status, null); } public InvalidRequestException(int status, String description) { super(getMessage(status, description)); this.status = status; this.description = description; } private static String getMessage(int status, String description) { StringBuilder base = new StringBuilder("HTTP Status Code: ").append(status); if (description != null) { base.append("(").append(description).append(")"); } return base.toString(); } /** * Gets the HTTP Status Code. */ public int getHttpStatusCode() { return status; } /** * Gets the error description. */ public String getDescription() { return description; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import static com.google.android.gcm.server.Constants.GCM_SEND_ENDPOINT; import static com.google.android.gcm.server.Constants.JSON_CANONICAL_IDS; import static com.google.android.gcm.server.Constants.JSON_ERROR; import static com.google.android.gcm.server.Constants.JSON_FAILURE; import static com.google.android.gcm.server.Constants.JSON_MESSAGE_ID; import static com.google.android.gcm.server.Constants.JSON_MULTICAST_ID; import static com.google.android.gcm.server.Constants.JSON_PAYLOAD; import static com.google.android.gcm.server.Constants.JSON_REGISTRATION_IDS; import static com.google.android.gcm.server.Constants.JSON_RESULTS; import static com.google.android.gcm.server.Constants.JSON_SUCCESS; import static com.google.android.gcm.server.Constants.PARAM_COLLAPSE_KEY; import static com.google.android.gcm.server.Constants.PARAM_DELAY_WHILE_IDLE; import static com.google.android.gcm.server.Constants.PARAM_DRY_RUN; import static com.google.android.gcm.server.Constants.PARAM_PAYLOAD_PREFIX; import static com.google.android.gcm.server.Constants.PARAM_REGISTRATION_ID; import static com.google.android.gcm.server.Constants.PARAM_RESTRICTED_PACKAGE_NAME; import static com.google.android.gcm.server.Constants.PARAM_TIME_TO_LIVE; import static com.google.android.gcm.server.Constants.TOKEN_CANONICAL_REG_ID; import static com.google.android.gcm.server.Constants.TOKEN_ERROR; import static com.google.android.gcm.server.Constants.TOKEN_MESSAGE_ID; import com.google.android.gcm.server.Result.Builder; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; /** * Helper class to send messages to the GCM service using an API Key. */ public class Sender { protected static final String UTF8 = "UTF-8"; /** * Initial delay before first retry, without jitter. */ protected static final int BACKOFF_INITIAL_DELAY = 1000; /** * Maximum delay before a retry. */ protected static final int MAX_BACKOFF_DELAY = 1024000; protected final Random random = new Random(); protected static final Logger logger = Logger.getLogger(Sender.class.getName()); private final String key; /** * Default constructor. * * @param key API key obtained through the Google API Console. */ public Sender(String key) { this.key = nonNull(key); } /** * Sends a message to one device, retrying in case of unavailability. * * <p> * <strong>Note: </strong> this method uses exponential back-off to retry in * case of service unavailability and hence could block the calling thread * for many seconds. * * @param message message to be sent, including the device's registration id. * @param registrationId device where the message will be sent. * @param retries number of retries in case of service unavailability errors. * * @return result of the request (see its javadoc for more details). * * @throws IllegalArgumentException if registrationId is {@literal null}. * @throws InvalidRequestException if GCM didn't returned a 200 or 5xx status. * @throws IOException if message could not be sent. */ public Result send(Message message, String registrationId, int retries) throws IOException { int attempt = 0; Result result = null; int backoff = BACKOFF_INITIAL_DELAY; boolean tryAgain; do { attempt++; if (logger.isLoggable(Level.FINE)) { logger.fine("Attempt #" + attempt + " to send message " + message + " to regIds " + registrationId); } result = sendNoRetry(message, registrationId); tryAgain = result == null && attempt <= retries; if (tryAgain) { int sleepTime = backoff / 2 + random.nextInt(backoff); sleep(sleepTime); if (2 * backoff < MAX_BACKOFF_DELAY) { backoff *= 2; } } } while (tryAgain); if (result == null) { throw new IOException("Could not send message after " + attempt + " attempts"); } return result; } /** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, String, int)} for more info. * * @return result of the post, or {@literal null} if the GCM service was * unavailable or any network exception caused the request to fail. * * @throws InvalidRequestException if GCM didn't returned a 200 or 5xx status. * @throws IllegalArgumentException if registrationId is {@literal null}. */ public Result sendNoRetry(Message message, String registrationId) throws IOException { StringBuilder body = newBody(PARAM_REGISTRATION_ID, registrationId); Boolean delayWhileIdle = message.isDelayWhileIdle(); if (delayWhileIdle != null) { addParameter(body, PARAM_DELAY_WHILE_IDLE, delayWhileIdle ? "1" : "0"); } Boolean dryRun = message.isDryRun(); if (dryRun != null) { addParameter(body, PARAM_DRY_RUN, dryRun ? "1" : "0"); } String collapseKey = message.getCollapseKey(); if (collapseKey != null) { addParameter(body, PARAM_COLLAPSE_KEY, collapseKey); } String restrictedPackageName = message.getRestrictedPackageName(); if (restrictedPackageName != null) { addParameter(body, PARAM_RESTRICTED_PACKAGE_NAME, restrictedPackageName); } Integer timeToLive = message.getTimeToLive(); if (timeToLive != null) { addParameter(body, PARAM_TIME_TO_LIVE, Integer.toString(timeToLive)); } for (Entry<String, String> entry : message.getData().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (key == null || value == null) { logger.warning("Ignoring payload entry thas has null: " + entry); } else { key = PARAM_PAYLOAD_PREFIX + key; addParameter(body, key, URLEncoder.encode(value, UTF8)); } } String requestBody = body.toString(); logger.finest("Request body: " + requestBody); HttpURLConnection conn; int status; try { conn = post(GCM_SEND_ENDPOINT, requestBody); status = conn.getResponseCode(); } catch (IOException e) { logger.log(Level.FINE, "IOException posting to GCM", e); return null; } if (status / 100 == 5) { logger.fine("GCM service is unavailable (status " + status + ")"); return null; } String responseBody; if (status != 200) { try { responseBody = getAndClose(conn.getErrorStream()); logger.finest("Plain post error response: " + responseBody); } catch (IOException e) { // ignore the exception since it will thrown an InvalidRequestException // anyways responseBody = "N/A"; logger.log(Level.FINE, "Exception reading response: ", e); } throw new InvalidRequestException(status, responseBody); } else { try { responseBody = getAndClose(conn.getInputStream()); } catch (IOException e) { logger.log(Level.WARNING, "Exception reading response: ", e); // return null so it can retry return null; } } String[] lines = responseBody.split("\n"); if (lines.length == 0 || lines[0].equals("")) { throw new IOException("Received empty response from GCM service."); } String firstLine = lines[0]; String[] responseParts = split(firstLine); String token = responseParts[0]; String value = responseParts[1]; if (token.equals(TOKEN_MESSAGE_ID)) { Builder builder = new Result.Builder().messageId(value); // check for canonical registration id if (lines.length > 1) { String secondLine = lines[1]; responseParts = split(secondLine); token = responseParts[0]; value = responseParts[1]; if (token.equals(TOKEN_CANONICAL_REG_ID)) { builder.canonicalRegistrationId(value); } else { logger.warning("Invalid response from GCM: " + responseBody); } } Result result = builder.build(); if (logger.isLoggable(Level.FINE)) { logger.fine("Message created succesfully (" + result + ")"); } return result; } else if (token.equals(TOKEN_ERROR)) { return new Result.Builder().errorCode(value).build(); } else { throw new IOException("Invalid response from GCM: " + responseBody); } } /** * Sends a message to many devices, retrying in case of unavailability. * * <p> * <strong>Note: </strong> this method uses exponential back-off to retry in * case of service unavailability and hence could block the calling thread * for many seconds. * * @param message message to be sent. * @param regIds registration id of the devices that will receive * the message. * @param retries number of retries in case of service unavailability errors. * * @return combined result of all requests made. * * @throws IllegalArgumentException if registrationIds is {@literal null} or * empty. * @throws InvalidRequestException if GCM didn't returned a 200 or 503 status. * @throws IOException if message could not be sent. */ public MulticastResult send(Message message, List<String> regIds, int retries) throws IOException { int attempt = 0; MulticastResult multicastResult; int backoff = BACKOFF_INITIAL_DELAY; // Map of results by registration id, it will be updated after each attempt // to send the messages Map<String, Result> results = new HashMap<String, Result>(); List<String> unsentRegIds = new ArrayList<String>(regIds); boolean tryAgain; List<Long> multicastIds = new ArrayList<Long>(); do { multicastResult = null; attempt++; if (logger.isLoggable(Level.FINE)) { logger.fine("Attempt #" + attempt + " to send message " + message + " to regIds " + unsentRegIds); } try { multicastResult = sendNoRetry(message, unsentRegIds); } catch(IOException e) { // no need for WARNING since exception might be already logged logger.log(Level.FINEST, "IOException on attempt " + attempt, e); } if (multicastResult != null) { long multicastId = multicastResult.getMulticastId(); logger.fine("multicast_id on attempt # " + attempt + ": " + multicastId); multicastIds.add(multicastId); unsentRegIds = updateStatus(unsentRegIds, results, multicastResult); tryAgain = !unsentRegIds.isEmpty() && attempt <= retries; } else { tryAgain = attempt <= retries; } if (tryAgain) { int sleepTime = backoff / 2 + random.nextInt(backoff); sleep(sleepTime); if (2 * backoff < MAX_BACKOFF_DELAY) { backoff *= 2; } } } while (tryAgain); if (multicastIds.isEmpty()) { // all JSON posts failed due to GCM unavailability throw new IOException("Could not post JSON requests to GCM after " + attempt + " attempts"); } // calculate summary int success = 0, failure = 0 , canonicalIds = 0; for (Result result : results.values()) { if (result.getMessageId() != null) { success++; if (result.getCanonicalRegistrationId() != null) { canonicalIds++; } } else { failure++; } } // build a new object with the overall result long multicastId = multicastIds.remove(0); MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds, multicastId).retryMulticastIds(multicastIds); // add results, in the same order as the input for (String regId : regIds) { Result result = results.get(regId); builder.addResult(result); } return builder.build(); } /** * Updates the status of the messages sent to devices and the list of devices * that should be retried. * * @param unsentRegIds list of devices that are still pending an update. * @param allResults map of status that will be updated. * @param multicastResult result of the last multicast sent. * * @return updated version of devices that should be retried. */ private List<String> updateStatus(List<String> unsentRegIds, Map<String, Result> allResults, MulticastResult multicastResult) { List<Result> results = multicastResult.getResults(); if (results.size() != unsentRegIds.size()) { // should never happen, unless there is a flaw in the algorithm throw new RuntimeException("Internal error: sizes do not match. " + "currentResults: " + results + "; unsentRegIds: " + unsentRegIds); } List<String> newUnsentRegIds = new ArrayList<String>(); for (int i = 0; i < unsentRegIds.size(); i++) { String regId = unsentRegIds.get(i); Result result = results.get(i); allResults.put(regId, result); String error = result.getErrorCodeName(); if (error != null && (error.equals(Constants.ERROR_UNAVAILABLE) || error.equals(Constants.ERROR_INTERNAL_SERVER_ERROR))) { newUnsentRegIds.add(regId); } } return newUnsentRegIds; } /** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, List, int)} for more info. * * @return multicast results if the message was sent successfully, * {@literal null} if it failed but could be retried. * * @throws IllegalArgumentException if registrationIds is {@literal null} or * empty. * @throws InvalidRequestException if GCM didn't returned a 200 status. * @throws IOException if there was a JSON parsing error */ public MulticastResult sendNoRetry(Message message, List<String> registrationIds) throws IOException { if (nonNull(registrationIds).isEmpty()) { throw new IllegalArgumentException("registrationIds cannot be empty"); } Map<Object, Object> jsonRequest = new HashMap<Object, Object>(); setJsonField(jsonRequest, PARAM_TIME_TO_LIVE, message.getTimeToLive()); setJsonField(jsonRequest, PARAM_COLLAPSE_KEY, message.getCollapseKey()); setJsonField(jsonRequest, PARAM_RESTRICTED_PACKAGE_NAME, message.getRestrictedPackageName()); setJsonField(jsonRequest, PARAM_DELAY_WHILE_IDLE, message.isDelayWhileIdle()); setJsonField(jsonRequest, PARAM_DRY_RUN, message.isDryRun()); jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds); Map<String, String> payload = message.getData(); if (!payload.isEmpty()) { jsonRequest.put(JSON_PAYLOAD, payload); } String requestBody = JSONValue.toJSONString(jsonRequest); logger.finest("JSON request: " + requestBody); HttpURLConnection conn; int status; try { conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody); status = conn.getResponseCode(); } catch (IOException e) { logger.log(Level.FINE, "IOException posting to GCM", e); return null; } String responseBody; if (status != 200) { try { responseBody = getAndClose(conn.getErrorStream()); logger.finest("JSON error response: " + responseBody); } catch (IOException e) { // ignore the exception since it will thrown an InvalidRequestException // anyways responseBody = "N/A"; logger.log(Level.FINE, "Exception reading response: ", e); } throw new InvalidRequestException(status, responseBody); } try { responseBody = getAndClose(conn.getInputStream()); } catch(IOException e) { logger.log(Level.WARNING, "IOException reading response", e); return null; } logger.finest("JSON response: " + responseBody); JSONParser parser = new JSONParser(); JSONObject jsonResponse; try { jsonResponse = (JSONObject) parser.parse(responseBody); int success = getNumber(jsonResponse, JSON_SUCCESS).intValue(); int failure = getNumber(jsonResponse, JSON_FAILURE).intValue(); int canonicalIds = getNumber(jsonResponse, JSON_CANONICAL_IDS).intValue(); long multicastId = getNumber(jsonResponse, JSON_MULTICAST_ID).longValue(); MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds, multicastId); @SuppressWarnings("unchecked") List<Map<String, Object>> results = (List<Map<String, Object>>) jsonResponse.get(JSON_RESULTS); if (results != null) { for (Map<String, Object> jsonResult : results) { String messageId = (String) jsonResult.get(JSON_MESSAGE_ID); String canonicalRegId = (String) jsonResult.get(TOKEN_CANONICAL_REG_ID); String error = (String) jsonResult.get(JSON_ERROR); Result result = new Result.Builder() .messageId(messageId) .canonicalRegistrationId(canonicalRegId) .errorCode(error) .build(); builder.addResult(result); } } MulticastResult multicastResult = builder.build(); return multicastResult; } catch (ParseException e) { throw newIoException(responseBody, e); } catch (CustomParserException e) { throw newIoException(responseBody, e); } } private IOException newIoException(String responseBody, Exception e) { // log exception, as IOException constructor that takes a message and cause // is only available on Java 6 String msg = "Error parsing JSON response (" + responseBody + ")"; logger.log(Level.WARNING, msg, e); return new IOException(msg + ":" + e); } private static void close(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { // ignore error logger.log(Level.FINEST, "IOException closing stream", e); } } } /** * Sets a JSON field, but only if the value is not {@literal null}. */ private void setJsonField(Map<Object, Object> json, String field, Object value) { if (value != null) { json.put(field, value); } } private Number getNumber(Map<?, ?> json, String field) { Object value = json.get(field); if (value == null) { throw new CustomParserException("Missing field: " + field); } if (!(value instanceof Number)) { throw new CustomParserException("Field " + field + " does not contain a number: " + value); } return (Number) value; } class CustomParserException extends RuntimeException { CustomParserException(String message) { super(message); } } private String[] split(String line) throws IOException { String[] split = line.split("=", 2); if (split.length != 2) { throw new IOException("Received invalid response line from GCM: " + line); } return split; } /** * Make an HTTP post to a given URL. * * @return HTTP response. */ protected HttpURLConnection post(String url, String body) throws IOException { return post(url, "application/x-www-form-urlencoded;charset=UTF-8", body); } /** * Makes an HTTP POST request to a given endpoint. * * <p> * <strong>Note: </strong> the returned connected should not be disconnected, * otherwise it would kill persistent connections made using Keep-Alive. * * @param url endpoint to post the request. * @param contentType type of request. * @param body body of the request. * * @return the underlying connection. * * @throws IOException propagated from underlying methods. */ protected HttpURLConnection post(String url, String contentType, String body) throws IOException { if (url == null || body == null) { throw new IllegalArgumentException("arguments cannot be null"); } if (!url.startsWith("https://")) { logger.warning("URL does not use https: " + url); } logger.fine("Sending POST to " + url); logger.finest("POST body: " + body); byte[] bytes = body.getBytes(); HttpURLConnection conn = getConnection(url); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("Authorization", "key=" + key); OutputStream out = conn.getOutputStream(); try { out.write(bytes); } finally { close(out); } return conn; } /** * Creates a map with just one key-value pair. */ protected static final Map<String, String> newKeyValues(String key, String value) { Map<String, String> keyValues = new HashMap<String, String>(1); keyValues.put(nonNull(key), nonNull(value)); return keyValues; } /** * Creates a {@link StringBuilder} to be used as the body of an HTTP POST. * * @param name initial parameter for the POST. * @param value initial value for that parameter. * @return StringBuilder to be used an HTTP POST body. */ protected static StringBuilder newBody(String name, String value) { return new StringBuilder(nonNull(name)).append('=').append(nonNull(value)); } /** * Adds a new parameter to the HTTP POST body. * * @param body HTTP POST body. * @param name parameter's name. * @param value parameter's value. */ protected static void addParameter(StringBuilder body, String name, String value) { nonNull(body).append('&') .append(nonNull(name)).append('=').append(nonNull(value)); } /** * Gets an {@link HttpURLConnection} given an URL. */ protected HttpURLConnection getConnection(String url) throws IOException { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); return conn; } /** * Convenience method to convert an InputStream to a String. * <p> * If the stream ends in a newline character, it will be stripped. * <p> * If the stream is {@literal null}, returns an empty string. */ protected static String getString(InputStream stream) throws IOException { if (stream == null) { return ""; } BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder content = new StringBuilder(); String newLine; do { newLine = reader.readLine(); if (newLine != null) { content.append(newLine).append('\n'); } } while (newLine != null); if (content.length() > 0) { // strip last newline content.setLength(content.length() - 1); } return content.toString(); } private static String getAndClose(InputStream stream) throws IOException { try { return getString(stream); } finally { if (stream != null) { close(stream); } } } static <T> T nonNull(T argument) { if (argument == null) { throw new IllegalArgumentException("argument cannot be null"); } return argument; } void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import java.io.Serializable; /** * Result of a GCM message request that returned HTTP status code 200. * * <p> * If the message is successfully created, the {@link #getMessageId()} returns * the message id and {@link #getErrorCodeName()} returns {@literal null}; * otherwise, {@link #getMessageId()} returns {@literal null} and * {@link #getErrorCodeName()} returns the code of the error. * * <p> * There are cases when a request is accept and the message successfully * created, but GCM has a canonical registration id for that device. In this * case, the server should update the registration id to avoid rejected requests * in the future. * * <p> * In a nutshell, the workflow to handle a result is: * <pre> * - Call {@link #getMessageId()}: * - {@literal null} means error, call {@link #getErrorCodeName()} * - non-{@literal null} means the message was created: * - Call {@link #getCanonicalRegistrationId()} * - if it returns {@literal null}, do nothing. * - otherwise, update the server datastore with the new id. * </pre> */ public final class Result implements Serializable { private final String messageId; private final String canonicalRegistrationId; private final String errorCode; public static final class Builder { // optional parameters private String messageId; private String canonicalRegistrationId; private String errorCode; public Builder canonicalRegistrationId(String value) { canonicalRegistrationId = value; return this; } public Builder messageId(String value) { messageId = value; return this; } public Builder errorCode(String value) { errorCode = value; return this; } public Result build() { return new Result(this); } } private Result(Builder builder) { canonicalRegistrationId = builder.canonicalRegistrationId; messageId = builder.messageId; errorCode = builder.errorCode; } /** * Gets the message id, if any. */ public String getMessageId() { return messageId; } /** * Gets the canonical registration id, if any. */ public String getCanonicalRegistrationId() { return canonicalRegistrationId; } /** * Gets the error code, if any. */ public String getErrorCodeName() { return errorCode; } @Override public String toString() { StringBuilder builder = new StringBuilder("["); if (messageId != null) { builder.append(" messageId=").append(messageId); } if (canonicalRegistrationId != null) { builder.append(" canonicalRegistrationId=") .append(canonicalRegistrationId); } if (errorCode != null) { builder.append(" errorCode=").append(errorCode); } return builder.append(" ]").toString(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Result of a GCM multicast message request . */ public final class MulticastResult implements Serializable { private final int success; private final int failure; private final int canonicalIds; private final long multicastId; private final List<Result> results; private final List<Long> retryMulticastIds; public static final class Builder { private final List<Result> results = new ArrayList<Result>(); // required parameters private final int success; private final int failure; private final int canonicalIds; private final long multicastId; // optional parameters private List<Long> retryMulticastIds; public Builder(int success, int failure, int canonicalIds, long multicastId) { this.success = success; this.failure = failure; this.canonicalIds = canonicalIds; this.multicastId = multicastId; } public Builder addResult(Result result) { results.add(result); return this; } public Builder retryMulticastIds(List<Long> retryMulticastIds) { this.retryMulticastIds = retryMulticastIds; return this; } public MulticastResult build() { return new MulticastResult(this); } } private MulticastResult(Builder builder) { success = builder.success; failure = builder.failure; canonicalIds = builder.canonicalIds; multicastId = builder.multicastId; results = Collections.unmodifiableList(builder.results); List<Long> tmpList = builder.retryMulticastIds; if (tmpList == null) { tmpList = Collections.emptyList(); } retryMulticastIds = Collections.unmodifiableList(tmpList); } /** * Gets the multicast id. */ public long getMulticastId() { return multicastId; } /** * Gets the number of successful messages. */ public int getSuccess() { return success; } /** * Gets the total number of messages sent, regardless of the status. */ public int getTotal() { return success + failure; } /** * Gets the number of failed messages. */ public int getFailure() { return failure; } /** * Gets the number of successful messages that also returned a canonical * registration id. */ public int getCanonicalIds() { return canonicalIds; } /** * Gets the results of each individual message, which is immutable. */ public List<Result> getResults() { return results; } /** * Gets additional ids if more than one multicast message was sent. */ public List<Long> getRetryMulticastIds() { return retryMulticastIds; } @Override public String toString() { StringBuilder builder = new StringBuilder("MulticastResult(") .append("multicast_id=").append(multicastId).append(",") .append("total=").append(getTotal()).append(",") .append("success=").append(success).append(",") .append("failure=").append(failure).append(",") .append("canonical_ids=").append(canonicalIds).append(","); if (!results.isEmpty()) { builder.append("results: " + results); } return builder.toString(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; /** * Constants used on GCM service communication. */ public final class Constants { /** * Endpoint for sending messages. */ public static final String GCM_SEND_ENDPOINT = "https://android.googleapis.com/gcm/send"; /** * HTTP parameter for registration id. */ public static final String PARAM_REGISTRATION_ID = "registration_id"; /** * HTTP parameter for collapse key. */ public static final String PARAM_COLLAPSE_KEY = "collapse_key"; /** * HTTP parameter for delaying the message delivery if the device is idle. */ public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle"; /** * HTTP parameter for telling gcm to validate the message without actually sending it. */ public static final String PARAM_DRY_RUN = "dry_run"; /** * HTTP parameter for package name that can be used to restrict message delivery by matching * against the package name used to generate the registration id. */ public static final String PARAM_RESTRICTED_PACKAGE_NAME = "restricted_package_name"; /** * Prefix to HTTP parameter used to pass key-values in the message payload. */ public static final String PARAM_PAYLOAD_PREFIX = "data."; /** * Prefix to HTTP parameter used to set the message time-to-live. */ public static final String PARAM_TIME_TO_LIVE = "time_to_live"; /** * Too many messages sent by the sender. Retry after a while. */ public static final String ERROR_QUOTA_EXCEEDED = "QuotaExceeded"; /** * Too many messages sent by the sender to a specific device. * Retry after a while. */ public static final String ERROR_DEVICE_QUOTA_EXCEEDED = "DeviceQuotaExceeded"; /** * Missing registration_id. * Sender should always add the registration_id to the request. */ public static final String ERROR_MISSING_REGISTRATION = "MissingRegistration"; /** * Bad registration_id. Sender should remove this registration_id. */ public static final String ERROR_INVALID_REGISTRATION = "InvalidRegistration"; /** * The sender_id contained in the registration_id does not match the * sender_id used to register with the GCM servers. */ public static final String ERROR_MISMATCH_SENDER_ID = "MismatchSenderId"; /** * The user has uninstalled the application or turned off notifications. * Sender should stop sending messages to this device and delete the * registration_id. The client needs to re-register with the GCM servers to * receive notifications again. */ public static final String ERROR_NOT_REGISTERED = "NotRegistered"; /** * The payload of the message is too big, see the limitations. * Reduce the size of the message. */ public static final String ERROR_MESSAGE_TOO_BIG = "MessageTooBig"; /** * Collapse key is required. Include collapse key in the request. */ public static final String ERROR_MISSING_COLLAPSE_KEY = "MissingCollapseKey"; /** * A particular message could not be sent because the GCM servers were not * available. Used only on JSON requests, as in plain text requests * unavailability is indicated by a 503 response. */ public static final String ERROR_UNAVAILABLE = "Unavailable"; /** * A particular message could not be sent because the GCM servers encountered * an error. Used only on JSON requests, as in plain text requests internal * errors are indicated by a 500 response. */ public static final String ERROR_INTERNAL_SERVER_ERROR = "InternalServerError"; /** * Time to Live value passed is less than zero or more than maximum. */ public static final String ERROR_INVALID_TTL= "InvalidTtl"; /** * Token returned by GCM when a message was successfully sent. */ public static final String TOKEN_MESSAGE_ID = "id"; /** * Token returned by GCM when the requested registration id has a canonical * value. */ public static final String TOKEN_CANONICAL_REG_ID = "registration_id"; /** * Token returned by GCM when there was an error sending a message. */ public static final String TOKEN_ERROR = "Error"; /** * JSON-only field representing the registration ids. */ public static final String JSON_REGISTRATION_IDS = "registration_ids"; /** * JSON-only field representing the payload data. */ public static final String JSON_PAYLOAD = "data"; /** * JSON-only field representing the number of successful messages. */ public static final String JSON_SUCCESS = "success"; /** * JSON-only field representing the number of failed messages. */ public static final String JSON_FAILURE = "failure"; /** * JSON-only field representing the number of messages with a canonical * registration id. */ public static final String JSON_CANONICAL_IDS = "canonical_ids"; /** * JSON-only field representing the id of the multicast request. */ public static final String JSON_MULTICAST_ID = "multicast_id"; /** * JSON-only field representing the result of each individual request. */ public static final String JSON_RESULTS = "results"; /** * JSON-only field representing the error field of an individual request. */ public static final String JSON_ERROR = "error"; /** * JSON-only field sent by GCM when a message was successfully sent. */ public static final String JSON_MESSAGE_ID = "message_id"; private Constants() { throw new UnsupportedOperationException(); } }
Java
package bean; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JLabel; import javax.swing.Timer; public class JLabelCronometro2 extends JLabel implements ActionListener{ Timer timer; private int segundos=0; private int minutos=0; private int horas=0; private boolean congelado=false; public JLabelCronometro2(){ timer=new Timer(1000,this); this.setText(horas+":"+minutos+":"+segundos); this.setForeground(Color.RED); this.setBackground(Color.WHITE); } public JLabelCronometro2(int hora, int minuto,int segundo){ timer=new Timer(1000,this); this.setText(horas+":"+minutos+":"+segundos); setHoras(hora); setMinutos(minuto); setSegundos(segundo); this.setForeground(Color.RED); this.setBackground(Color.WHITE); } public int getSegundos() { return segundos; } public void setSegundos(int segundos) { this.segundos = segundos; } public int getMinutos() { return minutos; } public void setMinutos(int minutos) { this.minutos = minutos; } public int getHoras() { return horas; } public void setHoras(int horas) { this.horas = horas; } public void iniciarCronometro() { if (congelado) { } else { timer.start(); } } public boolean cronometroEnMarcha(){ return timer.isRunning(); } public void detenerse() { timer.stop(); } public void reiniciarCronometro(){ timer.stop(); segundos=0; minutos=0; horas=0; this.setText(horas+":"+minutos+":"+segundos); } public void actionPerformed(ActionEvent e){ segundos++; if (segundos<=59){ this.setText(horas+":"+minutos+":"+segundos); } else{ minutos++; segundos=0; this.setText(horas+":"+minutos+":"+segundos); if (minutos==60){ minutos=0; horas++; this.setText(horas+":"+minutos+":"+segundos); } } } }
Java
package bean; import javax.swing.ImageIcon; public class JImageIcon { public ImageIcon crearImageIcon(String ruta) { java.net.URL imgenURL = getClass().getClassLoader().getResource(ruta); if (imgenURL != null) { return new ImageIcon(imgenURL, ""); } else { System.err.println("No se puede encontrar el archivo: " + ruta); return null; } } }
Java
package modelo; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Vector; public class FraseDAO { public FraseDAO() { super(); } public void registrarFrase(Frase frase){ String tiraSQL = "INSERT INTO frase"+ "(idfrase, descripcion, nivel) "+ "VALUES("+ ""+frase.getidFrase()+", '"+frase.getDescripcion()+ "', "+frase.getNivel().getIdnivel()+" )"; Conexion.ejecutar(tiraSQL); } public Vector<String> leerFrase(int nivel){ Vector<String> vectorFrases = new Vector<String>(); String tiraSQL = "SELECT descripcion FROM frase WHERE nivel='"+nivel+"'"; ResultSet resultSet = Conexion.consultar(tiraSQL); try{ while( resultSet.next() ){ String descripcion = resultSet.getString("descripcion"); vectorFrases.add(descripcion); } } catch(SQLException e) { e.printStackTrace(); } return vectorFrases; } public int generarNumeroFrase(){ int numero=0; String tiraSQL = "SELECT count(idfrase) AS cuantos FROM frase"; ResultSet resultSet = Conexion.consultar(tiraSQL); try{ if(resultSet.next()){ numero = resultSet.getInt("cuantos"); } } catch(SQLException e){ e.printStackTrace(); } return numero+1; } }
Java
package bean; import javax.swing.ImageIcon; public class EtiquetaImagen { public ImageIcon crearImageIcon(String ruta) { java.net.URL imgenURL = getClass().getClassLoader().getResource(ruta); if (imgenURL != null) { return new ImageIcon(imgenURL, ""); } else { System.err.println("No se puede encontrar el archivo: " + ruta); return null; } } }
Java
package bean; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JLabel; import javax.swing.Timer; public class JLabelCronometro extends JLabel implements ActionListener{ /** * */ private static final long serialVersionUID = 1L; Timer timer; private int segundos=0; private int minutos=0; private int horas=0; private boolean pausado=false; public JLabelCronometro(){ timer=new Timer(1000,this); this.setText("Tiempo"); this.setForeground(Color.RED); } public JLabelCronometro(int hora, int minuto,int segundo){ timer=new Timer(1000,this); this.setText(horas+":"+minutos+":"+segundos); setHoras(hora); setMinutos(minuto); setSegundos(segundo); this.setForeground(Color.RED); this.setBackground(Color.WHITE); } public int getSegundos() { return segundos; } public void setSegundos(int segundos) { this.segundos = segundos; } public int getMinutos() { return minutos; } public void setMinutos(int minutos) { this.minutos = minutos; } public int getHoras() { return horas; } public void setHoras(int horas) { this.horas = horas; } public void iniciarCronometro() { if (pausado) { } else { timer.start(); } } public boolean cronometroEnMarcha(){ return timer.isRunning(); } public void detenerse() { timer.stop(); } public void reiniciarCronometro(){ timer.stop(); segundos=0; minutos=0; horas=0; this.setText(horas+":"+minutos+":"+segundos); } public void actionPerformed(ActionEvent e){ segundos++; if (segundos<=59){ this.setText(horas+":"+minutos+":"+segundos); } else{ minutos++; segundos=0; this.setText(horas+":"+minutos+":"+segundos); if (minutos==60){ minutos=0; horas++; this.setText(horas+":"+minutos+":"+segundos); } } } }
Java
package vista; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Vector; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.WindowConstants; import javax.swing.SwingUtilities; import modelo.FraseDAO; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class prueba extends javax.swing.JFrame implements ActionListener { private JLabel lblPalabra; private Vector<FraseDAO> frases; FraseDAO fraseDAO; private JButton btnBuscar; private JTextField txtLetra; /** * Auto-generated main method to display this JFrame */ /*public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { prueba inst = new prueba(); inst.setLocationRelativeTo(null); inst.setVisible(true); } }); }*/ public prueba() { super(); fraseDAO = new FraseDAO(); fraseDAO.leerFrase(1); //frases = fraseDAO.obtenerFrase(); //System.out.println("numero de palabras: "+frases.size()); initGUI(); fraseDAO= frases.get(0); //actualizar(fraseDAO.separarFrase()); } public void actualizar(String palabra){ this.lblPalabra.setText( palabra ); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); { lblPalabra = new JLabel(); getContentPane().add(lblPalabra); lblPalabra.setText("MANOLO"); lblPalabra.setBounds(12, 182, 554, 65); lblPalabra.setFont(new java.awt.Font("Segoe UI",1,26)); } { txtLetra = new JTextField(); getContentPane().add(txtLetra); txtLetra.setBounds(26, 76, 121, 23); } { btnBuscar = new JButton(); getContentPane().add(btnBuscar); btnBuscar.setText("Buscar"); btnBuscar.setBounds(173, 76, 90, 23); btnBuscar.setActionCommand("buscar"); btnBuscar.addActionListener(this); } pack(); this.setSize(592, 333); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } public String getLetra(){ return this.txtLetra.getText().toLowerCase(); } public void actionPerformed(ActionEvent e) { if ( "buscar".equals(e.getActionCommand()) ) { /*Buscamos si existe la letra en palabra.*/ //if( fraseDAO.buscarLetra(getLetra()) ){ //System.out.println("x teclado: "+getLetra()); //System.out.println("x BD: "+fraseDAO); //fraseDAO.revelarFrase(); //actualizar( fraseDAO.separarFrase() ); //} } /*Borramos los campos de texto.*/ txtLetra.setText(""); } }
Java
package controlador; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import vista.VentanaMenu; public class ControladorVentanaMenu implements ActionListener{ private VentanaMenu ventanaMenu; public ControladorVentanaMenu() { super(); this.ventanaMenu = new VentanaMenu(); this.ventanaMenu.setLocationRelativeTo(null); this.ventanaMenu.setVisible(true); this.ventanaMenu.addListener(this); } @Override public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand(); if (actionCommand.equals("Salir")) { System.exit(0); } else if (actionCommand.equals("Nueva Frase")) { new ControladorVentanaFrase(); } else if (actionCommand.equals("JUGAR")) { new ControladorVentanaNivel(); } else if (actionCommand.equals("Listado")) { new ControladorVentanaListado(); } } }
Java
package controlador; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import modelo.Frase; import modelo.FraseDAO; import modelo.Nivel; import modelo.NivelDAO; import vista.VentanaFrase; public class ControladorVentanaFrase implements ActionListener { private VentanaFrase ventanaFrase; private NivelDAO nivelDAO = new NivelDAO(); private FraseDAO fraseDAO = new FraseDAO(); public ControladorVentanaFrase() { super(); // TODO Auto-generated constructor stub ventanaFrase = VentanaFrase.getInstancia(); ventanaFrase.setVisible(true); ventanaFrase.addListener(this); ventanaFrase.setCodigoFrase(String.valueOf(fraseDAO.generarNumeroFrase())); ventanaFrase.cargarComboNivel(nivelDAO.llenarComboNivel()); } public void guardarFrase(){ try { if(ventanaFrase.getCodigoFrase().equals("") || ventanaFrase.getDescripcion().equals("") ) ventanaFrase.mostrarMensaje("Debe llenar todos los datos para poder registrar una frase"); else { String codigo = ventanaFrase.getCodigoFrase(); String descripcion = ventanaFrase.getDescripcion(); String descripcionNivel = ventanaFrase.getNivel(); Nivel nivel = nivelDAO.buscarNivel(descripcionNivel); Frase frase = new Frase(Integer.parseInt(codigo), descripcion, nivel); fraseDAO.registrarFrase(frase); ventanaFrase.mostrarMensaje("La frase fue registrada exitosamente"); ventanaFrase.borrarDatos(); int numero = Integer.parseInt(ventanaFrase.getCodigoFrase())+1; ventanaFrase.setCodigoFrase(String.valueOf(numero)); } } catch(Exception e) { ventanaFrase.mostrarMensaje("No se pudo registrar la categoria, verifique que los datos sean correctos"); ventanaFrase.borrarDatos(); } } @Override public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand(); if ( e.getSource() == ventanaFrase.getComboNivel() ){ String descripcionNivel = ventanaFrase.getNivel(); int tamano = 0; if ( descripcionNivel.equals("basico") ){ tamano = 10; } else if ( descripcionNivel.equals("intermedio") ) tamano = 30; else if ( descripcionNivel.equals("avanzado")) tamano = 60; ventanaFrase.actualizarTamanoDescripcion(tamano); } else if (actionCommand.equals("Guardar")){ guardarFrase(); } else if (actionCommand.equals("Cancelar")) { ventanaFrase.borrarDatos(); } else if (actionCommand.equals("Salir")){ this.ventanaFrase.setVisible(false); } } }
Java
package controlador; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Time; import java.text.SimpleDateFormat; import java.util.Enumeration; import java.util.Locale; import java.util.Vector; import modelo.FraseDAO; import modelo.JugadorDAO; import vista.VentanaJugar; public class ControladorVentanaJugar implements ActionListener { private VentanaJugar ventanaJugar; private Vector<String> vectorFrases; private Vector<ControladorVentanaJugar> frases; private String frase; private FraseDAO fraseDAO; ControladorVentanaJugar controlador; private int nivel; int oportunidades=8; private Vector<Integer> indices = new Vector<Integer>(); private int indice; private int numeroJuegos; private JugadorDAO jugadorDAO; public ControladorVentanaJugar(int nivel) { super(); ventanaJugar = new VentanaJugar(); ventanaJugar.setVisible(true); ventanaJugar.addListener(this); fraseDAO = new FraseDAO(); this.nivel=nivel; ventanaJugar.getCrono().reiniciarCronometro(); frases = obtenerFrase(); int aleatorio = generarAleatorio(); controlador = frases.get(aleatorio); indices.add(aleatorio); ventanaJugar.actualizarFrase(controlador.separarFrase()); ventanaJugar.getCrono().iniciarCronometro(); numeroJuegos = 0; jugadorDAO = new JugadorDAO(); } public ControladorVentanaJugar (String frase) { vectorFrases = new Vector<String>(); for (int i = 0; i < frase.length(); i ++){ if (frase.charAt(i) == ' ') vectorFrases.add(""); else vectorFrases.add("_"); } this.frase = frase.toLowerCase(); } public Vector<ControladorVentanaJugar> obtenerFrase() { Vector<ControladorVentanaJugar> frases = new Vector<ControladorVentanaJugar>(); vectorFrases = fraseDAO.leerFrase(nivel); String[] cantidad = (String[])vectorFrases.toArray(new String[vectorFrases.size()]); for ( int i = 0; i < cantidad.length; i ++ ) frases.add( new ControladorVentanaJugar( cantidad[i] ) ); return frases; } public String separarFrase() { String separada = ""; for ( Enumeration noSeparada = vectorFrases.elements(); noSeparada.hasMoreElements(); ) separada += noSeparada.nextElement()+" "; return separada; } public boolean buscarLetra( String letra) { boolean encontro = false; if ( letra.length() != 0 ){ letra = ""+letra.toLowerCase().charAt(0); for ( int i = 0; i < frase.length() ; i ++ ) if ( frase.charAt(i) == letra.charAt(0) ){ vectorFrases.setElementAt(letra,i); encontro = true; } } return encontro; } public boolean buscarFrase( String palabra ) { boolean encontro = false; if ( frase.equals(palabra) ) encontro = true; if ( encontro ) for ( int j = 0; j < frase.length(); j ++ ) vectorFrases.set(j, String.valueOf(frase.charAt(j))); return encontro; } public int generarAleatorio() { int numero = vectorFrases.size(); return (int) (Math.random()*numero); } public int siguienteAleatorio() { int siguiente = generarAleatorio(); while (indices.contains(siguiente)) siguiente = generarAleatorio(); return siguiente; } public void resultadoDelJuego() { numeroJuegos ++; if( numeroJuegos != frases.size() ){ this.indice = siguienteAleatorio(); controlador = frases.get(indice); indices.add(indice); this.oportunidades = 8; ventanaJugar.actualizarFrase(controlador.separarFrase()); } else { ventanaJugar.cambioDeNivel(); ventanaJugar.setVisible(false); } } public Time convertirHora(String horaString) { Time fechaFormatoTime = null; try { SimpleDateFormat sdf = new java.text.SimpleDateFormat("hh:mm:ss", new Locale("es", "ES")); fechaFormatoTime = new java.sql.Time(sdf.parse(horaString).getTime()); } catch (Exception ex) { System.out.println("Error al obtener el formato de la fecha/hora: " + ex.getMessage()); } return fechaFormatoTime; } @Override public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand(); if (actionCommand.equals("Ok")) { if (ventanaJugar.getLetra().equals("")) { ventanaJugar.mostrarMensaje("Introduce una letra"); } else { if (controlador.buscarLetra(ventanaJugar.getLetra())) { ventanaJugar.actualizarFrase(controlador.separarFrase()); } else { ventanaJugar.mostrandoHomero(oportunidades); oportunidades--; ventanaJugar.oportunidadesRestantes(String.valueOf(oportunidades)); if (oportunidades == 0) { ventanaJugar.getCrono().detenerse(); ventanaJugar.mostrarMensajePerdio(); resultadoDelJuego(); oportunidades=8; ventanaJugar.oportunidadesRestantes(String.valueOf(oportunidades)); ventanaJugar.imagenInvisible(); } } } if (!controlador.vectorFrases.contains("_")){ ventanaJugar.actualizarFrase(controlador.separarFrase()); ventanaJugar.getCrono().detenerse(); ventanaJugar.mostrarMensaje("Felicidades has ganado :D"); resultadoDelJuego(); ventanaJugar.oportunidadesRestantes(String.valueOf(oportunidades)); ventanaJugar.imagenInvisible(); Time puntajeNuevo = convertirHora(ventanaJugar.getTiempo()); Time puntajeViejo = jugadorDAO.elMayor(nivel); int vaPor=1; if (jugadorDAO.generaridJugador(nivel)==5) vaPor=2; if (jugadorDAO.generaridJugador(nivel)<5) { new ControladorRegistrarJugador(vaPor, nivel, puntajeNuevo, puntajeViejo); } else if (jugadorDAO.generaridJugador(nivel)==5) { if (convertirHora(ventanaJugar.getTiempo()).compareTo(jugadorDAO.elMayor(nivel)) < 0) { new ControladorRegistrarJugador(vaPor, nivel, puntajeNuevo, puntajeViejo); } } ventanaJugar.getCrono().reiniciarCronometro(); ventanaJugar.getCrono().iniciarCronometro(); } ventanaJugar.limpiarLetra(); ventanaJugar.limpiarPalabra(); } else if (actionCommand.equals("Buscala")) { if (controlador.buscarFrase(ventanaJugar.getPalabra())) { ventanaJugar.actualizarFrase(controlador.separarFrase()); ventanaJugar.getCrono().detenerse(); ventanaJugar.mostrarMensaje("Felicidades has ganado :D"); resultadoDelJuego(); ventanaJugar.imagenInvisible(); Time puntajeNuevo = convertirHora(ventanaJugar.getTiempo()); Time puntajeViejo = jugadorDAO.elMayor(nivel); int vaPor=1; if (jugadorDAO.generaridJugador(nivel)==5) vaPor=2; if (jugadorDAO.generaridJugador(nivel)<5) { new ControladorRegistrarJugador(vaPor, nivel, puntajeNuevo, puntajeViejo); } else if (jugadorDAO.generaridJugador(nivel)==5) { if (convertirHora(ventanaJugar.getTiempo()).compareTo(jugadorDAO.elMayor(nivel)) < 0) { new ControladorRegistrarJugador(vaPor, nivel, puntajeNuevo, puntajeViejo); } } ventanaJugar.getCrono().reiniciarCronometro(); ventanaJugar.getCrono().iniciarCronometro(); } else { ventanaJugar.getCrono().detenerse(); ventanaJugar.mostrarMensajePerdio(); resultadoDelJuego(); ventanaJugar.imagenInvisible(); ventanaJugar.getCrono().reiniciarCronometro(); ventanaJugar.getCrono().iniciarCronometro(); } ventanaJugar.limpiarLetra(); ventanaJugar.limpiarPalabra(); } ventanaJugar.oportunidadesRestantes(String.valueOf(oportunidades)); } }
Java
package controlador; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Time; import modelo.Jugador; import modelo.JugadorDAO; import modelo.Nivel; import modelo.NivelDAO; import vista.VentanaRegistrarJugador; public class ControladorRegistrarJugador implements ActionListener { private VentanaRegistrarJugador ventanaRegistrarJugador; private int vienePor; private int idnivel; private Time puntajeNuevo; private Time puntajeViejo; private Nivel nivel; private NivelDAO nivelDAO; public ControladorRegistrarJugador(int vienePor, int idnivel, Time puntajeNuevo, Time puntajeViejo) { super(); // TODO Auto-generated constructor stub ventanaRegistrarJugador = new VentanaRegistrarJugador(); ventanaRegistrarJugador.setVisible(true); ventanaRegistrarJugador.addListener(this); this.vienePor = vienePor; this.idnivel = idnivel; this.puntajeNuevo = puntajeNuevo; this.puntajeViejo = puntajeViejo; nivel = new Nivel(); nivelDAO = new NivelDAO(); nivel = nivelDAO.buscarNivelPorid(idnivel); ventanaRegistrarJugador.actualizarDescripcionNivel(nivel.getDescripcion()); ventanaRegistrarJugador.actualizarPuntaje(puntajeNuevo); } public void accionAceptar() { if (ventanaRegistrarJugador.getNombre().equals("")) ventanaRegistrarJugador.mostrarMensaje("Debes colocar tu nombre"); else{ JugadorDAO jugadorDAO = new JugadorDAO(); int idjugador = jugadorDAO.generaridJugador(idnivel); String nombre = ventanaRegistrarJugador.getNombre(); Jugador jugador = new Jugador(idjugador, nombre, puntajeNuevo, nivel); if (vienePor==1) jugadorDAO.registrarJugador(jugador); else if (vienePor==2) jugadorDAO.actualizarJugador(nombre, puntajeViejo, puntajeNuevo, idnivel); ventanaRegistrarJugador.mostrarMensaje("Puntaje guardado"); ventanaRegistrarJugador.limpiarNombre(); } } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub String actionCommand = e.getActionCommand(); if (actionCommand.equals("Aceptar")) { accionAceptar(); ventanaRegistrarJugador.setVisible(false); } } }
Java
package controlador; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; import java.util.Vector; import modelo.JugadorDAO; import modelo.Nivel; import modelo.NivelDAO; import vista.VentanaJugadorModeloTabla; import vista.VentanaListadoJugador; public class ControladorVentanaListado implements ActionListener { private VentanaListadoJugador ventanaListado; private NivelDAO nivelDAO = new NivelDAO();; public ControladorVentanaListado() { super(); // TODO Auto-generated constructor stub ventanaListado = VentanaListadoJugador.getInstancia(); ventanaListado.setVisible(true); ventanaListado.addListener(this); ventanaListado.cargarComboNivel(nivelDAO.llenarComboNivel()); } private void cargarListadoJugadores(){ Nivel nivel = new Nivel(); JugadorDAO jugadorDAO = new JugadorDAO(); nivel = nivelDAO.buscarNivel(ventanaListado.getComboNivelSeleccionado()); List<Vector<String>> jugadores = jugadorDAO.cincoConMejorPuntuacion(nivel.getIdnivel()); this.ventanaListado.setResultados(new VentanaJugadorModeloTabla(jugadores)); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub String actionCommand = e.getActionCommand(); if (e.getSource() == ventanaListado.getComboNivel()) { cargarListadoJugadores(); } else if (actionCommand.equals("Salir")) this.ventanaListado.setVisible(false); } }
Java
package vista; import java.awt.BorderLayout; import java.awt.Image; import java.awt.event.ActionListener; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.WindowConstants; import bean.EtiquetaImagen; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class VentanaNivel extends javax.swing.JFrame { private JPanel panNivel; private JRadioButton rdbNivel1; private JRadioButton rdbNivel2; private JRadioButton rdbNivel3; private JLabel lblDibujo; private JLabel lblEtiqueta; private JButton btnPlay; private EtiquetaImagen etiqueta; { //Set Look & Feel try { javax.swing.UIManager.setLookAndFeel("com.sun." + "java.swing.plaf.nimbus.NimbusLookAndFeel"); } catch(Exception e) { e.printStackTrace(); } } /** * Auto-generated main method to display this JFrame */ private static VentanaNivel instancia; public final static synchronized VentanaNivel getInstancia() { if (instancia == null) instancia = new VentanaNivel(); return instancia; } public VentanaNivel() { super(); etiqueta = new EtiquetaImagen(); initGUI(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); { panNivel = new JPanel(); getContentPane().add(panNivel, BorderLayout.CENTER); panNivel.setLayout(null); ButtonGroup btgNivel = new ButtonGroup(); { rdbNivel1 = new JRadioButton(); panNivel.add(rdbNivel1); rdbNivel1.setText("Basico"); rdbNivel1.setBounds(35, 93, 115, 21); btgNivel.add(rdbNivel1); } { rdbNivel2 = new JRadioButton(); panNivel.add(rdbNivel2); rdbNivel2.setText("Intermedio"); rdbNivel2.setBounds(35, 142, 115, 21); btgNivel.add(rdbNivel2); } { rdbNivel3 = new JRadioButton(); panNivel.add(rdbNivel3); rdbNivel3.setText("Avanzado"); rdbNivel3.setBounds(35, 192, 115, 21); btgNivel.add(rdbNivel3); } { ImageIcon homero = etiqueta.crearImageIcon("iconos/homero4.JPG"); //Image imagen = homero.getImage(); //ImageIcon aescala = new ImageIcon( //imagen.getScaledInstance(200,200,Image.SCALE_SMOOTH)); lblDibujo = new JLabel(homero); panNivel.add(lblDibujo); lblDibujo.setBounds(311, 52, 172, 175); //lblDibujo.setIcon(new ImageIcon(getClass().getClassLoader().getResource("iconos/celebracion.gif"))); } { btnPlay = new JButton(); panNivel.add(btnPlay); btnPlay.setText("PLAY"); btnPlay.setBounds(171, 136, 92, 33); } { lblEtiqueta = new JLabel(); panNivel.add(lblEtiqueta); lblEtiqueta.setText("Selecciona un Nivel"); lblEtiqueta.setBounds(35, 36, 136, 23); } } pack(); this.setSize(516, 315); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } public void addListener(ActionListener actionListener){ this.btnPlay.addActionListener(actionListener); } public boolean estaSeleccionadoNivel1(){ return this.rdbNivel1.isSelected(); } public boolean estaSeleccionadoNivel2(){ return this.rdbNivel2.isSelected(); } public boolean estaSeleccionadoNivel3(){ return this.rdbNivel3.isSelected(); } public String getNivel1(){ return this.rdbNivel1.getText().toLowerCase(); } public String getNivel2(){ return this.rdbNivel2.getText().toLowerCase(); } public String getNivel3(){ return this.rdbNivel3.getText().toLowerCase(); } public void mostrarMensaje(String mensaje){ JOptionPane.showMessageDialog(this, mensaje); } }
Java
package vista; import java.awt.BorderLayout; import java.awt.event.ActionListener; import java.util.Vector; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.WindowConstants; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class VentanaListadoJugador extends javax.swing.JFrame { { //Set Look & Feel try { javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); } catch(Exception e) { e.printStackTrace(); } } private JPanel panListadoJugador; private JLabel lblSeleccione; private JButton btnSalir; private JComboBox cmbNivel; private JScrollPane scpListadoJugador; private JTable tblJugador; /** * Auto-generated main method to display this JFrame */ private static VentanaListadoJugador instancia; public final static synchronized VentanaListadoJugador getInstancia() { if (instancia == null) instancia = new VentanaListadoJugador(); return instancia; } public VentanaListadoJugador() { super(); initGUI(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); { panListadoJugador = new JPanel(); getContentPane().add(panListadoJugador, BorderLayout.CENTER); panListadoJugador.setLayout(null); { lblSeleccione = new JLabel(); panListadoJugador.add(lblSeleccione); lblSeleccione.setText("Seleccione un Nivel"); lblSeleccione.setBounds(36, 28, 156, 25); } { scpListadoJugador = new JScrollPane(); panListadoJugador.add(scpListadoJugador); scpListadoJugador.setBounds(36, 79, 443, 226); { TableModel tblJugadorModel = new DefaultTableModel(); tblJugador = new JTable(); scpListadoJugador.setViewportView(tblJugador); tblJugador.setModel(tblJugadorModel); } } { ComboBoxModel cmbNivelModel = new DefaultComboBoxModel(); cmbNivel = new JComboBox(); panListadoJugador.add(cmbNivel); cmbNivel.setModel(cmbNivelModel); cmbNivel.setBounds(186, 27, 146, 26); } { btnSalir = new JButton(); panListadoJugador.add(btnSalir); btnSalir.setText("Salir"); btnSalir.setBounds(209, 332, 81, 31); } } pack(); this.setSize(532, 420); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } public void addListener(ActionListener actionListener) { this.cmbNivel.addActionListener(actionListener); this.btnSalir.addActionListener(actionListener); } public void setResultados(AbstractTableModel abstractTableModel) { tblJugador.setModel(abstractTableModel); } public JComboBox getComboNivel() { return this.cmbNivel; } public void cargarComboNivel(Vector<String> vector){ ComboBoxModel cmbNivelModel = new DefaultComboBoxModel(vector); cmbNivel.setModel(cmbNivelModel); } public String getComboNivelSeleccionado() { return this.cmbNivel.getSelectedItem().toString(); } }
Java
package vista; import java.util.ArrayList; import java.util.List; import java.util.Vector; import javax.swing.table.AbstractTableModel; public class VentanaJugadorModeloTabla extends AbstractTableModel { private static String[] titulos = {"Nombre del Jugador", "Puntaje", "Nivel"}; private List<Vector<String>> jugadores = new ArrayList<Vector<String>>(); public VentanaJugadorModeloTabla(List<Vector<String>> jugadores) { super(); this.jugadores = jugadores; this.fireTableDataChanged(); } @Override public int getColumnCount() { return titulos.length; } @Override public int getRowCount() { return jugadores.size(); } @Override public Object getValueAt(int rowIndex, int columnIndex) { Vector<String> jugador = jugadores.get(rowIndex); switch (columnIndex) { case 0: return jugador.get(0); case 1: return jugador.get(1); case 2: return jugador.get(2); } return null; } @Override public String getColumnName(int column) { return titulos[column]; } }
Java
package vista; import java.awt.BorderLayout; import java.awt.event.ActionListener; import javabean.JPanelImagen; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.ButtonGroup; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JRadioButton; import javax.swing.WindowConstants; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class VentanaMenu extends javax.swing.JFrame { { //Set Look & Feel try { javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); } catch(Exception e) { e.printStackTrace(); } } private JMenuBar menuPrincipal; private JMenu menuSistema; private JMenuItem menuConsultar; private JMenuItem menuSalirAhora; private JMenu menuSalir; private JMenuItem menuNivel3; private JMenuItem menuNivel2; private JLabel lblElegirNivel; private JButton btnJugar; private JLabel lblPresentacion2; private JLabel lblPresentacion; private JMenuItem menuNivel1; private JMenuItem menuListados; private JMenuItem menuFrase; private JMenuItem menuRegistrar; private JPanelImagen panFondo; /** * Auto-generated main method to display this JFrame */ public VentanaMenu() { super(); initGUI(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); { menuPrincipal = new JMenuBar(); setJMenuBar(menuPrincipal); { menuSistema = new JMenu(); menuPrincipal.add(menuSistema); menuSistema.setText("Sistema"); { menuRegistrar = new JMenu(); menuSistema.add(menuRegistrar); menuRegistrar.setText("Registrar"); { menuFrase = new JMenuItem(); menuRegistrar.add(menuFrase); menuFrase.setText("Nueva Frase"); } } { menuConsultar = new JMenu(); menuSistema.add(menuConsultar); menuConsultar.setText("Consultar"); { menuListados = new JMenuItem(); menuConsultar.add(menuListados); menuListados.setText("Listado"); /*{ menuNivel1 = new JMenuItem(); menuListados.add(menuNivel1); menuNivel1.setText("Nivel 1"); } { menuNivel2 = new JMenuItem(); menuListados.add(menuNivel2); menuNivel2.setText("Nivel 2"); } { menuNivel3 = new JMenuItem(); menuListados.add(menuNivel3); menuNivel3.setText("Nivel 3"); }*/ } } } { menuSalir = new JMenu(); menuPrincipal.add(menuSalir); menuSalir.setText("Salir"); { menuSalirAhora = new JMenuItem(); menuSalir.add(menuSalirAhora); menuSalirAhora.setText("Salir"); } } { panFondo = new JPanelImagen(); getContentPane().add(panFondo, BorderLayout.CENTER); panFondo.setRutaImagen("/iconos/homersf4.jpg"); panFondo.setPreferredSize(new java.awt.Dimension(600, 387)); ButtonGroup btgNivel = new ButtonGroup(); { lblPresentacion = new JLabel(); panFondo.add(lblPresentacion); lblPresentacion.setText("JUEGA EL AHORCADO"); lblPresentacion.setBounds(38, 10, 289, 23); lblPresentacion.setFont(new java.awt.Font("Tempus Sans ITC",1,22)); lblPresentacion.setForeground(new java.awt.Color(255,255,255)); } { lblPresentacion2 = new JLabel(); panFondo.add(lblPresentacion2); lblPresentacion2.setText("Y DIVIERTE COMO NUNCA"); lblPresentacion2.setBounds(17, 45, 348, 26); lblPresentacion2.setFont(new java.awt.Font("Tempus Sans ITC",1,22)); lblPresentacion2.setForeground(new java.awt.Color(255,255,255)); } { btnJugar = new JButton(); panFondo.add(btnJugar); btnJugar.setText("JUGAR"); btnJugar.setBounds(427, 193, 106, 29); btnJugar.setFont(new java.awt.Font("Tempus Sans ITC",1,11)); } { lblElegirNivel = new JLabel(); panFondo.add(lblElegirNivel); lblElegirNivel.setText("PRESIONA EL BOTON"); lblElegirNivel.setBounds(417, 139, 151, 22); lblElegirNivel.setFont(new java.awt.Font("Tempus Sans ITC",1,11)); lblElegirNivel.setForeground(new java.awt.Color(255,255,255)); } } } pack(); this.setSize(645, 450); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } public void addListener(ActionListener actionListener) { menuSalirAhora.addActionListener(actionListener); menuFrase.addActionListener(actionListener); btnJugar.addActionListener(actionListener); menuListados.addActionListener(actionListener); } }
Java
package vista; import java.awt.BorderLayout; import java.awt.event.ActionListener; import java.util.Vector; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.WindowConstants; import bean.JTextFieldValidator; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class VentanaFrase extends javax.swing.JFrame { { //Set Look & Feel try { javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); } catch(Exception e) { e.printStackTrace(); } } private JPanel panFrase; private JLabel lblDescripcion; private JLabel lblNivel; private JButton btnCancelar; private JLabel lblEncabezado; private JButton btnSalir; private JButton btnGuardar; private JComboBox cmbNivel; private JTextFieldValidator txtDescripcion; private JTextField txtCodigoFrase; private JLabel lblCodigoFrase; private static VentanaFrase instancia; public final static synchronized VentanaFrase getInstancia() { if (instancia == null) instancia = new VentanaFrase(); return instancia; } public VentanaFrase() { super(); initGUI(); //actualizarTamanoDescripcion(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setTitle("Registrar Frase"); getContentPane().setBackground(new java.awt.Color(255,255,255)); { panFrase = new JPanel(); getContentPane().add(panFrase, BorderLayout.CENTER); panFrase.setLayout(null); panFrase.setBackground(new java.awt.Color(255,255,255)); { lblCodigoFrase = new JLabel(); panFrase.add(lblCodigoFrase); lblCodigoFrase.setText("Codigo"); lblCodigoFrase.setBounds(38, 76, 61, 18); lblCodigoFrase.setFont(new java.awt.Font("SansSerif",0,12)); } { lblDescripcion = new JLabel(); panFrase.add(lblDescripcion); lblDescripcion.setText("Descripcion"); lblDescripcion.setBounds(38, 113, 73, 18); lblDescripcion.setFont(new java.awt.Font("SansSerif",0,12)); } { lblNivel = new JLabel(); panFrase.add(lblNivel); lblNivel.setText("Nivel"); lblNivel.setBounds(38, 152, 61, 18); lblNivel.setFont(new java.awt.Font("SansSerif",0,12)); } { txtCodigoFrase = new JTextField(); panFrase.add(txtCodigoFrase); txtCodigoFrase.setBounds(126, 73, 100, 24); txtCodigoFrase.setFont(new java.awt.Font("SansSerif",0,12)); } { txtDescripcion = new JTextFieldValidator(); panFrase.add(txtDescripcion); txtDescripcion.setBounds(126, 112, 142, 24); txtDescripcion.setFont(new java.awt.Font("SansSerif",0,12)); //txtDescripcion.setMaximumSize(10); } { ComboBoxModel cmbNivelModel = new DefaultComboBoxModel(); cmbNivel = new JComboBox(); panFrase.add(cmbNivel); cmbNivel.setModel(cmbNivelModel); cmbNivel.setBounds(126, 151, 100, 24); cmbNivel.setFont(new java.awt.Font("SansSerif",0,12)); } { btnGuardar = new JButton(); panFrase.add(btnGuardar); btnGuardar.setText("Guardar"); btnGuardar.setBounds(38, 202, 87, 27); btnGuardar.setFont(new java.awt.Font("SansSerif",0,12)); } { btnCancelar = new JButton(); panFrase.add(btnCancelar); btnCancelar.setText("Cancelar"); btnCancelar.setBounds(137, 202, 87, 27); btnCancelar.setFont(new java.awt.Font("SansSerif",0,12)); } { btnSalir = new JButton(); panFrase.add(btnSalir); btnSalir.setText("Salir"); btnSalir.setBounds(237, 202, 87, 27); btnSalir.setFont(new java.awt.Font("SansSerif",0,12)); } { lblEncabezado = new JLabel(); panFrase.add(lblEncabezado); lblEncabezado.setText("RELLENE LOS SIGUIENTES CAMPOS"); lblEncabezado.setBounds(38, 18, 255, 24); lblEncabezado.setFont(new java.awt.Font("SansSerif",0,12)); } } pack(); this.setSize(363, 294); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } public void addListener(ActionListener actionListener){ this.btnGuardar.addActionListener(actionListener); this.btnCancelar.addActionListener(actionListener); this.btnSalir.addActionListener(actionListener); this.cmbNivel.addActionListener(actionListener); } public void setCodigoFrase(String codigo){ this.txtCodigoFrase.setText(codigo); } public String getCodigoFrase(){ return this.txtCodigoFrase.getText(); } public String getDescripcion(){ return this.txtDescripcion.getText(); } public void mostrarMensaje(String mensaje) { JOptionPane.showMessageDialog(this, mensaje); } public void cargarComboNivel(Vector<String> vector){ ComboBoxModel cmbNivelModel = new DefaultComboBoxModel(vector); cmbNivel.setModel(cmbNivelModel); } public String getNivel(){ return cmbNivel.getSelectedItem().toString(); } public void borrarDatos(){ this.txtDescripcion.setText(""); } public JComboBox getComboNivel(){ return this.cmbNivel; } public void actualizarTamanoDescripcion(int tamano){ this.txtDescripcion.setMaximaLongitud(tamano); } public int getTamanoDescripcion(){ return this.txtDescripcion.getMaximaLongitud(); } /*public void actualizarTamanoDescripcion(){ this.txtDescripcion = new JTextFieldValidator(JTextFieldValidator.SOLO_LETRAS); }*/ }
Java
package modelo; import java.sql.*; public class Conexion { // La descripcion del driver de la BD private static String driver = "org.postgresql.Driver"; // La direccion URL de la BD private static String url = "jdbc:postgresql://localhost:5432/"; // El nombre de la BD private static String bd = "BD1-2"; // EL login del usuario para conectarse al servidor de BD private static String usuario = "postgres"; // EL password del usuario para conectarse al servidor de BD private static String password = "20236773"; private static Connection conexion; /** * Metodo utilizado para Obtener una conexion a BD * @return Un objeto tipo Connection que representa una conexion a la BD */ private static Connection getConexion() { try{ if (conexion == null || conexion.isClosed()) { // Cargo el driver en memoria Class.forName(driver); // Establezco la conexion conexion=DriverManager.getConnection(url+bd,usuario,password); } } catch(SQLException e){ e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return conexion; } /** * Metodo consultar * @param String tiraSQL * @return ResultSet */ public static ResultSet consultar(String tiraSQL) { getConexion(); ResultSet resultado = null; try { Statement sentencia= conexion.createStatement(); resultado = sentencia.executeQuery(tiraSQL); } catch(Exception e) { e.printStackTrace(); } try { conexion.close(); } catch( SQLException e ) { e.printStackTrace(); } return resultado; } /** * Metodo ejecutar * @param String TiraSQL * @return boolean */ public static boolean ejecutar(String tiraSQL) { getConexion(); boolean ok = false; try { Statement sentencia = conexion.createStatement(); int i = sentencia.executeUpdate(tiraSQL); if (i > 0) { ok = true; } sentencia.close (); } catch(Exception e) { e.printStackTrace(); } try { conexion.close(); } catch( SQLException e ) { e.printStackTrace(); } return ok; } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.engine; import eu.lighthouselabs.obd.commands.PercentageObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * Read the throttle position in percentage. */ public class ThrottlePositionObdCommand extends PercentageObdCommand { /** * Default ctor. */ public ThrottlePositionObdCommand() { super("01 11"); } /** * Copy ctor. * * @param other */ public ThrottlePositionObdCommand(ThrottlePositionObdCommand other) { super(other); } /** * */ @Override public String getName() { return AvailableCommandNames.THROTTLE_POS.getValue(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.engine; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.commands.PercentageObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * Calculated Engine Load value. */ public class EngineLoadObdCommand extends PercentageObdCommand { /** * @param command */ public EngineLoadObdCommand() { super("01 04"); } /** * @param other */ public EngineLoadObdCommand(ObdCommand other) { super(other); } /* (non-Javadoc) * @see eu.lighthouselabs.obd.commands.ObdCommand#getName() */ @Override public String getName() { return AvailableCommandNames.ENGINE_LOAD.getValue(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.engine; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * Displays the current engine revolutions per minute (RPM). */ public class EngineRPMObdCommand extends ObdCommand { private int _rpm = -1; /** * Default ctor. */ public EngineRPMObdCommand() { super("01 0C"); } /** * Copy ctor. * * @param other */ public EngineRPMObdCommand(EngineRPMObdCommand other) { super(other); } /** * @return the engine RPM per minute */ @Override public String getFormattedResult() { if (!"NODATA".equals(getResult())) { // ignore first two bytes [41 0C] of the response int a = buffer.get(2); int b = buffer.get(3); _rpm = (a * 256 + b) / 4; } return String.format("%d%s", _rpm, " RPM"); } @Override public String getName() { return AvailableCommandNames.ENGINE_RPM.getValue(); } public int getRPM() { return _rpm; } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.engine; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * TODO put description * * Mass Air Flow */ public class MassAirFlowObdCommand extends ObdCommand { private float _maf = -1.0f; /** * Default ctor. */ public MassAirFlowObdCommand() { super("01 10"); } /** * Copy ctor. * * @param other */ public MassAirFlowObdCommand(MassAirFlowObdCommand other) { super(other); } /** * */ @Override public String getFormattedResult() { if (!"NODATA".equals(getResult())) { // ignore first two bytes [hh hh] of the response int a = buffer.get(2); int b = buffer.get(3); _maf = (a * 256 + b) / 100.0f; } return String.format("%.2f%s", _maf, "g/s"); } /** * @return MAF value for further calculus. */ public double getMAF() { return _maf; } @Override public String getName() { return AvailableCommandNames.MAF.getValue(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.engine; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * TODO put description */ public class EngineRuntimeObdCommand extends ObdCommand { /** * Default ctor. */ public EngineRuntimeObdCommand() { super("01 1F"); } /** * Copy ctor. * * @param other */ public EngineRuntimeObdCommand(EngineRuntimeObdCommand other) { super(other); } @Override public String getFormattedResult() { String res = getResult(); if (!"NODATA".equals(res)) { // ignore first two bytes [01 0C] of the response int a = buffer.get(2); int b = buffer.get(3); int value = a * 256 + b; // determine time String hh = String.format("%02d", value / 3600); String mm = String.format("%02d", (value % 3600) / 60); String ss = String.format("%02d", value % 60); res = String.format("%s:%s:%s", hh, mm, ss); } return res; } @Override public String getName() { return AvailableCommandNames.ENGINE_RUNTIME.getValue(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.control; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * Fuel systems that use conventional oxygen sensor display the commanded open * loop equivalence ratio while the system is in open loop. Should report 100% * when in closed loop fuel. * * To obtain the actual air/fuel ratio being commanded, multiply the * stoichiometric A/F ratio by the equivalence ratio. For example, gasoline, * stoichiometric is 14.64:1 ratio. If the fuel control system was commanded an * equivalence ratio of 0.95, the commanded A/F ratio to the engine would be * 14.64 * 0.95 = 13.9 A/F. */ public class CommandEquivRatioObdCommand extends ObdCommand { /* * Equivalent ratio (%) */ private double ratio = 0.00; /** * Default ctor. */ public CommandEquivRatioObdCommand() { super("01 44"); } /** * Copy ctor. * * @param other */ public CommandEquivRatioObdCommand(CommandEquivRatioObdCommand other) { super(other); } /** * */ @Override public String getFormattedResult() { String res = getResult(); if (!"NODATA".equals(res)) { // ignore first two bytes [hh hh] of the response int a = buffer.get(2); int b = buffer.get(3); ratio = (a * 256 + b) / 32768; res = String.format("%.1f%s", ratio, "%"); } return res; } /** * @return */ public double getRatio() { return ratio; } @Override public String getName() { return AvailableCommandNames.EQUIV_RATIO.getValue(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.control; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * In order to get ECU Trouble Codes, one must first send a DtcNumberObdCommand * and by so, determining the number of error codes available by means of * getTotalAvailableCodes(). * * If none are available (totalCodes < 1), don't instantiate this command. */ public class TroubleCodesObdCommand extends ObdCommand { protected final static char[] dtcLetters = { 'P', 'C', 'B', 'U' }; private StringBuffer codes = null; private int howManyTroubleCodes = 0; /** * Default ctor. */ public TroubleCodesObdCommand(int howManyTroubleCodes) { super("03"); codes = new StringBuffer(); this.howManyTroubleCodes = howManyTroubleCodes; } /** * Copy ctor. * * @param other */ public TroubleCodesObdCommand(TroubleCodesObdCommand other) { super(other); codes = new StringBuffer(); } // TODO clean // int count = numCmd.getCodeCount(); // int dtcNum = (count + 2) / 3; // for (int i = 0; i < dtcNum; i++) { // sendCommand(cmd); // String res = getResult(); // for (int j = 0; j < 3; j++) { // String byte1 = res.substring(3 + j * 6, 5 + j * 6); // String byte2 = res.substring(6 + j * 6, 8 + j * 6); // int b1 = Integer.parseInt(byte1, 16); // int b2 = Integer.parseInt(byte2, 16); // int val = (b1 << 8) + b2; // if (val == 0) { // break; // } // String code = "P"; // if ((val & 0xC000) > 14) { // code = "C"; // } // code += Integer.toString((val & 0x3000) >> 12); // code += Integer.toString((val & 0x0fff)); // codes.append(code); // codes.append("\n"); // } /** * @return the formatted result of this command in string representation. */ public String formatResult() { String res = getResult(); if (!"NODATA".equals(res)) { /* * Ignore first byte [43] of the response and then read each two * bytes. */ int begin = 2; // start at 2nd byte int end = 6; // end at 4th byte for (int i = 0; i < howManyTroubleCodes * 2; i++) { // read and jump 2 bytes byte b1 = Byte.parseByte(res.substring(begin, end)); begin += 2; end += 2; // read and jump 2 bytes byte b2 = Byte.parseByte(res.substring(begin, end)); begin += 2; end += 2; int tempValue = b1 << 8 | b2; } } String[] ress = res.split("\r"); for (String r : ress) { String k = r.replace("\r", ""); codes.append(k); codes.append("\n"); } return codes.toString(); } @Override public String getFormattedResult() { // TODO Auto-generated method stub return null; } @Override public String getName() { return AvailableCommandNames.TROUBLE_CODES.getValue(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.control; import eu.lighthouselabs.obd.commands.PercentageObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * TODO put description * * Timing Advance */ public class TimingAdvanceObdCommand extends PercentageObdCommand { public TimingAdvanceObdCommand() { super("01 0E"); } public TimingAdvanceObdCommand(TimingAdvanceObdCommand other) { super(other); } @Override public String getName() { return AvailableCommandNames.TIMING_ADVANCE.getValue(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.control; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * This command will for now read MIL (check engine light) state and number of * diagnostic trouble codes currently flagged in the ECU. * * Perhaps in the future we'll extend this to read the 3rd, 4th and 5th bytes of * the response in order to store information about the availability and * completeness of certain on-board tests. */ public class DtcNumberObdCommand extends ObdCommand { private int codeCount = 0; private boolean milOn = false; /** * Default ctor. */ public DtcNumberObdCommand() { super("01 01"); } /** * Copy ctor. * * @param other */ public DtcNumberObdCommand(DtcNumberObdCommand other) { super(other); } /** * */ public String getFormattedResult() { String res = getResult(); if (!"NODATA".equals(res)) { // ignore first two bytes [hh hh] of the response int mil = buffer.get(2); if ((mil & 0x80) == 128) milOn = true; codeCount = mil & 0x7F; } res = milOn ? "MIL is ON" : "MIL is OFF"; return new StringBuilder().append(res).append(codeCount) .append(" codes").toString(); } /** * @return the number of trouble codes currently flaggd in the ECU. */ public int getTotalAvailableCodes() { return codeCount; } /** * * @return the state of the check engine light state. */ public boolean getMilOn() { return milOn; } @Override public String getName() { return AvailableCommandNames.DTC_NUMBER.getValue(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.protocol; import eu.lighthouselabs.obd.commands.ObdCommand; /** * This command will turn-off echo. */ public class EchoOffObdCommand extends ObdCommand { /** * @param command */ public EchoOffObdCommand() { super("AT E0"); } /** * @param other */ public EchoOffObdCommand(ObdCommand other) { super(other); } /* * (non-Javadoc) * * @see eu.lighthouselabs.obd.commands.ObdCommand#getFormattedResult() */ @Override public String getFormattedResult() { return getResult(); } @Override public String getName() { return "Echo Off"; } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.protocol; import java.io.IOException; import java.io.InputStream; import eu.lighthouselabs.obd.commands.ObdCommand; /** * This method will reset the OBD connection. */ public class ObdResetCommand extends ObdCommand { /** * @param command */ public ObdResetCommand() { super("AT Z"); } /** * @param other */ public ObdResetCommand(ObdResetCommand other) { super(other); } /** * Reset command returns an empty string, so we must override the following * two methods. * @throws IOException */ @Override public void readResult(InputStream in) throws IOException { // do nothing return; } @Override public String getResult() { return ""; } /* * (non-Javadoc) * * @see eu.lighthouselabs.obd.commands.ObdCommand#getFormattedResult() */ @Override public String getFormattedResult() { return getResult(); } @Override public String getName() { return "Reset OBD"; } }
Java
/* * TODO put description */ package eu.lighthouselabs.obd.commands.protocol; import eu.lighthouselabs.obd.commands.ObdCommand; /** * This will set the value of time in milliseconds (ms) that the OBD interface * will wait for a response from the ECU. If exceeds, the response is "NO DATA". */ public class TimeoutObdCommand extends ObdCommand { /** * @param a * value between 0 and 255 that multiplied by 4 results in the * desired timeout in milliseconds (ms). */ public TimeoutObdCommand(int timeout) { super("AT ST " + Integer.toHexString(0xFF & timeout)); } /** * @param other */ public TimeoutObdCommand(ObdCommand other) { super(other); } /* * (non-Javadoc) * * @see eu.lighthouselabs.obd.commands.ObdCommand#getFormattedResult() */ @Override public String getFormattedResult() { return getResult(); } @Override public String getName() { return "Timeout"; } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.protocol; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.ObdProtocols; /** * Select the protocol to use. */ public class SelectProtocolObdCommand extends ObdCommand { private final ObdProtocols _protocol; /** * @param command */ public SelectProtocolObdCommand(ObdProtocols protocol) { super("AT SP " + protocol.getValue()); _protocol = protocol; } /* * (non-Javadoc) * * @see eu.lighthouselabs.obd.commands.ObdCommand#getFormattedResult() */ @Override public String getFormattedResult() { return getResult(); } @Override public String getName() { return "Select Protocol " + _protocol.name(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.protocol; import eu.lighthouselabs.obd.commands.ObdCommand; /** * Turns off line-feed. */ public class LineFeedOffObdCommand extends ObdCommand { /** * @param command */ public LineFeedOffObdCommand() { super("AT L0"); } /** * @param other */ public LineFeedOffObdCommand(ObdCommand other) { super(other); } /* * (non-Javadoc) * * @see eu.lighthouselabs.obd.commands.ObdCommand#getFormattedResult() */ @Override public String getFormattedResult() { return getResult(); } @Override public String getName() { return "Line Feed Off"; } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.temperature; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * Engine Coolant Temperature. */ public class EngineCoolantTemperatureObdCommand extends TemperatureObdCommand { /** * */ public EngineCoolantTemperatureObdCommand() { super("01 05"); } /** * @param other */ public EngineCoolantTemperatureObdCommand(TemperatureObdCommand other) { super(other); } /* * (non-Javadoc) * * @see eu.lighthouselabs.obd.commands.ObdCommand#getName() */ @Override public String getName() { return AvailableCommandNames.ENGINE_COOLANT_TEMP.getValue(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.temperature; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * TODO * * put description */ public class AirIntakeTemperatureObdCommand extends TemperatureObdCommand { public AirIntakeTemperatureObdCommand() { super("01 0F"); } public AirIntakeTemperatureObdCommand(AirIntakeTemperatureObdCommand other) { super(other); } @Override public String getName() { return AvailableCommandNames.AIR_INTAKE_TEMP.getValue(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.temperature; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.commands.SystemOfUnits; /** * TODO * * put description */ public abstract class TemperatureObdCommand extends ObdCommand implements SystemOfUnits { private float temperature = 0.0f; /** * Default ctor. * * @param cmd */ public TemperatureObdCommand(String cmd) { super(cmd); } /** * Copy ctor. * * @param other */ public TemperatureObdCommand(TemperatureObdCommand other) { super(other); } /** * TODO * * put description of why we subtract 40 * * @param temp * @return */ protected final float prepareTempValue(float temp) { return temp - 40; } /** * Get values from 'buff', since we can't rely on char/string for calculations. * * @return Temperature in Celsius or Fahrenheit. */ @Override public String getFormattedResult() { String res = getResult(); if (!"NODATA".equals(res)) { // ignore first two bytes [hh hh] of the response temperature = prepareTempValue(buffer.get(2)); // convert? if (useImperialUnits) res = String.format("%.1f%s", getImperialUnit(), "F"); else res = String.format("%.0f%s", temperature, "C"); } return res; } /** * @return the temperature in Celsius. */ public float getTemperature() { return temperature; } /** * @return the temperature in Fahrenheit. */ public float getImperialUnit() { return temperature * 1.8f + 32; } /** * @return the temperature in Kelvin. */ public float getKelvin() { return temperature + 273.15f; } /** * @return the OBD command name. */ public abstract String getName(); }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.temperature; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * Ambient Air Temperature. */ public class AmbientAirTemperatureObdCommand extends TemperatureObdCommand { /** * @param cmd */ public AmbientAirTemperatureObdCommand() { super("01 46"); } /** * @param other */ public AmbientAirTemperatureObdCommand(TemperatureObdCommand other) { super(other); } @Override public String getName() { return AvailableCommandNames.AMBIENT_AIR_TEMP.getValue(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.utils; /** * Misc utilities */ public final class ObdUtils { /** * @param an integer value * @return the equivalent FuelType name. */ public final static String getFuelTypeName(int value) { String name = null; switch (value) { case 1: name = "Gasoline"; break; case 2: name = "Methanol"; break; case 3: name = "Ethanol"; break; case 4: name = "Diesel"; break; case 5: name = "GPL/LGP"; break; case 6: name = "Natural Gas (CNG)"; break; case 7: name = "Propane"; break; case 8: name = "Electric"; break; case 9: name = "Biodiesel + Gasoline"; break; case 10: name = "Biodiesel + Methanol"; break; case 11: name = "Biodiesel + Ethanol"; break; case 12: name = "Biodiesel + GPL/LPG"; break; case 13: name = "Biodiesel + Natural Gas"; break; case 14: name = "Biodiesel + Propane"; break; case 15: name = "Biodiesel + Electric"; break; case 16: name = "Biodiesel + Gasoline/Electric"; break; case 17: name = "Hybrid Gasoline"; break; case 18: name = "Hybrid Ethanol"; break; case 19: name = "Hybrid Diesel"; break; case 20: name = "Hybrid Electric"; break; case 21: name = "Hybrid Mixed"; break; case 22: name = "Hybrid Regenerative"; break; default: name = "NODATA"; } return name; } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.fuel; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * Get fuel level in percentage */ public class FuelLevelObdCommand extends ObdCommand { private float fuelLevel = 0f; /** * @param command */ public FuelLevelObdCommand() { super("01 2F"); } /* * (non-Javadoc) * * @see eu.lighthouselabs.obd.commands.ObdCommand#getFormattedResult() */ @Override public String getFormattedResult() { if (!"NODATA".equals(getResult())) { // ignore first two bytes [hh hh] of the response fuelLevel = 100.0f * buffer.get(2) / 255.0f; } return String.format("%.1f%s", fuelLevel, "%"); } @Override public String getName() { return AvailableCommandNames.FUEL_LEVEL.getValue(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.fuel; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.commands.SpeedObdCommand; import eu.lighthouselabs.obd.commands.control.CommandEquivRatioObdCommand; import eu.lighthouselabs.obd.commands.engine.EngineRPMObdCommand; import eu.lighthouselabs.obd.commands.pressure.IntakeManifoldPressureObdCommand; import eu.lighthouselabs.obd.commands.temperature.AirIntakeTemperatureObdCommand; /** * TODO put description */ public class FuelEconomyWithoutMAFObdCommand extends ObdCommand { public static final double AIR_FUEL_RATIO = 14.64; public static final double FUEL_DENSITY_GRAMS_PER_LITER = 720.0; public FuelEconomyWithoutMAFObdCommand() { super(""); } /** * As it's a fake command, neither do we need to send request or read * response. */ @Override public void run(InputStream in, OutputStream out) throws IOException, InterruptedException { // prepare variables EngineRPMObdCommand rpmCmd = new EngineRPMObdCommand(); rpmCmd.run(in, out); rpmCmd.getFormattedResult(); AirIntakeTemperatureObdCommand airTempCmd = new AirIntakeTemperatureObdCommand(); airTempCmd.run(in, out); airTempCmd.getFormattedResult(); SpeedObdCommand speedCmd = new SpeedObdCommand(); speedCmd.run(in, out); speedCmd.getFormattedResult(); CommandEquivRatioObdCommand equivCmd = new CommandEquivRatioObdCommand(); equivCmd.run(in, out); equivCmd.getFormattedResult(); IntakeManifoldPressureObdCommand pressCmd = new IntakeManifoldPressureObdCommand(); pressCmd.run(in, out); pressCmd.getFormattedResult(); double imap = rpmCmd.getRPM() * pressCmd.getMetricUnit() / airTempCmd.getKelvin(); // double maf = (imap / 120) * (speedCmd.getMetricSpeed()/100)*() } @Override public String getFormattedResult() { // TODO Auto-generated method stub return null; } @Override public String getName() { // TODO Auto-generated method stub return null; } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.fuel; import eu.lighthouselabs.obd.enums.AvailableCommandNames; import eu.lighthouselabs.obd.enums.FuelType; /** * TODO put description */ public class FuelEconomyWithMAFObdCommand { private int speed = 1; private double maf = 1; private float ltft = 1; private double ratio = 1; private FuelType fuelType; private boolean useImperial = false; double mpg = -1; double litersPer100Km = -1; /** * @param command */ public FuelEconomyWithMAFObdCommand(FuelType fuelType, int speed, double maf, float ltft, boolean useImperial) { this.fuelType = fuelType; this.speed = speed; this.maf = maf; this.ltft = ltft; this.useImperial = useImperial; mpg = (14.7 * 6.17 * 454 * speed * 0.621371) / (3600 * maf); // mpg = 710.7 * speed / maf * (1 + ltft / 100); // mpg = (14.7 * ratio * 6.17 * 454.0 * speed * 0.621371) / (3600.0 * maf); // mpg = (14.7 * (1 + ltft / 100) * 6.17 * 454.0 * speed * 0.621371) / (3600.0 * maf); // litersPer100Km = mpg / 2.2352; litersPer100Km = 235.2 / mpg; // float fuelDensity = 0.71f; // if (fuelType.equals(FuelType.DIESEL)) // fuelDensity = 0.832f; // litersPer100Km = (maf / 14.7 / fuelDensity * 3600) * (1 + ltft / 100) // / speed; } /** * As it's a fake command, neither do we need to send request or read * response. */ public double getMPG() { return mpg; } /** * @return the fuel consumption in l/100km */ public double getLitersPer100Km() { return litersPer100Km; } public String getFormattedResult() { String res = "NODATA"; res = String.format("%.2f%s", litersPer100Km, "l/100km"); if (useImperial) res = String.format("%.1f%s", mpg, "mpg"); return res; } public String getName() { return AvailableCommandNames.FUEL_ECONOMY_WITH_MAF.getValue(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.fuel; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.commands.SpeedObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * TODO put description */ public class FuelEconomyObdCommand extends ObdCommand { protected float kml = -1.0f; private float speed = -1.0f; /** * Default ctor. */ public FuelEconomyObdCommand() { super(""); } /** * As it's a fake command, neither do we need to send request or read * response. */ @Override public void run(InputStream in, OutputStream out) throws IOException, InterruptedException { // get consumption liters per hour FuelConsumptionObdCommand fuelConsumptionCommand = new FuelConsumptionObdCommand(); fuelConsumptionCommand.run(in, out); fuelConsumptionCommand.getFormattedResult(); float fuelConsumption = fuelConsumptionCommand.getLitersPerHour(); // get metric speed SpeedObdCommand speedCommand = new SpeedObdCommand(); speedCommand.run(in, out); speedCommand.getFormattedResult(); speed = speedCommand.getMetricSpeed(); // get l/100km kml = (100 / speed) * fuelConsumption; } /** * * @return */ @Override public String getFormattedResult() { if (useImperialUnits) { // convert to mpg return String.format("%.1f %s", getMilesPerUKGallon(), "mpg"); } return String.format("%.1f %s", kml, "l/100km"); } public float getLitersPer100Km() { return kml; } public float getMilesPerUSGallon() { return 235.2f / kml; } public float getMilesPerUKGallon() { return 282.5f / kml; } @Override public String getName() { return AvailableCommandNames.FUEL_ECONOMY.getValue(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.fuel; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.FuelTrim; /** * Get Fuel Trim. * */ public class FuelTrimObdCommand extends ObdCommand { private float fuelTrimValue = 0.0f; private final FuelTrim bank; /** * Default ctor. * * Will read the bank from parameters and construct the command accordingly. * Please, see FuelTrim enum for more details. */ public FuelTrimObdCommand(FuelTrim bank) { super(bank.getObdCommand()); this.bank = bank; } /** * @param value * @return */ private float prepareTempValue(int value) { Double perc = (value - 128) * (100.0 / 128); return Float.parseFloat(perc.toString()); } @Override public String getFormattedResult() { if (!"NODATA".equals(getResult())) { // ignore first two bytes [hh hh] of the response fuelTrimValue = prepareTempValue(buffer.get(2)); } return String.format("%.2f%s", fuelTrimValue, "%"); } /** * @return the readed Fuel Trim percentage value. */ public final float getValue() { return fuelTrimValue; } /** * @return the name of the bank in string representation. */ public final String getBank() { return bank.getBank(); } @Override public String getName() { return bank.getBank(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.fuel; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * TODO put description */ public class FuelConsumptionObdCommand extends ObdCommand { private float fuelRate = -1.0f; public FuelConsumptionObdCommand() { super("01 5E"); } public FuelConsumptionObdCommand(ObdCommand other) { super(other); } /* * (non-Javadoc) * * @see eu.lighthouselabs.obd.commands.ObdCommand#getFormattedResult() */ @Override public String getFormattedResult() { if (!"NODATA".equals(getResult())) { // ignore first two bytes [hh hh] of the response int a = buffer.get(2); int b = buffer.get(3); fuelRate = (a * 256 + b) * 0.05f; } String res = String.format("%.1f%s", fuelRate, ""); return res; } public float getLitersPerHour() { return fuelRate; } /* * (non-Javadoc) * * @see eu.lighthouselabs.obd.commands.ObdCommand#getName() */ @Override public String getName() { return AvailableCommandNames.FUEL_CONSUMPTION.getValue(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.fuel; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.commands.utils.ObdUtils; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * This command is intended to determine the vehicle fuel type. */ public class FindFuelTypeObdCommand extends ObdCommand { private int fuelType = 0; /** * Default ctor. */ public FindFuelTypeObdCommand() { super("10 51"); } /** * Copy ctor * * @param other */ public FindFuelTypeObdCommand(ObdCommand other) { super(other); } /* * (non-Javadoc) * * @see eu.lighthouselabs.obd.command.ObdCommand#getFormattedResult() */ @Override public String getFormattedResult() { String res = getResult(); if (!"NODATA".equals(res)) { // ignore first two bytes [hh hh] of the response fuelType = buffer.get(2); res = getFuelTypeName(); } return res; } /** * @return Fuel type name. */ public final String getFuelTypeName() { return ObdUtils.getFuelTypeName(fuelType); } @Override public String getName() { return AvailableCommandNames.FUEL_TYPE.getValue(); } }
Java
package eu.lighthouselabs.obd.commands.pressure; import eu.lighthouselabs.obd.enums.AvailableCommandNames; public class FuelPressureObdCommand extends PressureObdCommand { public FuelPressureObdCommand() { super("010A"); } public FuelPressureObdCommand(FuelPressureObdCommand other) { super(other); } /** * TODO * * put description of why we multiply by 3 * * @param temp * @return */ @Override protected final int preparePressureValue() { return tempValue * 3; } @Override public String getName() { return AvailableCommandNames.FUEL_PRESSURE.getValue(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.pressure; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * Intake Manifold Pressure */ public class IntakeManifoldPressureObdCommand extends PressureObdCommand { /** * Default ctor. */ public IntakeManifoldPressureObdCommand() { super("01 0B"); } /** * Copy ctor. * * @param other */ public IntakeManifoldPressureObdCommand( IntakeManifoldPressureObdCommand other) { super(other); } @Override public String getName() { return AvailableCommandNames.INTAKE_MANIFOLD_PRESSURE.getValue(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands.pressure; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.commands.SystemOfUnits; /** * TODO put description */ public abstract class PressureObdCommand extends ObdCommand implements SystemOfUnits { protected int tempValue = 0; protected int pressure = 0; /** * Default ctor * * @param cmd */ public PressureObdCommand(String cmd) { super(cmd); } /** * Copy ctor. * * @param cmd */ public PressureObdCommand(PressureObdCommand other) { super(other); } /** * Some PressureObdCommand subclasses will need to implement this method in * order to determine the final kPa value. * * *NEED* to read tempValue * * @return */ protected int preparePressureValue() { return tempValue; } /** * */ @Override public String getFormattedResult() { String res = getResult(); if (!"NODATA".equals(res)) { // ignore first two bytes [hh hh] of the response tempValue = buffer.get(2); pressure = preparePressureValue(); // this will need tempValue res = String.format("%d%s", pressure, "kPa"); if (useImperialUnits) { res = String.format("%.1f%s", getImperialUnit(), "psi"); } } return res; } /** * @return the pressure in kPa */ public int getMetricUnit() { return pressure; } /** * @return the pressure in psi */ public float getImperialUnit() { Double d = pressure * 0.145037738; return Float.valueOf(d.toString()); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands; /** * This interface will define methods for converting to/from imperial units and * from/to metric units. */ public interface SystemOfUnits { float getImperialUnit(); }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; /** * TODO put description */ public abstract class ObdCommand { protected ArrayList<Integer> buffer = null; protected String cmd = null; protected boolean useImperialUnits = false; protected String rawData = null; /** * Default ctor to use * * @param command * the command to send */ public ObdCommand(String command) { this.cmd = command; this.buffer = new ArrayList<Integer>(); } /** * Prevent empty instantiation */ private ObdCommand() { } /** * Copy ctor. * * @param other * the ObdCommand to copy. */ public ObdCommand(ObdCommand other) { this(other.cmd); } /** * Sends the OBD-II request and deals with the response. * * This method CAN be overriden in fake commands. */ public void run(InputStream in, OutputStream out) throws IOException, InterruptedException { sendCommand(out); readResult(in); } /** * Sends the OBD-II request. * * This method may be overriden in subclasses, such as ObMultiCommand or * TroubleCodesObdCommand. * * @param cmd * The command to send. */ protected void sendCommand(OutputStream out) throws IOException, InterruptedException { // add the carriage return char cmd += "\r"; // write to OutputStream, or in this case a BluetoothSocket out.write(cmd.getBytes()); out.flush(); /* * HACK GOLDEN HAMMER ahead!! * * TODO clean * * Due to the time that some systems may take to respond, let's give it * 500ms. */ Thread.sleep(200); } /** * Resends this command. * * */ protected void resendCommand(OutputStream out) throws IOException, InterruptedException { out.write("\r".getBytes()); out.flush(); /* * HACK GOLDEN HAMMER ahead!! * * TODO clean this * * Due to the time that some systems may take to respond, let's give it * 500ms. */ // Thread.sleep(250); } /** * Reads the OBD-II response. * * This method may be overriden in subclasses, such as ObdMultiCommand. */ protected void readResult(InputStream in) throws IOException { byte b = 0; StringBuilder res = new StringBuilder(); // read until '>' arrives while ((char) (b = (byte) in.read()) != '>') if ((char) b != ' ') res.append((char) b); /* * Imagine the following response 41 0c 00 0d. * * ELM sends strings!! So, ELM puts spaces between each "byte". And pay * attention to the fact that I've put the word byte in quotes, because * 41 is actually TWO bytes (two chars) in the socket. So, we must do * some more processing.. */ // rawData = res.toString().trim(); // clear buffer buffer.clear(); // read string each two chars int begin = 0; int end = 2; while (end <= rawData.length()) { String temp = "0x" + rawData.substring(begin, end); buffer.add(Integer.decode(temp)); begin = end; end += 2; } } /** * @return the raw command response in string representation. */ public String getResult() { if (rawData.contains("SEARCHING") || rawData.contains("DATA")) { rawData = "NODATA"; } return rawData; } /** * @return a formatted command response in string representation. */ public abstract String getFormattedResult(); /****************************************************************** * Getters & Setters */ /** * @return a list of integers */ public ArrayList<Integer> getBuffer() { return buffer; } /** * Returns this command in string representation. * * @return the command */ public String getCommand() { return cmd; } /** * @return true if imperial units are used, or false otherwise */ public boolean useImperialUnits() { return useImperialUnits; } /** * Set to 'true' if you want to use imperial units, false otherwise. By * default this value is set to 'false'. * * @param isImperial */ public void useImperialUnits(boolean isImperial) { this.useImperialUnits = isImperial; } /** * @return the OBD command name. */ public abstract String getName(); }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; /** * TODO put description */ public class ObdMultiCommand { private ArrayList<ObdCommand> commands; /** * Default ctor. */ public ObdMultiCommand() { this.commands = new ArrayList<ObdCommand>(); } /** * Add ObdCommand to list of ObdCommands. * * @param command */ public void add(ObdCommand command) { this.commands.add(command); } /** * Removes ObdCommand from the list of ObdCommands. * @param command */ public void remove(ObdCommand command) { this.commands.remove(command); } /** * Iterate all commands and call: * - sendCommand() * - readResult() */ public void sendCommands(InputStream in, OutputStream out) throws IOException, InterruptedException { for (ObdCommand command : commands) { /* * Send command and read response. */ command.run(in, out); } } /** * * @return */ public String getFormattedResult() { StringBuilder res = new StringBuilder(); for (ObdCommand command : commands) { res.append(command.getFormattedResult()).append(","); } return res.toString(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.commands; import eu.lighthouselabs.obd.enums.AvailableCommandNames; /** * TODO put description * * Current speed. */ public class SpeedObdCommand extends ObdCommand implements SystemOfUnits { private int metricSpeed = 0; /** * Default ctor. */ public SpeedObdCommand() { super("01 0D"); } /** * Copy ctor. * * @param other */ public SpeedObdCommand(SpeedObdCommand other) { super(other); } /** * */ public String getFormattedResult() { String res = getResult(); if (!"NODATA".equals(res)) { //Ignore first two bytes [hh hh] of the response. metricSpeed = buffer.get(2); res = String.format("%d%s", metricSpeed, "km/h"); if (useImperialUnits) res = String.format("%.2f%s", getImperialUnit(), "mph"); } return res; } /** * @return the speed in metric units. */ public int getMetricSpeed() { return metricSpeed; } /** * @return the speed in imperial units. */ public float getImperialSpeed() { return getImperialUnit(); } /** * Convert from km/h to mph */ public float getImperialUnit() { Double tempValue = metricSpeed * 0.621371192; return Float.valueOf(tempValue.toString()); } @Override public String getName() { return AvailableCommandNames.SPEED.getValue(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.enums; /** * TODO put description */ public enum AvailableCommandNames { AIR_INTAKE_TEMP("Air Intake Temperature"), AMBIENT_AIR_TEMP("Ambient Air Temperature"), ENGINE_COOLANT_TEMP("Engine Coolant Temperature"), BAROMETRIC_PRESSURE("Barometric Pressure"), FUEL_PRESSURE("Fuel Pressure"), INTAKE_MANIFOLD_PRESSURE("Intake Manifold Pressure"), ENGINE_LOAD("Engine Load"), ENGINE_RUNTIME("Engine Runtime"), ENGINE_RPM("Engine RPM"), SPEED("Vehicle Speed"), MAF("Mass Air Flow"), THROTTLE_POS("Throttle Position"), TROUBLE_CODES("Trouble Codes"), FUEL_LEVEL("Fuel Level"), FUEL_TYPE("Fuel Type"), FUEL_CONSUMPTION("Fuel Consumption"), FUEL_ECONOMY("Fuel Economy"), FUEL_ECONOMY_WITH_MAF("Fuel Economy 2"), FUEL_ECONOMY_WITHOUT_MAF("Fuel Economy 3"), TIMING_ADVANCE("Timing Advance"), DTC_NUMBER("Diagnostic Trouble Codes"), EQUIV_RATIO("Command Equivalence Ratio"); private final String value; /** * * @param value */ private AvailableCommandNames(String value) { this.value = value; } /** * * @return */ public final String getValue() { return value; } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.enums; /** * All OBD protocols. */ public enum ObdProtocols { /** * Auto select protocol and save. */ AUTO('0'), /** * 41.6 kbaud */ SAE_J1850_PWM('1'), /** * 10.4 kbaud */ SAE_J1850_VPW('2'), /** * 5 baud init */ ISO_9141_2('3'), /** * 5 baud init */ ISO_14230_4_KWP('4'), /** * Fast init */ ISO_14230_4_KWP_FAST('5'), /** * 11 bit ID, 500 kbaud */ ISO_15765_4_CAN('6'), /** * 29 bit ID, 500 kbaud */ ISO_15765_4_CAN_B('7'), /** * 11 bit ID, 250 kbaud */ ISO_15765_4_CAN_C('8'), /** * 29 bit ID, 250 kbaud */ ISO_15765_4_CAN_D('9'), /** * 29 bit ID, 250 kbaud (user adjustable) */ SAE_J1939_CAN('A'), /** * 11 bit ID (user adjustable), 125 kbaud (user adjustable) */ USER1_CAN('B'), /** * 11 bit ID (user adjustable), 50 kbaud (user adjustable) */ USER2_CAN('C'); private final char value; ObdProtocols(char value) { this.value = value; } public char getValue() { return value; } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.enums; /** * Select one of the Fuel Trim percentage banks to access. */ public enum FuelTrim { SHORT_TERM_BANK_1(0x06), LONG_TERM_BANK_1(0x07), SHORT_TERM_BANK_2(0x08), LONG_TERM_BANK_2(0x09); private final int value; /** * * @param value */ private FuelTrim(int value) { this.value = value; } /** * * @return */ public final int getValue() { return value; } /** * * @return */ public final String getObdCommand() { return new String("01 " + value); } public final String getBank() { String res = "NODATA"; switch (value) { case 0x06: res = "Short Term Fuel Trim Bank 1"; break; case 0x07: res = "Long Term Fuel Trim Bank 1"; break; case 0x08: res = "Short Term Fuel Trim Bank 2"; break; case 0x09: res = "Long Term Fuel Trim Bank 2"; break; default: break; } return res; } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.enums; import eu.lighthouselabs.obd.commands.utils.ObdUtils; /** * MODE 1 PID 0x51 will return one of the following values to identify the fuel * type of the vehicle. */ public enum FuelType { GASOLINE(0x01), METHANOL(0x02), ETHANOL(0x03), DIESEL(0x04), LPG(0x05), CNG(0x06), PROPANE(0x07), ELECTRIC(0x08), BIFUEL_GASOLINE(0x09), BIFUEL_METHANOL(0x0A), BIFUEL_ETHANOL(0x0B), BIFUEL_LPG(0x0C), BIFUEL_CNG(0x0D), BIFUEL_PROPANE(0x0E), BIFUEL_ELECTRIC(0x0F), BIFUEL_GASOLINE_ELECTRIC(0x10), HYBRID_GASOLINE(0x11), HYBRID_ETHANOL(0x12), HYBRID_DIESEL(0x13), HYBRID_ELECTRIC(0x14), HYBRID_MIXED(0x15), HYBRID_REGENERATIVE(0x16); private final int value; /** * * @param value */ private FuelType(int value) { this.value = value; } /** * * @return */ public final int getValue() { return value; } /** * * @return */ public final String getName() { return ObdUtils.getFuelTypeName(value); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.reader.config; import java.util.ArrayList; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.commands.SpeedObdCommand; import eu.lighthouselabs.obd.commands.control.CommandEquivRatioObdCommand; import eu.lighthouselabs.obd.commands.control.DtcNumberObdCommand; import eu.lighthouselabs.obd.commands.control.TimingAdvanceObdCommand; import eu.lighthouselabs.obd.commands.control.TroubleCodesObdCommand; import eu.lighthouselabs.obd.commands.engine.EngineLoadObdCommand; import eu.lighthouselabs.obd.commands.engine.EngineRPMObdCommand; import eu.lighthouselabs.obd.commands.engine.EngineRuntimeObdCommand; import eu.lighthouselabs.obd.commands.engine.MassAirFlowObdCommand; import eu.lighthouselabs.obd.commands.engine.ThrottlePositionObdCommand; import eu.lighthouselabs.obd.commands.fuel.FindFuelTypeObdCommand; import eu.lighthouselabs.obd.commands.fuel.FuelLevelObdCommand; import eu.lighthouselabs.obd.commands.fuel.FuelTrimObdCommand; import eu.lighthouselabs.obd.commands.pressure.BarometricPressureObdCommand; import eu.lighthouselabs.obd.commands.pressure.FuelPressureObdCommand; import eu.lighthouselabs.obd.commands.pressure.IntakeManifoldPressureObdCommand; import eu.lighthouselabs.obd.commands.protocol.ObdResetCommand; import eu.lighthouselabs.obd.commands.temperature.AirIntakeTemperatureObdCommand; import eu.lighthouselabs.obd.commands.temperature.AmbientAirTemperatureObdCommand; import eu.lighthouselabs.obd.commands.temperature.EngineCoolantTemperatureObdCommand; import eu.lighthouselabs.obd.enums.FuelTrim; /** * TODO put description */ public final class ObdConfig { public static ArrayList<ObdCommand> getCommands() { ArrayList<ObdCommand> cmds = new ArrayList<ObdCommand>(); // Protocol cmds.add(new ObdResetCommand()); // Control cmds.add(new CommandEquivRatioObdCommand()); cmds.add(new DtcNumberObdCommand()); cmds.add(new TimingAdvanceObdCommand()); cmds.add(new TroubleCodesObdCommand(0)); // Engine cmds.add(new EngineLoadObdCommand()); cmds.add(new EngineRPMObdCommand()); cmds.add(new EngineRuntimeObdCommand()); cmds.add(new MassAirFlowObdCommand()); // Fuel // cmds.add(new AverageFuelEconomyObdCommand()); // cmds.add(new FuelEconomyObdCommand()); // cmds.add(new FuelEconomyMAPObdCommand()); // cmds.add(new FuelEconomyCommandedMAPObdCommand()); cmds.add(new FindFuelTypeObdCommand()); cmds.add(new FuelLevelObdCommand()); cmds.add(new FuelTrimObdCommand(FuelTrim.LONG_TERM_BANK_1)); cmds.add(new FuelTrimObdCommand(FuelTrim.LONG_TERM_BANK_2)); cmds.add(new FuelTrimObdCommand(FuelTrim.SHORT_TERM_BANK_1)); cmds.add(new FuelTrimObdCommand(FuelTrim.SHORT_TERM_BANK_2)); // Pressure cmds.add(new BarometricPressureObdCommand()); cmds.add(new FuelPressureObdCommand()); cmds.add(new IntakeManifoldPressureObdCommand()); // Temperature cmds.add(new AirIntakeTemperatureObdCommand()); cmds.add(new AmbientAirTemperatureObdCommand()); cmds.add(new EngineCoolantTemperatureObdCommand()); // Misc cmds.add(new SpeedObdCommand()); cmds.add(new ThrottlePositionObdCommand()); return cmds; } }
Java
package eu.lighthouselabs.obd.reader.network; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.util.Iterator; import java.util.Map; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; public class DataUploader { public String uploadRecord(String urlStr, Map<String,String> data) throws IOException, URISyntaxException { String encData = getEncodedData(data); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 5000); HttpConnectionParams.setSoTimeout(params, 30000); HttpClient client = new DefaultHttpClient(params); HttpPost request = new HttpPost(); request.setURI(new URI(urlStr)); request.setHeader("Content-Type", "application/x-www-form-urlencoded"); request.setEntity(new StringEntity(encData)); ResponseHandler<String> resHandle = new BasicResponseHandler(); String response = client.execute(request,resHandle); return response; } public String getEncodedData(Map<String,String> data) throws UnsupportedEncodingException { StringBuffer buff = new StringBuffer(); Iterator<String> keys = data.keySet().iterator(); while (keys.hasNext()) { String k = keys.next(); buff.append(URLEncoder.encode(k,"UTF-8")); buff.append("="); buff.append(URLEncoder.encode(data.get(k),"UTF-8")); buff.append("&"); } return buff.toString(); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.reader; import eu.lighthouselabs.obd.reader.io.ObdCommandJob; /** * TODO put description */ public interface IPostMonitor { void setListener(IPostListener callback); boolean isRunning(); void executeQueue(); void addJobToQueue(ObdCommandJob job); }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.reader; import eu.lighthouselabs.obd.reader.io.ObdCommandJob; /** * TODO put description */ public interface IPostListener { void stateUpdate(ObdCommandJob job); }
Java
package eu.lighthouselabs.obd.reader.drawable; import eu.lighthouselabs.obd.reader.R; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.util.AttributeSet; public class CoolantGaugeView extends GradientGaugeView { public final static int min_temp = 35; public final static int max_temp = 138; public final static int TEXT_SIZE = 18; public final static int range = max_temp - min_temp; private int temp = min_temp; public CoolantGaugeView(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; paint = new Paint(); paint.setTextSize(TEXT_SIZE); Typeface bold = Typeface.defaultFromStyle(Typeface.BOLD); paint.setTypeface(bold); paint.setStrokeWidth(3); paint.setStyle(Paint.Style.FILL_AND_STROKE); } public void setTemp(int temp) { this.temp = temp; if (this.temp < min_temp) { this.temp = min_temp + 2; } if (this.temp > max_temp) { this.temp = max_temp; } invalidate(); } @Override protected void onDraw(Canvas canvas) { Resources res = context.getResources(); Drawable container = (Drawable) res.getDrawable(R.drawable.coolant_gauge); int width = getWidth(); int left = getLeft(); int top = getTop(); paint.setColor(Color.BLUE); canvas.drawText("C",left,top+TEXT_SIZE,paint); paint.setColor(Color.RED); canvas.drawText("H", left+width-TEXT_SIZE, top+TEXT_SIZE, paint); drawGradient(canvas, container, TEXT_SIZE+5, temp-min_temp,range); } }
Java
package eu.lighthouselabs.obd.reader.drawable; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.RectShape; import android.util.AttributeSet; import android.util.Log; import android.view.View; public abstract class GradientGaugeView extends View { protected Context context = null; protected Paint paint = null; public GradientGaugeView(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; paint = new Paint(); } @Override protected abstract void onDraw(Canvas canvas); protected void drawGradient(Canvas canvas, Drawable container, int offset, double value, double range) { int width = getWidth(); int height = getHeight(); int left = getLeft(); int top = getTop(); Log.i("width",String.format("%d %d",width,left)); container.setBounds(left,top+offset,left+width,top+height+offset); container.draw(canvas); ShapeDrawable cover = new ShapeDrawable(new RectShape()); double perc = value / range; int coverLeft = (int)(width * perc); cover.setBounds(left+coverLeft, top+offset, left+width, top+height+offset); cover.draw(canvas); } }
Java
package eu.lighthouselabs.obd.reader.drawable; import eu.lighthouselabs.obd.reader.R; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.util.AttributeSet; public class AccelGaugeView extends GradientGaugeView { public final static int TEXT_SIZE = 15; public final static int range = 20; private double accel = 2; public AccelGaugeView(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; paint = new Paint(); paint.setTextSize(TEXT_SIZE); Typeface bold = Typeface.defaultFromStyle(Typeface.BOLD); paint.setTypeface(bold); paint.setStrokeWidth(3); paint.setStyle(Paint.Style.FILL); } public void setAccel(double accel) { this.accel = accel; } @Override protected void onDraw(Canvas canvas) { Resources res = context.getResources(); Drawable container = (Drawable) res.getDrawable(R.drawable.accel_gauge); int width = getWidth(); int left = getLeft(); int top = getTop(); paint.setColor(Color.GREEN); canvas.drawText("Soft",left,top+TEXT_SIZE,paint); paint.setColor(Color.RED); canvas.drawText("Hard", left+width-TEXT_SIZE*3, top+TEXT_SIZE, paint); drawGradient(canvas, container, TEXT_SIZE+5, accel, range); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.reader.activity; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.bluetooth.BluetoothAdapter; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import android.os.PowerManager; import android.preference.PreferenceManager; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.ViewGroup.MarginLayoutParams; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import eu.lighthouselabs.obd.commands.SpeedObdCommand; import eu.lighthouselabs.obd.commands.control.CommandEquivRatioObdCommand; import eu.lighthouselabs.obd.commands.engine.EngineRPMObdCommand; import eu.lighthouselabs.obd.commands.engine.MassAirFlowObdCommand; import eu.lighthouselabs.obd.commands.fuel.FuelEconomyObdCommand; import eu.lighthouselabs.obd.commands.fuel.FuelEconomyWithMAFObdCommand; import eu.lighthouselabs.obd.commands.fuel.FuelLevelObdCommand; import eu.lighthouselabs.obd.commands.fuel.FuelTrimObdCommand; import eu.lighthouselabs.obd.commands.temperature.AmbientAirTemperatureObdCommand; import eu.lighthouselabs.obd.enums.AvailableCommandNames; import eu.lighthouselabs.obd.enums.FuelTrim; import eu.lighthouselabs.obd.enums.FuelType; import eu.lighthouselabs.obd.reader.IPostListener; import eu.lighthouselabs.obd.reader.R; import eu.lighthouselabs.obd.reader.io.ObdCommandJob; import eu.lighthouselabs.obd.reader.io.ObdGatewayService; import eu.lighthouselabs.obd.reader.io.ObdGatewayServiceConnection; /** * The main activity. */ public class MainActivity extends Activity { private static final String TAG = "MainActivity"; /* * TODO put description */ static final int NO_BLUETOOTH_ID = 0; static final int BLUETOOTH_DISABLED = 1; static final int NO_GPS_ID = 2; static final int START_LIVE_DATA = 3; static final int STOP_LIVE_DATA = 4; static final int SETTINGS = 5; static final int COMMAND_ACTIVITY = 6; static final int TABLE_ROW_MARGIN = 7; static final int NO_ORIENTATION_SENSOR = 8; private Handler mHandler = new Handler(); /** * Callback for ObdGatewayService to update UI. */ private IPostListener mListener = null; private Intent mServiceIntent = null; private ObdGatewayServiceConnection mServiceConnection = null; private SensorManager sensorManager = null; private Sensor orientSensor = null; private SharedPreferences prefs = null; private PowerManager powerManager = null; private PowerManager.WakeLock wakeLock = null; private boolean preRequisites = true; private int speed = 1; private double maf = 1; private float ltft = 0; private double equivRatio = 1; private final SensorEventListener orientListener = new SensorEventListener() { public void onSensorChanged(SensorEvent event) { float x = event.values[0]; String dir = ""; if (x >= 337.5 || x < 22.5) { dir = "N"; } else if (x >= 22.5 && x < 67.5) { dir = "NE"; } else if (x >= 67.5 && x < 112.5) { dir = "E"; } else if (x >= 112.5 && x < 157.5) { dir = "SE"; } else if (x >= 157.5 && x < 202.5) { dir = "S"; } else if (x >= 202.5 && x < 247.5) { dir = "SW"; } else if (x >= 247.5 && x < 292.5) { dir = "W"; } else if (x >= 292.5 && x < 337.5) { dir = "NW"; } TextView compass = (TextView) findViewById(R.id.compass_text); updateTextView(compass, dir); } public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO Auto-generated method stub } }; public void updateTextView(final TextView view, final String txt) { new Handler().post(new Runnable() { public void run() { view.setText(txt); } }); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* * TODO clean-up this upload thing * * ExceptionHandler.register(this, * "http://www.whidbeycleaning.com/droid/server.php"); */ setContentView(R.layout.main); mListener = new IPostListener() { public void stateUpdate(ObdCommandJob job) { String cmdName = job.getCommand().getName(); String cmdResult = job.getCommand().getFormattedResult(); Log.d(TAG, FuelTrim.LONG_TERM_BANK_1.getBank() + " equals " + cmdName + "?"); if (AvailableCommandNames.ENGINE_RPM.getValue().equals(cmdName)) { TextView tvRpm = (TextView) findViewById(R.id.rpm_text); tvRpm.setText(cmdResult); } else if (AvailableCommandNames.SPEED.getValue().equals( cmdName)) { TextView tvSpeed = (TextView) findViewById(R.id.spd_text); tvSpeed.setText(cmdResult); speed = ((SpeedObdCommand) job.getCommand()) .getMetricSpeed(); } else if (AvailableCommandNames.MAF.getValue().equals(cmdName)) { maf = ((MassAirFlowObdCommand) job.getCommand()).getMAF(); addTableRow(cmdName, cmdResult); } else if (FuelTrim.LONG_TERM_BANK_1.getBank().equals(cmdName)) { ltft = ((FuelTrimObdCommand) job.getCommand()).getValue(); } else if (AvailableCommandNames.EQUIV_RATIO.getValue().equals(cmdName)) { equivRatio = ((CommandEquivRatioObdCommand) job.getCommand()).getRatio(); addTableRow(cmdName, cmdResult); } else { addTableRow(cmdName, cmdResult); } } }; /* * Validate GPS service. */ LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (locationManager.getProvider(LocationManager.GPS_PROVIDER) == null) { /* * TODO for testing purposes we'll not make GPS a pre-requisite. */ // preRequisites = false; showDialog(NO_GPS_ID); } /* * Validate Bluetooth service. */ // Bluetooth device exists? final BluetoothAdapter mBtAdapter = BluetoothAdapter .getDefaultAdapter(); if (mBtAdapter == null) { preRequisites = false; showDialog(NO_BLUETOOTH_ID); } else { // Bluetooth device is enabled? if (!mBtAdapter.isEnabled()) { preRequisites = false; showDialog(BLUETOOTH_DISABLED); } } /* * Get Orientation sensor. */ sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); List<Sensor> sens = sensorManager .getSensorList(Sensor.TYPE_ORIENTATION); if (sens.size() <= 0) { showDialog(NO_ORIENTATION_SENSOR); } else { orientSensor = sens.get(0); } // validate app pre-requisites if (preRequisites) { /* * Prepare service and its connection */ mServiceIntent = new Intent(this, ObdGatewayService.class); mServiceConnection = new ObdGatewayServiceConnection(); mServiceConnection.setServiceListener(mListener); // bind service Log.d(TAG, "Binding service.."); bindService(mServiceIntent, mServiceConnection, Context.BIND_AUTO_CREATE); } } @Override protected void onDestroy() { super.onDestroy(); releaseWakeLockIfHeld(); mServiceIntent = null; mServiceConnection = null; mListener = null; mHandler = null; } @Override protected void onPause() { super.onPause(); Log.d(TAG, "Pausing.."); releaseWakeLockIfHeld(); } /** * If lock is held, release. Lock will be held when the service is running. */ private void releaseWakeLockIfHeld() { if (wakeLock.isHeld()) { wakeLock.release(); } } protected void onResume() { super.onResume(); Log.d(TAG, "Resuming.."); sensorManager.registerListener(orientListener, orientSensor, SensorManager.SENSOR_DELAY_UI); prefs = PreferenceManager.getDefaultSharedPreferences(this); powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "ObdReader"); } private void updateConfig() { Intent configIntent = new Intent(this, ConfigActivity.class); startActivity(configIntent); } public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, START_LIVE_DATA, 0, "Start Live Data"); menu.add(0, COMMAND_ACTIVITY, 0, "Run Command"); menu.add(0, STOP_LIVE_DATA, 0, "Stop"); menu.add(0, SETTINGS, 0, "Settings"); return true; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case START_LIVE_DATA: startLiveData(); return true; case STOP_LIVE_DATA: stopLiveData(); return true; case SETTINGS: updateConfig(); return true; // case COMMAND_ACTIVITY: // staticCommand(); // return true; } return false; } // private void staticCommand() { // Intent commandIntent = new Intent(this, ObdReaderCommandActivity.class); // startActivity(commandIntent); // } private void startLiveData() { Log.d(TAG, "Starting live data.."); if (!mServiceConnection.isRunning()) { Log.d(TAG, "Service is not running. Going to start it.."); startService(mServiceIntent); } // start command execution mHandler.post(mQueueCommands); // screen won't turn off until wakeLock.release() wakeLock.acquire(); } private void stopLiveData() { Log.d(TAG, "Stopping live data.."); if (mServiceConnection.isRunning()) stopService(mServiceIntent); // remove runnable mHandler.removeCallbacks(mQueueCommands); releaseWakeLockIfHeld(); } protected Dialog onCreateDialog(int id) { AlertDialog.Builder build = new AlertDialog.Builder(this); switch (id) { case NO_BLUETOOTH_ID: build.setMessage("Sorry, your device doesn't support Bluetooth."); return build.create(); case BLUETOOTH_DISABLED: build.setMessage("You have Bluetooth disabled. Please enable it!"); return build.create(); case NO_GPS_ID: build.setMessage("Sorry, your device doesn't support GPS."); return build.create(); case NO_ORIENTATION_SENSOR: build.setMessage("Orientation sensor missing?"); return build.create(); } return null; } public boolean onPrepareOptionsMenu(Menu menu) { MenuItem startItem = menu.findItem(START_LIVE_DATA); MenuItem stopItem = menu.findItem(STOP_LIVE_DATA); MenuItem settingsItem = menu.findItem(SETTINGS); MenuItem commandItem = menu.findItem(COMMAND_ACTIVITY); // validate if preRequisites are satisfied. if (preRequisites) { if (mServiceConnection.isRunning()) { startItem.setEnabled(false); stopItem.setEnabled(true); settingsItem.setEnabled(false); commandItem.setEnabled(false); } else { stopItem.setEnabled(false); startItem.setEnabled(true); settingsItem.setEnabled(true); commandItem.setEnabled(false); } } else { startItem.setEnabled(false); stopItem.setEnabled(false); settingsItem.setEnabled(false); commandItem.setEnabled(false); } return true; } private void addTableRow(String key, String val) { TableLayout tl = (TableLayout) findViewById(R.id.data_table); TableRow tr = new TableRow(this); MarginLayoutParams params = new ViewGroup.MarginLayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); params.setMargins(TABLE_ROW_MARGIN, TABLE_ROW_MARGIN, TABLE_ROW_MARGIN, TABLE_ROW_MARGIN); tr.setLayoutParams(params); tr.setBackgroundColor(Color.BLACK); TextView name = new TextView(this); name.setGravity(Gravity.RIGHT); name.setText(key + ": "); TextView value = new TextView(this); value.setGravity(Gravity.LEFT); value.setText(val); tr.addView(name); tr.addView(value); tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); /* * TODO remove this hack * * let's define a limit number of rows */ if (tl.getChildCount() > 10) tl.removeViewAt(0); } /** * */ private Runnable mQueueCommands = new Runnable() { public void run() { /* * If values are not default, then we have values to calculate MPG */ Log.d(TAG, "SPD:" + speed + ", MAF:" + maf + ", LTFT:" + ltft); if (speed > 1 && maf > 1 && ltft != 0) { FuelEconomyWithMAFObdCommand fuelEconCmd = new FuelEconomyWithMAFObdCommand( FuelType.DIESEL, speed, maf, ltft, false /* TODO */); TextView tvMpg = (TextView) findViewById(R.id.fuel_econ_text); String liters100km = String.format("%.2f", fuelEconCmd.getLitersPer100Km()); tvMpg.setText("" + liters100km); Log.d(TAG, "FUELECON:" + liters100km); } if (mServiceConnection.isRunning()) queueCommands(); // run again in 2s mHandler.postDelayed(mQueueCommands, 2000); } }; /** * */ private void queueCommands() { final ObdCommandJob airTemp = new ObdCommandJob( new AmbientAirTemperatureObdCommand()); final ObdCommandJob speed = new ObdCommandJob(new SpeedObdCommand()); final ObdCommandJob fuelEcon = new ObdCommandJob( new FuelEconomyObdCommand()); final ObdCommandJob rpm = new ObdCommandJob(new EngineRPMObdCommand()); final ObdCommandJob maf = new ObdCommandJob(new MassAirFlowObdCommand()); final ObdCommandJob fuelLevel = new ObdCommandJob( new FuelLevelObdCommand()); final ObdCommandJob ltft1 = new ObdCommandJob(new FuelTrimObdCommand( FuelTrim.LONG_TERM_BANK_1)); final ObdCommandJob ltft2 = new ObdCommandJob(new FuelTrimObdCommand( FuelTrim.LONG_TERM_BANK_2)); final ObdCommandJob stft1 = new ObdCommandJob(new FuelTrimObdCommand( FuelTrim.SHORT_TERM_BANK_1)); final ObdCommandJob stft2 = new ObdCommandJob(new FuelTrimObdCommand( FuelTrim.SHORT_TERM_BANK_2)); final ObdCommandJob equiv = new ObdCommandJob(new CommandEquivRatioObdCommand()); // mServiceConnection.addJobToQueue(airTemp); mServiceConnection.addJobToQueue(speed); // mServiceConnection.addJobToQueue(fuelEcon); mServiceConnection.addJobToQueue(rpm); mServiceConnection.addJobToQueue(maf); mServiceConnection.addJobToQueue(fuelLevel); // mServiceConnection.addJobToQueue(equiv); mServiceConnection.addJobToQueue(ltft1); // mServiceConnection.addJobToQueue(ltft2); // mServiceConnection.addJobToQueue(stft1); // mServiceConnection.addJobToQueue(stft2); } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.reader.activity; import java.util.ArrayList; import java.util.Set; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.preference.PreferenceScreen; import android.widget.Toast; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.reader.R; import eu.lighthouselabs.obd.reader.config.ObdConfig; /** * Configuration activity. */ public class ConfigActivity extends PreferenceActivity implements OnPreferenceChangeListener { public static final String BLUETOOTH_LIST_KEY = "bluetooth_list_preference"; public static final String UPLOAD_URL_KEY = "upload_url_preference"; public static final String UPLOAD_DATA_KEY = "upload_data_preference"; public static final String UPDATE_PERIOD_KEY = "update_period_preference"; public static final String VEHICLE_ID_KEY = "vehicle_id_preference"; public static final String ENGINE_DISPLACEMENT_KEY = "engine_displacement_preference"; public static final String VOLUMETRIC_EFFICIENCY_KEY = "volumetric_efficiency_preference"; public static final String IMPERIAL_UNITS_KEY = "imperial_units_preference"; public static final String COMMANDS_SCREEN_KEY = "obd_commands_screen"; public static final String ENABLE_GPS_KEY = "enable_gps_preference"; public static final String MAX_FUEL_ECON_KEY = "max_fuel_econ_preference"; public static final String CONFIG_READER_KEY = "reader_config_preference"; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* * Read preferences resources available at res/xml/preferences.xml */ addPreferencesFromResource(R.xml.preferences); ArrayList<CharSequence> pairedDeviceStrings = new ArrayList<CharSequence>(); ArrayList<CharSequence> vals = new ArrayList<CharSequence>(); ListPreference listBtDevices = (ListPreference) getPreferenceScreen() .findPreference(BLUETOOTH_LIST_KEY); String[] prefKeys = new String[] { ENGINE_DISPLACEMENT_KEY, VOLUMETRIC_EFFICIENCY_KEY, UPDATE_PERIOD_KEY, MAX_FUEL_ECON_KEY }; for (String prefKey : prefKeys) { EditTextPreference txtPref = (EditTextPreference) getPreferenceScreen() .findPreference(prefKey); txtPref.setOnPreferenceChangeListener(this); } /* * Available OBD commands * * TODO This should be read from preferences database */ ArrayList<ObdCommand> cmds = ObdConfig.getCommands(); PreferenceScreen cmdScr = (PreferenceScreen) getPreferenceScreen() .findPreference(COMMANDS_SCREEN_KEY); for (ObdCommand cmd : cmds) { CheckBoxPreference cpref = new CheckBoxPreference(this); cpref.setTitle(cmd.getName()); cpref.setKey(cmd.getName()); cpref.setChecked(true); cmdScr.addPreference(cpref); } /* * Let's use this device Bluetooth adapter to select which paired OBD-II * compliant device we'll use. */ final BluetoothAdapter mBtAdapter = BluetoothAdapter .getDefaultAdapter(); if (mBtAdapter == null) { listBtDevices.setEntries(pairedDeviceStrings .toArray(new CharSequence[0])); listBtDevices.setEntryValues(vals.toArray(new CharSequence[0])); // we shouldn't get here, still warn user Toast.makeText(this, "This device does not support Bluetooth.", Toast.LENGTH_LONG); return; } /* * Listen for preferences click. * * TODO there are so many repeated validations :-/ */ final Activity thisActivity = this; listBtDevices.setEntries(new CharSequence[1]); listBtDevices.setEntryValues(new CharSequence[1]); listBtDevices .setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { // see what I mean in the previous comment? if (mBtAdapter == null || !mBtAdapter.isEnabled()) { Toast.makeText( thisActivity, "This device does not support Bluetooth or it is disabled.", Toast.LENGTH_LONG); return false; } return true; } }); /* * Get paired devices and populate preference list. */ Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { pairedDeviceStrings.add(device.getName() + "\n" + device.getAddress()); vals.add(device.getAddress()); } } listBtDevices.setEntries(pairedDeviceStrings .toArray(new CharSequence[0])); listBtDevices.setEntryValues(vals.toArray(new CharSequence[0])); } /** * OnPreferenceChangeListener method that will validate a preferencen new * value when it's changed. * * @param preference * the changed preference * @param newValue * the value to be validated and set if valid */ public boolean onPreferenceChange(Preference preference, Object newValue) { if (UPDATE_PERIOD_KEY.equals(preference.getKey()) || VOLUMETRIC_EFFICIENCY_KEY.equals(preference.getKey()) || ENGINE_DISPLACEMENT_KEY.equals(preference.getKey()) || UPDATE_PERIOD_KEY.equals(preference.getKey()) || MAX_FUEL_ECON_KEY.equals(preference.getKey())) { try { Double.parseDouble(newValue.toString()); return true; } catch (Exception e) { Toast.makeText( this, "Couldn't parse '" + newValue.toString() + "' as a number.", Toast.LENGTH_LONG).show(); } } return false; } /** * * @param prefs * @return */ public static int getUpdatePeriod(SharedPreferences prefs) { String periodString = prefs.getString(ConfigActivity.UPDATE_PERIOD_KEY, "4"); // 4 as in seconds int period = 4000; // by default 4000ms try { period = Integer.parseInt(periodString) * 1000; } catch (Exception e) { } if (period <= 0) { period = 250; } return period; } /** * * @param prefs * @return */ public static double getVolumetricEfficieny(SharedPreferences prefs) { String veString = prefs.getString( ConfigActivity.VOLUMETRIC_EFFICIENCY_KEY, ".85"); double ve = 0.85; try { ve = Double.parseDouble(veString); } catch (Exception e) { } return ve; } /** * * @param prefs * @return */ public static double getEngineDisplacement(SharedPreferences prefs) { String edString = prefs.getString( ConfigActivity.ENGINE_DISPLACEMENT_KEY, "1.6"); double ed = 1.6; try { ed = Double.parseDouble(edString); } catch (Exception e) { } return ed; } /** * * @param prefs * @return */ public static ArrayList<ObdCommand> getObdCommands(SharedPreferences prefs) { ArrayList<ObdCommand> cmds = ObdConfig.getCommands(); ArrayList<ObdCommand> ucmds = new ArrayList<ObdCommand>(); for (int i = 0; i < cmds.size(); i++) { ObdCommand cmd = cmds.get(i); boolean selected = prefs.getBoolean(cmd.getName(), true); if (selected) { ucmds.add(cmd); } } return ucmds; } /** * * @param prefs * @return */ public static double getMaxFuelEconomy(SharedPreferences prefs) { String maxStr = prefs.getString(ConfigActivity.MAX_FUEL_ECON_KEY, "70"); double max = 70; try { max = Double.parseDouble(maxStr); } catch (Exception e) { } return max; } /** * * @param prefs * @return */ public static String[] getReaderConfigCommands(SharedPreferences prefs) { String cmdsStr = prefs.getString(CONFIG_READER_KEY, "atsp0\natz"); String[] cmds = cmdsStr.split("\n"); return cmds; } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.reader.io; import java.io.IOException; import java.util.ArrayList; import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.location.LocationManager; import android.os.Binder; import android.os.IBinder; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.commands.protocol.EchoOffObdCommand; import eu.lighthouselabs.obd.commands.protocol.LineFeedOffObdCommand; import eu.lighthouselabs.obd.commands.protocol.ObdResetCommand; import eu.lighthouselabs.obd.commands.protocol.SelectProtocolObdCommand; import eu.lighthouselabs.obd.commands.protocol.TimeoutObdCommand; import eu.lighthouselabs.obd.commands.temperature.AmbientAirTemperatureObdCommand; import eu.lighthouselabs.obd.enums.ObdProtocols; import eu.lighthouselabs.obd.reader.IPostListener; import eu.lighthouselabs.obd.reader.IPostMonitor; import eu.lighthouselabs.obd.reader.R; import eu.lighthouselabs.obd.reader.activity.ConfigActivity; import eu.lighthouselabs.obd.reader.activity.MainActivity; import eu.lighthouselabs.obd.reader.io.ObdCommandJob.ObdCommandJobState; /** * This service is primarily responsible for establishing and maintaining a * permanent connection between the device where the application runs and a more * OBD Bluetooth interface. * * Secondarily, it will serve as a repository of ObdCommandJobs and at the same * time the application state-machine. */ public class ObdGatewayService extends Service { private static final String TAG = "ObdGatewayService"; private IPostListener _callback = null; private final Binder _binder = new LocalBinder(); private AtomicBoolean _isRunning = new AtomicBoolean(false); private NotificationManager _notifManager; private BlockingQueue<ObdCommandJob> _queue = new LinkedBlockingQueue<ObdCommandJob>(); private AtomicBoolean _isQueueRunning = new AtomicBoolean(false); private Long _queueCounter = 0L; private BluetoothDevice _dev = null; private BluetoothSocket _sock = null; /* * http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html * #createRfcommSocketToServiceRecord(java.util.UUID) * * "Hint: If you are connecting to a Bluetooth serial board then try using * the well-known SPP UUID 00001101-0000-1000-8000-00805F9B34FB. However if * you are connecting to an Android peer then please generate your own * unique UUID." */ private static final UUID MY_UUID = UUID .fromString("00001101-0000-1000-8000-00805F9B34FB"); /** * As long as the service is bound to another component, say an Activity, it * will remain alive. */ @Override public IBinder onBind(Intent intent) { return _binder; } @Override public void onCreate() { _notifManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); showNotification(); } @Override public void onDestroy() { stopService(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "Received start id " + startId + ": " + intent); /* * Register listener Start OBD connection */ startService(); /* * We want this service to continue running until it is explicitly * stopped, so return sticky. */ return START_STICKY; } private void startService() { Log.d(TAG, "Starting service.."); /* * Retrieve preferences */ SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(this); /* * Let's get the remote Bluetooth device */ String remoteDevice = prefs.getString( ConfigActivity.BLUETOOTH_LIST_KEY, null); if (remoteDevice == null || "".equals(remoteDevice)) { Toast.makeText(this, "No Bluetooth device selected", Toast.LENGTH_LONG).show(); // log error Log.e(TAG, "No Bluetooth device has been selected."); // TODO kill this service gracefully stopService(); } final BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); _dev = btAdapter.getRemoteDevice(remoteDevice); /* * TODO put this as deprecated Determine if upload is enabled */ // boolean uploadEnabled = prefs.getBoolean( // ConfigActivity.UPLOAD_DATA_KEY, false); // String uploadUrl = null; // if (uploadEnabled) { // uploadUrl = prefs.getString(ConfigActivity.UPLOAD_URL_KEY, // null); // } /* * Get GPS */ LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); boolean gps = prefs.getBoolean(ConfigActivity.ENABLE_GPS_KEY, false); /* * TODO clean * * Get more preferences */ int period = ConfigActivity.getUpdatePeriod(prefs); double ve = ConfigActivity.getVolumetricEfficieny(prefs); double ed = ConfigActivity.getEngineDisplacement(prefs); boolean imperialUnits = prefs.getBoolean( ConfigActivity.IMPERIAL_UNITS_KEY, false); ArrayList<ObdCommand> cmds = ConfigActivity.getObdCommands(prefs); /* * Establish Bluetooth connection * * Because discovery is a heavyweight procedure for the Bluetooth * adapter, this method should always be called before attempting to * connect to a remote device with connect(). Discovery is not managed * by the Activity, but is run as a system service, so an application * should always call cancel discovery even if it did not directly * request a discovery, just to be sure. If Bluetooth state is not * STATE_ON, this API will return false. * * see * http://developer.android.com/reference/android/bluetooth/BluetoothAdapter * .html#cancelDiscovery() */ Log.d(TAG, "Stopping Bluetooth discovery."); btAdapter.cancelDiscovery(); Toast.makeText(this, "Starting OBD connection..", Toast.LENGTH_SHORT); try { startObdConnection(); } catch (Exception e) { Log.e(TAG, "There was an error while establishing connection. -> " + e.getMessage()); // in case of failure, stop this service. stopService(); } } /** * Start and configure the connection to the OBD interface. * * @throws IOException */ private void startObdConnection() throws IOException { Log.d(TAG, "Starting OBD connection.."); // Instantiate a BluetoothSocket for the remote device and connect it. _sock = _dev.createRfcommSocketToServiceRecord(MY_UUID); _sock.connect(); // Let's configure the connection. Log.d(TAG, "Queing jobs for connection configuration.."); queueJob(new ObdCommandJob(new ObdResetCommand())); queueJob(new ObdCommandJob(new EchoOffObdCommand())); /* * Will send second-time based on tests. * * TODO this can be done w/o having to queue jobs by just issuing * command.run(), command.getResult() and validate the result. */ queueJob(new ObdCommandJob(new EchoOffObdCommand())); queueJob(new ObdCommandJob(new LineFeedOffObdCommand())); queueJob(new ObdCommandJob(new TimeoutObdCommand(62))); // For now set protocol to AUTO queueJob(new ObdCommandJob(new SelectProtocolObdCommand( ObdProtocols.AUTO))); // Job for returning dummy data queueJob(new ObdCommandJob(new AmbientAirTemperatureObdCommand())); Log.d(TAG, "Initialization jobs queued."); // Service is running.. _isRunning.set(true); // Set queue execution counter _queueCounter = 0L; } /** * Runs the queue until the service is stopped */ private void _executeQueue() { Log.d(TAG, "Executing queue.."); _isQueueRunning.set(true); while (!_queue.isEmpty()) { ObdCommandJob job = null; try { job = _queue.take(); // log job Log.d(TAG, "Taking job[" + job.getId() + "] from queue.."); if (job.getState().equals(ObdCommandJobState.NEW)) { Log.d(TAG, "Job state is NEW. Run it.."); job.setState(ObdCommandJobState.RUNNING); job.getCommand().run(_sock.getInputStream(), _sock.getOutputStream()); } else { // log not new job Log.e(TAG, "Job state was not new, so it shouldn't be in queue. BUG ALERT!"); } } catch (Exception e) { job.setState(ObdCommandJobState.EXECUTION_ERROR); Log.e(TAG, "Failed to run command. -> " + e.getMessage()); } if (job != null) { Log.d(TAG, "Job is finished."); job.setState(ObdCommandJobState.FINISHED); _callback.stateUpdate(job); } } _isQueueRunning.set(false); } /** * This method will add a job to the queue while setting its ID to the * internal queue counter. * * @param job * @return */ public Long queueJob(ObdCommandJob job) { _queueCounter++; Log.d(TAG, "Adding job[" + _queueCounter + "] to queue.."); job.setId(_queueCounter); try { _queue.put(job); } catch (InterruptedException e) { job.setState(ObdCommandJobState.QUEUE_ERROR); // log error Log.e(TAG, "Failed to queue job."); } Log.d(TAG, "Job queued successfully."); return _queueCounter; } /** * Stop OBD connection and queue processing. */ public void stopService() { Log.d(TAG, "Stopping service.."); clearNotification(); _queue.removeAll(_queue); // TODO is this safe? _isQueueRunning.set(false); _callback = null; _isRunning.set(false); // close socket try { _sock.close(); } catch (IOException e) { Log.e(TAG, e.getMessage()); } // kill service stopSelf(); } /** * Show a notification while this service is running. */ private void showNotification() { // Set the icon, scrolling text and timestamp Notification notification = new Notification(R.drawable.icon, getText(R.string.service_started), System.currentTimeMillis()); // Launch our activity if the user selects this notification PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); // Set the info for the views that show in the notification panel. notification.setLatestEventInfo(this, getText(R.string.notification_label), getText(R.string.service_started), contentIntent); // Send the notification. _notifManager.notify(R.string.service_started, notification); } /** * Clear notification. */ private void clearNotification() { _notifManager.cancel(R.string.service_started); } /** * TODO put description */ public class LocalBinder extends Binder implements IPostMonitor { public void setListener(IPostListener callback) { _callback = callback; } public boolean isRunning() { return _isRunning.get(); } public void executeQueue() { _executeQueue(); } public void addJobToQueue(ObdCommandJob job) { Log.d(TAG, "Adding job [" + job.getCommand().getName() + "] to queue."); _queue.add(job); if (!_isQueueRunning.get()) _executeQueue(); } } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.reader.io; import eu.lighthouselabs.obd.commands.ObdCommand; /** * This class represents a job that ObdGatewayService will have to execute and * maintain until the job is finished. It is, thereby, the application * representation of an ObdCommand instance plus a state that will be * interpreted and manipulated by ObdGatewayService. */ public class ObdCommandJob { private Long _id; private ObdCommand _command; private ObdCommandJobState _state; /** * Default ctor. * * @param id the ID of the job. * @param command the ObdCommand to encapsulate. */ public ObdCommandJob(ObdCommand command) { _command = command; _state = ObdCommandJobState.NEW; } public Long getId() { return _id; } public void setId(Long id) { _id = id; } public ObdCommand getCommand() { return _command; } /** * @return job current state. */ public ObdCommandJobState getState() { return _state; } /** * Sets a new job state. * * @param the new job state. */ public void setState(ObdCommandJobState state) { _state = state; } /** * The state of the command. */ public enum ObdCommandJobState { NEW, RUNNING, FINISHED, EXECUTION_ERROR, QUEUE_ERROR } }
Java
/* * TODO put header */ package eu.lighthouselabs.obd.reader.io; import android.content.ComponentName; import android.content.ServiceConnection; import android.os.IBinder; import android.util.Log; import eu.lighthouselabs.obd.reader.IPostListener; import eu.lighthouselabs.obd.reader.IPostMonitor; /** * Service connection for ObdGatewayService. */ public class ObdGatewayServiceConnection implements ServiceConnection { private static final String TAG = "ObdGatewayServiceConnection"; private IPostMonitor _service = null; private IPostListener _listener = null; public void onServiceConnected(ComponentName name, IBinder binder) { _service = (IPostMonitor) binder; _service.setListener(_listener); } public void onServiceDisconnected(ComponentName name) { _service = null; Log.d(TAG, "Service is disconnected."); } /** * @return true if service is running, false otherwise. */ public boolean isRunning() { if (_service == null) { return false; } return _service.isRunning(); } /** * Queue JobObdCommand. * * @param the * job */ public void addJobToQueue(ObdCommandJob job) { if (null != _service) _service.addJobToQueue(job); } /** * Sets a callback in the service. * * @param listener */ public void setServiceListener(IPostListener listener) { _listener = listener; } }
Java
package client; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import server.Command; public class Client { public static void main(String args[]){ try{ BufferedReader in = new BufferedReader( new InputStreamReader( new DataInputStream( new FileInputStream("sisend.txt")))); String strLine; String url="http://localhost:5500/SENDTASK?urls=["; while ((strLine = in.readLine()) != null) { url += "("+ strLine + ")"; } url +="]"; Command.openUrl(url); System.out.println(url); in.close(); }catch (Exception e){e.printStackTrace();} } }
Java
package server; import server.clients.ClientList; public class OnlinePeers extends Thread { private ClientList clientList; public OnlinePeers(ClientList clientList) { this.clientList = clientList; } public void run() { while (true) { } } }
Java
package server; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.InetAddress; import java.net.Socket; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; public class Command { public static List<String> openUrl(String urlStr){ List<String> result = new ArrayList<String>(); URL url; String inputLine; result.add(""); if (urlStr.equals("")) return result; result.clear(); try { url = new URL(urlStr); BufferedReader in = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream())); while ((inputLine = in.readLine()) != null) result.add(inputLine); in.close(); } catch (Exception e){} return result; } public static void sendGetRequest(String urlStr){ try { String params = URLEncoder.encode("param", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8"); params += "&" + URLEncoder.encode("param2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8"); String hostname = "vorgurak.servehttp.com"; int port = 80; InetAddress addr = InetAddress.getByName(hostname); Socket socket = new Socket(addr, port); String path = "/4/proov.php"; // Send headers BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")); wr.write("POST "+path+" HTTP/1.0\r\n"); wr.write("Content-Length: "+params.length()+"\r\n"); wr.write("Content-Type: application/x-www-form-urlencoded\r\n"); wr.write("\r\n"); // Send parameters wr.write(params); wr.flush(); } catch (Exception e) { e.printStackTrace(); } } }
Java
package server; public class newConnection extends Thread { private String confPort, port, aPort, aIp; public newConnection(String confPort, String port, String aPort, String aIp) throws Exception { this.confPort = confPort; this.port = port; this.aIp = aIp; this.aPort = aPort; } public void run() { // System.out.println(port + " " + confPort); if(!port.equals(confPort)) Command.openUrl("http://localhost:"+ confPort +"/ADDME?adr=:" + port); else if(!aIp.equals("0") && !aPort.equals("0")) Command.openUrl("http://"+ aIp+":"+ aPort +"/ADDME?adr=:" + port); } }
Java
package server; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Properties; public class Configuration { Properties configFile = new java.util.Properties(); String path; public Configuration(){ try { configFile.load(new FileInputStream("conf.txt")); }catch(Exception eta){} } public String getProperty(String key){ return configFile.getProperty(key); } public void setProperty(String key, String value){ configFile.setProperty(key, value); try { configFile.store(new FileOutputStream(path), null); } catch (Exception e) {} } }
Java
package server; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.InetAddress; import java.net.Socket; import java.net.URLEncoder; import java.net.UnknownHostException; public class SendHTTPPOSTRequestWithSocket { public static void main(String[] args) { try { String params = URLEncoder.encode("param", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8"); params += "&" + URLEncoder.encode("param2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8"); String hostname = "vorgurak.servehttp.com"; int port = 80; InetAddress addr = InetAddress.getByName(hostname); Socket socket = new Socket(addr, port); String path = "/4/proov.php"; // Send headers BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")); wr.write("POST "+path+" HTTP/1.0\r\n"); wr.write("Content-Length: "+params.length()+"\r\n"); wr.write("Content-Type: application/x-www-form-urlencoded\r\n"); wr.write("\r\n"); // Send parameters wr.write(params); wr.flush(); // Get response BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } wr.close(); rd.close(); System.out.println(params); } catch (Exception e) { e.printStackTrace(); } } }
Java
package server; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import server.clients.ClientList; public class HttpServer { private static int port; private static ClientList clientList = new ClientList(); public static void main(String args[]) { Configuration conf = new Configuration(); int cport = Integer.parseInt(conf.getProperty("PORT")); String aPort = conf.getProperty("APORT"); String aIp = conf.getProperty("AIP"); int[] ports = new int[100]; for (int i=0; i<100;ports[i]=cport+i++); ServerSocket server_socket; try { server_socket = create(ports); port = server_socket.getLocalPort(); // OnlinePeers oPeers = new OnlinePeers(clientList); // oPeers.start(); newConnection nc = new newConnection(conf.getProperty("PORT"), Integer.toString(port), aPort, aIp); nc.start(); System.out.println("httpServer running on port " + server_socket.getLocalPort()); while (true) { Socket socket = server_socket.accept(); httpRequestHandler request = new httpRequestHandler(socket); Thread thread = new Thread(request); thread.start(); } } catch (Exception e) { e.printStackTrace(); } } public static ServerSocket create(int[] ports) throws IOException { for (int port : ports) { try { return new ServerSocket(port); } catch (IOException ex) { continue; // try next port } } // if the program gets here, no port in the range was found throw new IOException("no free port found"); } public static int getPort() { return port; } public static ClientList getClientList() { return clientList; } }
Java
package server; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.Socket; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import server.clients.Client; import server.clients.ClientList; public class httpRequestHandler implements Runnable { final static String CRLF = "\r\n"; Socket socket; InputStream input; OutputStream output; BufferedReader br; public httpRequestHandler(Socket socket) throws Exception { this.socket = socket; this.input = socket.getInputStream(); this.output = socket.getOutputStream(); this.br = new BufferedReader(new InputStreamReader(socket.getInputStream())); } public void run() { try { processRequest(); } catch (Exception e) { e.printStackTrace(); } } private void processRequest() throws Exception { int i=0; while (true) { String headerLine = br.readLine(); // System.out.println(headerLine); if (headerLine.equals(CRLF) || headerLine.equals("")) break; StringTokenizer s = new StringTokenizer(headerLine); String temp = s.nextToken(); String header = "HTTP/1.0 200 OK\r\nServer: Masspäringud\r\nContent-type: text/html\r\n\r\n"; if (temp.equals("GET")) { String fileName = s.nextToken(), commandStr = "", content=""; if(fileName.indexOf("?")>-1){ commandStr = fileName.substring(1,fileName.indexOf("?")); System.out.println(socket.getInetAddress().getHostAddress() + " " + commandStr); if(commandStr.equals("URL")){ String url = fileName.substring(fileName.indexOf("url=")+4); System.out.println(url); List<String> res = Command.openUrl(url); for (String string : res){ content += string; } } else if(commandStr.equals("SENDTASK")){ String url = fileName.substring(fileName.indexOf("urls=")+5); System.out.println(url); String[] urls = url.split("\\)\\("); urls[0] = urls[0].substring(2); urls[urls.length-1] = urls[urls.length-1].substring(0, urls[urls.length-1].length()-2); int loend=0; String cmd=""; List<String> tasks = new ArrayList<String>(); for (String string : urls) { if(loend==0) cmd = "[("; cmd += string; loend++; if(loend <10) cmd +=")("; if(loend==10){ tasks.add(cmd); // Command.openUrl("http://localhost:5500/SENDURLS?urls=" + cmd+")]"); loend=0; } } if(loend != 10) tasks.add(cmd); } else if(commandStr.equals("SENDURLS")){ System.out.println(i++); String url = fileName.substring(fileName.indexOf("urls=")+5); System.out.println(url); String[] urls = url.split("\\)\\("); urls[0] = urls[0].substring(2); urls[urls.length-1] = urls[urls.length-1].substring(0, urls[urls.length-1].length()-2); for (String string : urls) { System.out.println(string); } } else if(commandStr.equals("ADDME")){ String address = fileName.substring(fileName.indexOf("adr=")+4); String ip = socket.getInetAddress().getHostAddress(); String port = address.substring(address.indexOf(':')+1); // System.out.println(address); // System.out.println(ip); // System.out.println(port); String result=""; List<Client> clientList = HttpServer.getClientList().addClient(ip, Integer.parseInt(port)); for (Client client : clientList) { String clientStr = client.getIp() + ":" + client.getPort(); if (!clientStr.equals(ip + ":" + port)){ if(!ip.equals("127.0.0.1") && client.getIp().equals("127.0.0.1")) result += socket.getLocalAddress().getHostAddress() + ":" + client.getPort() +";"; else result += clientStr+";"; Command.openUrl("http://" + clientStr + "/ADDCLIENT?adr=" + ip + ":" + port); System.out.println(clientStr + "/ADDCLIENT?adr=" + ip + ":" + port); } } result += socket.getLocalAddress().getHostAddress() + ":" + HttpServer.getPort() + ";"; if(!result.equals("")) { System.out.println(ip + ":" + port+"/ADDCLIENTS?adr=" +result.substring(0, result.length()-1)); Command.openUrl("http://" + ip + ":" + port+"/ADDCLIENTS?adr=" +result.substring(0, result.length()-1)); } } else if(commandStr.equals("ADDCLIENT")){ String address = fileName.substring(fileName.indexOf("adr=")+4); String ip = address.substring(0, address.indexOf(':')); String port = address.substring(address.indexOf(':')+1); System.out.println(address); // System.out.println(ip); // System.out.println(port); HttpServer.getClientList().addClient(ip, Integer.parseInt(port)); } else if(commandStr.equals("ADDCLIENTS")){ String address = fileName.substring(fileName.indexOf("adr=")+4); String[] addresses = address.split(";"); for (String adr : addresses) { String ip = adr.substring(0, adr.indexOf(':')); String port = adr.substring(adr.indexOf(':')+1); System.out.println(adr); // System.out.println(ip); // System.out.println(port); HttpServer.getClientList().addClient(ip, Integer.parseInt(port)); } } else if(commandStr.equals("PING")){ content = "PONG"; } } output.write(header.getBytes()); output.write(content.getBytes()); } } output.close(); br.close(); socket.close(); } }
Java
package server.clients; public class Client { private String ip; private int port; private String tasks; public Client(String ip, int port) { super(); this.ip = ip; this.port = port; } public String getTasks() { return tasks; } public void setTasks(String tasks) { this.tasks = tasks; } public String getIp() { return ip; } public int getPort() { return port; } }
Java
package server.clients; import java.util.ArrayList; import java.util.List; public class ClientList { List<Client> clientsList = new ArrayList<Client>(); public List<Client> addClient(String ip, int port){ clientsList.add(new Client(ip, port)); return clientsList; } public void removeClient(Client client){ clientsList.remove(client); } public List<Client> getClientsList() { return clientsList; } }
Java
/** Automatically generated file. DO NOT MODIFY */ package org.tpmkranz.notifyme; public final class BuildConfig { public final static boolean DEBUG = true; }
Java
/* Notify Me!, an app to enhance Android(TM)'s abilities to show notifications. Copyright (C) 2013 Tom Kranz This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Android is a trademark of Google Inc. */ package org.tpmkranz.notifyme; import android.accessibilityservice.AccessibilityService; import android.accessibilityservice.AccessibilityServiceInfo; import android.annotation.SuppressLint; import android.app.KeyguardManager; import android.app.Notification; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.PowerManager; import android.telephony.TelephonyManager; import android.view.LayoutInflater; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.widget.RemoteViews; import android.widget.TextView; public class NotificationService extends AccessibilityService { Prefs prefs; int filter; private BroadcastReceiver receiver = new BroadcastReceiver(){ @Override public void onReceive(Context arg0, Intent arg1) { if( ((TelephonyManager)arg0.getSystemService(Context.TELEPHONY_SERVICE)).getCallState() != 0 ){ arg0.unregisterReceiver(this); return; } startActivity(new Intent(arg0, NotificationActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) ); arg0.unregisterReceiver(this); } }; @Override public void onAccessibilityEvent(AccessibilityEvent event) { ((TemporaryStorage)getApplicationContext()).accessGranted(true); if( !event.getClassName().equals("android.app.Notification") ) return; if( filterMatch(event, true) ){ if( prefs.isAggressive(filter) ); else if( ((PowerManager)getSystemService(POWER_SERVICE)).isScreenOn() && !((KeyguardManager)getSystemService(KEYGUARD_SERVICE)).inKeyguardRestrictedInputMode() ) return; }else return; if( filterMatch(event, false) && ((TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE)).getCallState() == 0 ) triggerNotification(event); } @SuppressLint("NewApi") private boolean filterMatch(AccessibilityEvent event, boolean nameOnly) { boolean filterMatch = false; for( int i = 0; i < prefs.getNumberOfFilters() && !filterMatch; i++ ){ if( event.getPackageName().equals(prefs.getFilterApp(i)) ){ filter = i; if( prefs.hasFilterKeywords(i) && !nameOnly ){ String notificationContents = ( event.getText().size() == 0 ? "" : event.getText().get(0).toString() ); try{ Notification notification = (Notification) event.getParcelableData(); RemoteViews remoteViews = notification.contentView; LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); ViewGroup localViews = (ViewGroup) inflater.inflate(remoteViews.getLayoutId(), null); remoteViews.reapply(this, localViews); String piece = ""; for( int j = 16900000 ; j < 17000000 ; j++ ){ try{ piece = "\n"+( (TextView) localViews.findViewById(j) ).getText(); notificationContents.concat(piece); }catch(Exception e){ } } if(android.os.Build.VERSION.SDK_INT >= 16){ try{ remoteViews = notification.bigContentView; localViews = (ViewGroup) inflater.inflate(remoteViews.getLayoutId(), null); remoteViews.reapply(this, localViews); piece = ""; for( int j = 16900000 ; j < 17000000 ; j++ ){ try{ piece = "\n"+( (TextView) localViews.findViewById(j) ).getText(); notificationContents.concat(piece); }catch(Exception e){ } } }catch(Exception e){ } } }catch(Exception e){ } String[] keywords = prefs.getFilterKeywords(i); for( int j = 0 ; j < keywords.length && !filterMatch ; j++ ){ if( notificationContents.contains(keywords[j]) && !keywords.equals("") ){ filterMatch = true; } } }else{ filterMatch = true; } } } return filterMatch; } private void triggerNotification(AccessibilityEvent event) { try{ unregisterReceiver(receiver); }catch(Exception e){ } ((TemporaryStorage)getApplicationContext()).storeStuff(event.getParcelableData()); ((TemporaryStorage)getApplicationContext()).storeStuff(filter); if( ( prefs.isLightUpAllowed(filter) || ((PowerManager)getSystemService(POWER_SERVICE)).isScreenOn() ) ) startActivity(new Intent(this, NotificationActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) ); else{ IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); registerReceiver(receiver, filter); } } @Override protected void onServiceConnected(){ AccessibilityServiceInfo info = new AccessibilityServiceInfo(); info.eventTypes = AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED; info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC; info.flags = AccessibilityServiceInfo.DEFAULT; this.setServiceInfo(info); prefs = new Prefs(this); } @Override public void onInterrupt() { } @Override public void onDestroy(){ super.onDestroy(); ((TemporaryStorage)getApplicationContext()).accessGranted(false); } }
Java
/* Notify Me!, an app to enhance Android(TM)'s abilities to show notifications. Copyright (C) 2013 Tom Kranz This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Android is a trademark of Google Inc. */ package org.tpmkranz.notifyme; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; @SuppressLint("CommitPrefEdits") public class Prefs { private final SharedPreferences prefs; private final Editor edit; protected Prefs(Context context){ prefs = PreferenceManager.getDefaultSharedPreferences(context); edit = prefs.edit(); } protected int getPrevVersion(){ return prefs.getInt("PreviousVersion", 0); } protected void setPrevVersion(int newVersion){ edit.putInt("PreviousVersion", newVersion); edit.commit(); } protected boolean isBackgroundColorInverted(){ return prefs.getBoolean("BackgroundInverted", true); } protected void setBackgroundColorInverted(boolean inverted){ edit.putBoolean("BackgroundInverted", inverted); edit.commit(); } protected long getScreenTimeout(){ return prefs.getLong("ScreenTimeout", 0L); } protected void setScreenTimeout(long timeout){ edit.putLong("ScreenTimeout", timeout); edit.commit(); } protected boolean isInterfaceSlider(){ return prefs.getBoolean("InterfaceSlider", true); } protected void setInterfaceSlider(boolean slider){ edit.putBoolean("InterfaceSlider", slider); edit.commit(); } protected int getSliderBackgroundR(){ return prefs.getInt("SliderBackgroundR", ( android.os.Build.VERSION.SDK_INT > 10 ? 24 : 255 )); } protected int getSliderBackgroundG(){ return prefs.getInt("SliderBackgroundG", ( android.os.Build.VERSION.SDK_INT > 10 ? 24 : 255 )); } protected int getSliderBackgroundB(){ return prefs.getInt("SliderBackgroundB", ( android.os.Build.VERSION.SDK_INT > 10 ? 24 : 255 )); } protected void setSliderBackground(int r, int g, int b){ edit.putInt("SliderBackgroundR", r); edit.putInt("SliderBackgroundG", g); edit.putInt("SliderBackgroundB", b); edit.commit(); } protected int getNumberOfFilters(){ return prefs.getInt("numberOfFilters", 0); } protected String getFilterApp(int filter){ return prefs.getString("filter"+String.valueOf(filter)+"App", ""); } protected boolean hasFilterKeywords(int filter){ return ( prefs.getInt("filter"+String.valueOf(filter)+"numberOfKeywords", 0) > 0 ); } protected boolean isPopupAllowed(int filter){ return prefs.getBoolean("filter"+String.valueOf(filter)+"Popup", true); } protected boolean isAggressive(int filter){ return prefs.getBoolean("filter"+String.valueOf(filter)+"Aggressive", false); } protected boolean isExpansionAllowed(int filter){ return prefs.getBoolean("filter"+String.valueOf(filter)+"Expansion", true); } protected boolean expandByDefault(int filter){ return prefs.getBoolean("filter"+String.valueOf(filter)+"Expanded", false); } protected boolean isLightUpAllowed(int filter){ return prefs.getBoolean("filter"+String.valueOf(filter)+"Light", true); } protected String[] getFilterKeywords(int filter){ int numberOfKeywords = prefs.getInt("filter"+String.valueOf(filter)+"numberOfKeywords", 0); String[] keywords = new String[numberOfKeywords]; for(int i = 0 ; i < numberOfKeywords ; i++ ){ keywords[i] = prefs.getString("filter"+String.valueOf(filter)+"Keyword"+String.valueOf(i), ""); } return keywords; } protected void addFilter(String app, boolean popupAllowed, boolean aggressive, boolean expansionAllowed, boolean expanded, boolean lightUpAllowed){ int filter = getNumberOfFilters(); edit.putString("filter"+String.valueOf(filter)+"App", app); edit.putBoolean("filter"+String.valueOf(filter)+"Popup", popupAllowed); edit.putBoolean("filter"+String.valueOf(filter)+"Aggressive", aggressive); edit.putBoolean("filter"+String.valueOf(filter)+"Expansion", expansionAllowed); edit.putBoolean("filter"+String.valueOf(filter)+"Expanded", expanded); edit.putBoolean("filter"+String.valueOf(filter)+"Light", lightUpAllowed); edit.putInt( "numberOfFilters", filter + 1 ); edit.commit(); } protected void addFilter(String app, boolean popupAllowed, boolean aggressive, boolean expansionAllowed, boolean expanded, boolean lightUpAllowed, String[] keywords){ int filter = getNumberOfFilters(); edit.putString("filter"+String.valueOf(filter)+"App", app); edit.putBoolean("filter"+String.valueOf(filter)+"Popup", popupAllowed); edit.putBoolean("filter"+String.valueOf(filter)+"Aggressive", aggressive); edit.putBoolean("filter"+String.valueOf(filter)+"Expansion", expansionAllowed); edit.putBoolean("filter"+String.valueOf(filter)+"Expanded", expanded); edit.putBoolean("filter"+String.valueOf(filter)+"Light", lightUpAllowed); int pos = 0; for( int i = 0 ; i < keywords.length ; i++ ){ if( !isUseless(keywords, i) ){ edit.putString("filter"+String.valueOf(filter)+"Keyword"+String.valueOf(pos++), cleaned(keywords[i])); } } edit.putInt("filter"+String.valueOf(filter)+"numberOfKeywords", pos); edit.putInt( "numberOfFilters", filter + 1 ); edit.commit(); } protected void editFilter(int filter, String app, boolean popupAllowed, boolean aggressive, boolean expansionAllowed, boolean expanded, boolean lightUpAllowed){ for( int i = 0 ; i < prefs.getInt("filter"+String.valueOf(filter)+"numberOfKeywords", 0) ; i++ ){ edit.remove("filter"+String.valueOf(filter)+"Keyword"+String.valueOf(i)); } edit.remove("filter"+String.valueOf(filter)+"numberOfKeywords"); edit.putString("filter"+String.valueOf(filter)+"App", app); edit.putBoolean("filter"+String.valueOf(filter)+"Popup", popupAllowed); edit.putBoolean("filter"+String.valueOf(filter)+"Aggressive", aggressive); edit.putBoolean("filter"+String.valueOf(filter)+"Expansion", expansionAllowed); edit.putBoolean("filter"+String.valueOf(filter)+"Expanded", expanded); edit.putBoolean("filter"+String.valueOf(filter)+"Light", lightUpAllowed); edit.commit(); } protected void editFilter(int filter, String app, boolean popupAllowed, boolean aggressive, boolean expansionAllowed, boolean expanded, boolean lightUpAllowed, String[] keywords){ for( int i = 0 ; i < prefs.getInt("filter"+String.valueOf(filter)+"numberOfKeywords", 0) ; i++ ){ edit.remove("filter"+String.valueOf(filter)+"Keyword"+String.valueOf(i)); } edit.remove("filter"+String.valueOf(filter)+"numberOfKeywords"); edit.putString("filter"+String.valueOf(filter)+"App", app); edit.putBoolean("filter"+String.valueOf(filter)+"Popup", popupAllowed); edit.putBoolean("filter"+String.valueOf(filter)+"Aggressive", aggressive); edit.putBoolean("filter"+String.valueOf(filter)+"Expansion", expansionAllowed); edit.putBoolean("filter"+String.valueOf(filter)+"Expanded", expanded); edit.putBoolean("filter"+String.valueOf(filter)+"Light", lightUpAllowed); int pos = 0; for( int i = 0 ; i < keywords.length ; i++ ){ if( !isUseless(keywords, i) ){ edit.putString("filter"+String.valueOf(filter)+"Keyword"+String.valueOf(pos++), cleaned(keywords[i])); } } edit.putInt("filter"+String.valueOf(filter)+"numberOfKeywords", pos); edit.commit(); } private String cleaned(String keyword) { boolean startsWithCharacter = false; while( !startsWithCharacter ){ if( keyword.indexOf(" ") == 0 ) keyword = keyword.substring(1); else startsWithCharacter = true; } if( keyword.equals("") ) return ""; boolean endsWithCharacter = false; while( !endsWithCharacter ){ if( keyword.lastIndexOf(" ") == keyword.length()-1 ) keyword = keyword.substring(0, keyword.length()-1); else endsWithCharacter = true; } return keyword; } private boolean isUseless(String[] keywords, int position){ String keyword = cleaned(keywords[position]); if( keyword.equals("") ) return true; for( int i = 0 ; i < position ; i++ ){ if( cleaned(keywords[i]).equals(keyword) ) return true; } return false; } protected void removeFilter(int filter){ edit.remove("filter"+String.valueOf(filter)+"App"); edit.remove("filter"+String.valueOf(filter)+"Popup"); edit.remove("filter"+String.valueOf(filter)+"Aggressive"); edit.remove("filter"+String.valueOf(filter)+"Expansion"); edit.remove("filter"+String.valueOf(filter)+"Expanded"); edit.remove("filter"+String.valueOf(filter)+"Light"); for( int i = 0 ; i < prefs.getInt("filter"+String.valueOf(filter)+"numberOfKeywords", 0) ; i++ ){ edit.remove("filter"+String.valueOf(filter)+"Keyword"+String.valueOf(i)); } edit.remove("filter"+String.valueOf(filter)+"numberOfKeywords"); for( int i = filter + 1 ; i < getNumberOfFilters() ; i++ ){ edit.putString("filter"+String.valueOf(i-1)+"App", getFilterApp(i)); edit.remove("filter"+String.valueOf(i)+"App"); edit.putBoolean("filter"+String.valueOf(i-1)+"Popup", isPopupAllowed(i)); edit.remove("filter"+String.valueOf(i)+"Popup"); edit.putBoolean("filter"+String.valueOf(i-1)+"Aggressive", isAggressive(i)); edit.remove("filter"+String.valueOf(i)+"Aggressive"); edit.putBoolean("filter"+String.valueOf(i-1)+"Expansion", isExpansionAllowed(i)); edit.remove("filter"+String.valueOf(i)+"Expansion"); edit.putBoolean("filter"+String.valueOf(i-1)+"Expanded", expandByDefault(i)); edit.remove("filter"+String.valueOf(i)+"Expanded"); edit.putBoolean("filter"+String.valueOf(i-1)+"Light", isLightUpAllowed(i)); edit.remove("filter"+String.valueOf(i)+"Light"); for( int j = 0 ; j < prefs.getInt("filter"+String.valueOf(i)+"numberOfKeywords", 0) ; j++ ){ edit.putString("filter"+String.valueOf(i-1)+"Keyword"+String.valueOf(j), prefs.getString("filter"+String.valueOf(i)+"Keyword"+String.valueOf(j), "")); edit.remove("filter"+String.valueOf(i)+"Keyword"+String.valueOf(j)); } edit.putInt("filter"+String.valueOf(i-1)+"numberOfKeywords", prefs.getInt("filter"+String.valueOf(i)+"numberOfKeywords", 0)); edit.remove("filter"+String.valueOf(i)+"numberOfKeywords"); } edit.putInt( "numberOfFilters", getNumberOfFilters() - 1 ); edit.commit(); } }
Java
/* Notify Me!, an app to enhance Android(TM)'s abilities to show notifications. Copyright (C) 2013 Tom Kranz This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Android is a trademark of Google Inc. */ package org.tpmkranz.notifyme; import android.app.Application; import android.os.Parcelable; public class TemporaryStorage extends Application { private static Parcelable storedP; private static int filter; private static long timeout; private static boolean access; @Override public void onCreate(){ super.onCreate(); access = false; } public void storeStuff(Parcelable parc){ storedP = parc; } public void storeStuff(int filt){ filter = filt; } public void storeStuff(long time){ timeout = time; } public Parcelable getParcelable(){ return storedP; } public int getFilter(){ return filter; } public long getTimeout(){ return timeout; } public void accessGranted(boolean granted){ access = granted; } public boolean hasAccess(){ return access; } }
Java
/* Notify Me!, an app to enhance Android(TM)'s abilities to show notifications. Copyright (C) 2013 Tom Kranz This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Android is a trademark of Google Inc. */ package org.tpmkranz.notifyme; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class EditFilterActivity extends Activity { Prefs prefs; ImageView appChooserButton; TextView appNameView; ImageView appIconView; CheckBox keywordsCheckbox; EditText keywordsEditor; LinearLayout keywordsCaption; CheckBox popupCheckbox; LinearLayout popupCaption; CheckBox aggressiveCheckbox; LinearLayout aggressiveCaption; CheckBox expansionCheckbox; LinearLayout expansionCaption; CheckBox expandedCheckbox; LinearLayout expandedCaption; CheckBox lightUpCheckbox; LinearLayout lightUpCaption; int filter; String app; PackageManager packMan; boolean changed = false; long lastBackPress = 0L; Toast leaveToast; @SuppressLint("ShowToast") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_filter); prefs = new Prefs(this); appChooserButton = (ImageView) findViewById(R.id.editor_app_chooser_button); appNameView = (TextView) findViewById(R.id.editor_chosen_app_name); appIconView = (ImageView) findViewById(R.id.editor_chosen_app_icon); keywordsCheckbox = (CheckBox) findViewById(R.id.editor_keywords_checkbox); keywordsEditor = (EditText) findViewById(R.id.editor_keywords_edittext); keywordsCaption = (LinearLayout) findViewById(R.id.editor_keywords_caption); popupCheckbox = (CheckBox) findViewById(R.id.editor_popup_checkbox); popupCaption = (LinearLayout) findViewById(R.id.editor_popup_caption); aggressiveCheckbox = (CheckBox) findViewById(R.id.editor_aggressive_checkbox); aggressiveCaption = (LinearLayout) findViewById(R.id.editor_aggressive_caption); expansionCheckbox = (CheckBox) findViewById(R.id.editor_expansion_checkbox); expansionCaption = (LinearLayout) findViewById(R.id.editor_expansion_caption); expandedCheckbox = (CheckBox) findViewById(R.id.editor_expanded_checkbox); expandedCaption = (LinearLayout) findViewById(R.id.editor_expanded_caption); lightUpCheckbox = (CheckBox) findViewById(R.id.editor_lightup_checkbox); lightUpCaption = (LinearLayout) findViewById(R.id.editor_lightup_caption); if( getIntent().getAction().equals("edit") ){ filter = getIntent().getIntExtra("filter", 0); app = prefs.getFilterApp(filter); }else{ filter = prefs.getNumberOfFilters(); } packMan = this.getPackageManager(); leaveToast = Toast.makeText(this, R.string.editor_leave_toast, Toast.LENGTH_LONG); } @Override protected void onResume(){ super.onResume(); if( android.os.Build.VERSION.SDK_INT < 16 ){ findViewById(R.id.editor_expansion).setVisibility(View.GONE); findViewById(R.id.editor_expanded).setVisibility(View.GONE); } if( app != null ){ try { ApplicationInfo appInfo = packMan.getApplicationInfo(app, 0); appNameView.setText(packMan.getApplicationLabel(appInfo)); appIconView.setImageDrawable(packMan.getApplicationIcon(appInfo)); appChooserButton.setImageDrawable(getResources().getDrawable(android.R.drawable.ic_menu_edit)); keywordsCheckbox.setEnabled(true); keywordsCheckbox.setChecked(prefs.hasFilterKeywords(filter)); keywordsEditor.setText(""); if( keywordsCheckbox.isChecked() ){ String[] keywords = prefs.getFilterKeywords(filter); for( int i = 0 ; i < keywords.length - 1 ; i++ ) keywordsEditor.setText(keywordsEditor.getText()+keywords[i]+"\n"); keywordsEditor.setText(keywordsEditor.getText()+keywords[keywords.length-1]); keywordsEditor.setEnabled(true); keywordsEditor.setFocusableInTouchMode(true); }else{ keywordsEditor.setEnabled(false); keywordsEditor.setFocusable(false); } keywordsCaption.setEnabled(true); keywordsCaption.getChildAt(0).setEnabled(true); keywordsCaption.getChildAt(1).setEnabled(true); popupCheckbox.setEnabled(true); popupCheckbox.setChecked(prefs.isPopupAllowed(filter)); popupCaption.setEnabled(true); popupCaption.getChildAt(0).setEnabled(true); popupCaption.getChildAt(1).setEnabled(true); aggressiveCheckbox.setChecked(prefs.isAggressive(filter)); expansionCheckbox.setChecked(prefs.isExpansionAllowed(filter)); expandedCheckbox.setChecked(prefs.expandByDefault(filter)); lightUpCheckbox.setEnabled(true); lightUpCheckbox.setChecked(prefs.isLightUpAllowed(filter)); lightUpCaption.setEnabled(true); lightUpCaption.getChildAt(0).setEnabled(true); lightUpCaption.getChildAt(1).setEnabled(true); }catch(Exception e){ finish(); } }else{ keywordsCheckbox.setEnabled(false); keywordsCheckbox.setChecked(false); keywordsEditor.setEnabled(false); keywordsEditor.setFocusable(false); keywordsEditor.setText(""); keywordsCaption.setEnabled(false); keywordsCaption.getChildAt(0).setEnabled(false); keywordsCaption.getChildAt(1).setEnabled(false); popupCheckbox.setEnabled(false); popupCheckbox.setChecked(false); popupCaption.setEnabled(false); popupCaption.getChildAt(0).setEnabled(false); popupCaption.getChildAt(1).setEnabled(false); aggressiveCheckbox.setChecked(false); expansionCheckbox.setChecked(false); expandedCheckbox.setChecked(false); lightUpCheckbox.setEnabled(false); lightUpCheckbox.setChecked(false); lightUpCaption.setEnabled(false); lightUpCaption.getChildAt(0).setEnabled(false); lightUpCaption.getChildAt(1).setEnabled(false); appNameView.setText(R.string.editor_app_chooser_title); } aggressiveCheckbox.setEnabled(popupCheckbox.isChecked()); aggressiveCaption.setEnabled(popupCheckbox.isChecked()); aggressiveCaption.getChildAt(0).setEnabled(popupCheckbox.isChecked()); aggressiveCaption.getChildAt(1).setEnabled(popupCheckbox.isChecked()); expansionCheckbox.setEnabled(popupCheckbox.isChecked()); expansionCaption.setEnabled(popupCheckbox.isChecked()); expansionCaption.getChildAt(0).setEnabled(popupCheckbox.isChecked()); expansionCaption.getChildAt(1).setEnabled(popupCheckbox.isChecked()); expandedCheckbox.setEnabled(popupCheckbox.isChecked() && expansionCheckbox.isChecked()); expandedCaption.setEnabled(popupCheckbox.isChecked() && expansionCheckbox.isChecked()); expandedCaption.getChildAt(0).setEnabled(popupCheckbox.isChecked() && expansionCheckbox.isChecked()); expandedCaption.getChildAt(1).setEnabled(popupCheckbox.isChecked() && expansionCheckbox.isChecked()); } @Override public void onBackPressed(){ if( app == null || !changed || (System.currentTimeMillis()-lastBackPress < 3500L) ){ leaveToast.cancel(); AppPicker.appInfos = null; finish(); return; } leaveToast.show(); lastBackPress = System.currentTimeMillis(); } @SuppressLint("NewApi") public void checkTheKeywordsBox(View view){ if( view.equals(keywordsCaption) ) keywordsCheckbox.toggle(); keywordsEditor.setEnabled(keywordsCheckbox.isChecked()); keywordsEditor.setFocusable(keywordsCheckbox.isChecked()); keywordsEditor.setFocusableInTouchMode(keywordsCheckbox.isChecked()); changed = true; if( android.os.Build.VERSION.SDK_INT >= 11 ) invalidateOptionsMenu(); } @SuppressLint("NewApi") public void checkThePopupBox(View view){ if( view.equals(popupCaption) ) popupCheckbox.toggle(); aggressiveCheckbox.setEnabled(popupCheckbox.isChecked()); aggressiveCheckbox.setChecked(false); aggressiveCaption.setEnabled(popupCheckbox.isChecked()); aggressiveCaption.getChildAt(0).setEnabled(popupCheckbox.isChecked()); aggressiveCaption.getChildAt(1).setEnabled(popupCheckbox.isChecked()); expansionCheckbox.setEnabled(popupCheckbox.isChecked()); expansionCheckbox.setChecked(popupCheckbox.isChecked()); expansionCaption.setEnabled(popupCheckbox.isChecked()); expansionCaption.getChildAt(0).setEnabled(popupCheckbox.isChecked()); expansionCaption.getChildAt(1).setEnabled(popupCheckbox.isChecked()); expandedCheckbox.setEnabled(popupCheckbox.isChecked() && expansionCheckbox.isChecked()); expandedCheckbox.setChecked(false); expandedCaption.setEnabled(popupCheckbox.isChecked() && expansionCheckbox.isChecked()); expandedCaption.getChildAt(0).setEnabled(popupCheckbox.isChecked() && expansionCheckbox.isChecked()); expandedCaption.getChildAt(1).setEnabled(popupCheckbox.isChecked() && expansionCheckbox.isChecked()); changed = true; if( android.os.Build.VERSION.SDK_INT >= 11 ) invalidateOptionsMenu(); } @SuppressLint("NewApi") public void checkTheAggressiveBox(View view){ if( view.equals(aggressiveCaption) ) aggressiveCheckbox.toggle(); changed = true; if( android.os.Build.VERSION.SDK_INT >= 11 ) invalidateOptionsMenu(); } @SuppressLint("NewApi") public void checkTheExpansionBox(View view){ if( view.equals(expansionCaption) ) expansionCheckbox.toggle(); expandedCheckbox.setEnabled(popupCheckbox.isChecked() && expansionCheckbox.isChecked()); expandedCheckbox.setChecked(false); expandedCaption.setEnabled(popupCheckbox.isChecked() && expansionCheckbox.isChecked()); expandedCaption.getChildAt(0).setEnabled(popupCheckbox.isChecked() && expansionCheckbox.isChecked()); expandedCaption.getChildAt(1).setEnabled(popupCheckbox.isChecked() && expansionCheckbox.isChecked()); changed = true; if( android.os.Build.VERSION.SDK_INT >= 11 ) invalidateOptionsMenu(); } @SuppressLint("NewApi") public void checkTheExpandedBox(View view){ if( view.equals(expandedCaption) ) expandedCheckbox.toggle(); changed = true; if( android.os.Build.VERSION.SDK_INT >= 11 ) invalidateOptionsMenu(); } @SuppressLint("NewApi") public void checkTheLightUpBox(View view){ if( view.equals(lightUpCaption) ) lightUpCheckbox.toggle(); changed = true; if( android.os.Build.VERSION.SDK_INT >= 11 ) invalidateOptionsMenu(); } public void chooseApp(View view){ leaveToast.cancel(); startActivityForResult(new Intent(this, AppPicker.class).putExtra("filter", filter), 42); } @SuppressLint("NewApi") protected void onActivityResult(int reqCode, int resCode, Intent result){ if( resCode == Activity.RESULT_OK && reqCode == 42 ){ app = result.getAction(); changed = true; if( android.os.Build.VERSION.SDK_INT >= 11 ) invalidateOptionsMenu(); } } void apply(){ if( filter == prefs.getNumberOfFilters() ){ if( !popupCheckbox.isChecked() && !lightUpCheckbox.isChecked() ){ Toast.makeText(this, R.string.editor_nonsense_toast1, Toast.LENGTH_LONG).show(); return; } if( keywordsCheckbox.isChecked() && !keywordsEditor.getText().toString().equals("") ){ prefs.addFilter(app, popupCheckbox.isChecked(), aggressiveCheckbox.isChecked(), expansionCheckbox.isChecked(), expandedCheckbox.isChecked(), lightUpCheckbox.isChecked(), produceKeywords()); }else{ prefs.addFilter(app, popupCheckbox.isChecked(), aggressiveCheckbox.isChecked(), expansionCheckbox.isChecked(), expandedCheckbox.isChecked(), lightUpCheckbox.isChecked()); } }else{ if( !popupCheckbox.isChecked() && !lightUpCheckbox.isChecked() ){ Toast.makeText(this, R.string.editor_nonsense_toast2, Toast.LENGTH_LONG).show(); return; } if( keywordsCheckbox.isChecked() && !keywordsEditor.getText().toString().equals("") ){ prefs.editFilter(filter, app, popupCheckbox.isChecked(), aggressiveCheckbox.isChecked(), expansionCheckbox.isChecked(), expandedCheckbox.isChecked(), lightUpCheckbox.isChecked(), produceKeywords()); }else{ prefs.editFilter(filter, app, popupCheckbox.isChecked(), aggressiveCheckbox.isChecked(), expansionCheckbox.isChecked(), expandedCheckbox.isChecked(), lightUpCheckbox.isChecked()); } } finish(); } private String[] produceKeywords(){ String keywordString = keywordsEditor.getText().toString(); int numberOfBreaks = 0; for( int i = 0 ; i < keywordString.length() ; i++ ){ if( String.valueOf(keywordString.charAt(i)).equals("\n") ){ numberOfBreaks++; } } String[] keywords = new String[numberOfBreaks+1]; int prevBreak = 0; int j = 0; for( int i = 0 ; i < keywordString.length() ; i++ ){ if( String.valueOf(keywordString.charAt(i)).equals("\n") ){ keywords[j] = keywordString.substring(prevBreak, i); prevBreak = i + 1; j++; } } keywords[numberOfBreaks] = keywordString.substring(prevBreak); return keywords; } @Override public boolean onCreateOptionsMenu(Menu menu){ getMenuInflater().inflate(R.menu.edit_filter_menu, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu){ menu.findItem(R.id.editor_menu_apply).setTitle( (filter == prefs.getNumberOfFilters() ? R.string.editor_menu_apply0 : R.string.editor_menu_apply) ).setEnabled(changed); menu.findItem(R.id.editor_menu_discard).setTitle( (filter == prefs.getNumberOfFilters() ? R.string.editor_menu_discard0 : R.string.editor_menu_discard) ); menu.findItem(R.id.editor_menu_remove).setVisible(prefs.getFilterApp(filter).equals(app)); leaveToast.cancel(); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item){ leaveToast.cancel(); switch( item.getItemId() ){ case R.id.editor_menu_apply: AppPicker.appInfos = null; apply(); return true; case R.id.editor_menu_discard: AppPicker.appInfos = null; finish(); return true; case R.id.editor_menu_remove: prefs.removeFilter(filter); AppPicker.appInfos = null; finish(); return true; default: return super.onOptionsItemSelected(item); } } }
Java
package org.tpmkranz.notifyme; /* Notify Me!, an app to enhance Android(TM)'s abilities to show notifications. Copyright (C) 2013 Tom Kranz This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Android is a trademark of Google Inc. */ import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.KeyguardManager; import android.app.Notification; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.os.PowerManager; import android.provider.Settings; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager.LayoutParams; import android.widget.RemoteViews; public class NotificationActivity extends Activity { Prefs prefs; int filter; boolean big, showPopup, touchValid, triggers, screenWasOff; Notification notif; RemoteViews remViews; View nView; ViewGroup pView; SliderSurfaceView sView; float X, lastX; DrawTask dTask; GestureDetector geDet; AlertDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { screenWasOff = !((PowerManager)getSystemService(POWER_SERVICE)).isScreenOn(); if( !((KeyguardManager)getSystemService(KEYGUARD_SERVICE)).inKeyguardRestrictedInputMode() ) setTheme(R.style.Transparent); getWindow().setFlags(LayoutParams.FLAG_TURN_SCREEN_ON, LayoutParams.FLAG_TURN_SCREEN_ON); getWindow().setFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED, LayoutParams.FLAG_SHOW_WHEN_LOCKED); prefs = new Prefs(this); filter = ((TemporaryStorage)getApplicationContext()).getFilter(); dTask = new DrawTask(); super.onCreate(savedInstanceState); } @SuppressLint("NewApi") @Override protected void onResume(){ super.onResume(); notif = (Notification) ((TemporaryStorage)getApplicationContext()).getParcelable(); if( !prefs.isPopupAllowed(filter) ){ new WaitForLightTask().execute(); return; } if( prefs.expandByDefault(filter) && android.os.Build.VERSION.SDK_INT >= 16 ){ try{ notif.bigContentView.hashCode(); big = true; }catch(Exception e){ } } try{ if( ((TemporaryStorage)getApplicationContext()).getTimeout() == 0L && prefs.getScreenTimeout() != 0L && screenWasOff ){ ((TemporaryStorage)getApplicationContext()).storeStuff(Settings.System.getLong(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT)); Settings.System.putLong(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, prefs.getScreenTimeout()); } }catch(Exception e){ } if( !preparePopup() ) return; if( prefs.isInterfaceSlider() ) showPopupSlider(); else showPopupButton(); } @SuppressLint("NewApi") private boolean preparePopup(){ try{ if( big ) remViews = notif.bigContentView; else remViews = notif.contentView; }catch(Exception e){ return false; } dialog = new AlertDialog.Builder(this).setView(pView).setInverseBackgroundForced(prefs.isBackgroundColorInverted()).create(); dialog.setCanceledOnTouchOutside(false); dialog.setOnCancelListener( new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } } ); return true; } @SuppressWarnings("deprecation") private void showPopupSlider(){ pView = (ViewGroup) ((LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.slider_popup, null); nView = remViews.apply(this, pView); pView.addView(nView, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); sView = (SliderSurfaceView) pView.getChildAt(1); geDet = new GestureDetector( new UnlockListener() ); sView.setOnTouchListener( new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if( event.getAction() == MotionEvent.ACTION_UP ){ touchValid = false; } return geDet.onTouchEvent(event); } } ); sView.setOnClickListener(null); sView.setZOrderOnTop(true); dialog.setView(pView); dTask.cancel(true); dTask = new DrawTask(); dTask.execute(); dialog.show(); } @SuppressLint("NewApi") private void showPopupButton(){ nView = remViews.apply(this, null); dialog.setView(nView); dialog.setButton(Dialog.BUTTON_POSITIVE, this.getText(R.string.notification_view_button), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); startActivity(new Intent(getApplicationContext(), Unlock.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } } ); dialog.setButton(Dialog.BUTTON_NEGATIVE, this.getText(R.string.notification_dismiss_button), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } } ); if( android.os.Build.VERSION.SDK_INT >= 16 && prefs.isExpansionAllowed(filter) ){ try{ notif.bigContentView.hashCode(); dialog.setButton(Dialog.BUTTON_NEUTRAL, getText( big ? R.string.notification_collapse_button : R.string.notification_expand_button ), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); big = !big; if( preparePopup() ) showPopupButton(); } } ); }catch(Exception e){ } } dialog.show(); } @Override protected void onPause(){ super.onPause(); if( !prefs.isPopupAllowed(filter) ) return; if( prefs.getScreenTimeout() != 0L && screenWasOff ) Settings.System.putLong(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, ((TemporaryStorage)getApplicationContext()).getTimeout()); ((TemporaryStorage)getApplicationContext()).storeStuff(0L); dialog.dismiss(); dTask.cancel(true); } @Override protected void onNewIntent(Intent intent){ if( !getIntent().equals(intent) ){ finish(); startActivity(intent); }else super.onNewIntent(intent); } private class WaitForLightTask extends AsyncTask<Void, Void, Void>{ @Override protected Void doInBackground(Void... params){ while( !((PowerManager)getSystemService(POWER_SERVICE)).isScreenOn() ); return null; } @Override protected void onPostExecute(Void result){ finish(); } } private class DrawTask extends AsyncTask<Void, Void, Void>{ @Override protected Void doInBackground(Void... params) { while( sView.getWidth() == 0 ){ } sView.setDimensions((float) sView.getWidth(),(float) sView.getHeight()); Resources res = getResources(); sView.setBitmaps(BitmapFactory.decodeResource(res, R.drawable.ic_lock_lock), BitmapFactory.decodeResource(res, R.drawable.ic_lock_handle), BitmapFactory.decodeResource(res, R.drawable.ic_lock_view), BitmapFactory.decodeResource(res, R.drawable.ic_lock_view0), BitmapFactory.decodeResource(res, R.drawable.ic_lock_dismiss), BitmapFactory.decodeResource(res, R.drawable.ic_lock_dismiss0)); X = sView.centerX; lastX = X / 2; while( !this.isCancelled() ){ while( sView.onDisplay ){ if( lastX != X ){ sView.doDraw(X, touchValid); if( !touchValid ){ lastX = X; X = sView.centerX; } } } } return null; } } private class UnlockListener extends SimpleOnGestureListener{ float[] a = new float[2]; float[] b = new float[2]; @Override public boolean onDown(MotionEvent ev){ a[0] = ev.getX(); a[1] = ev.getY(); b[0] = sView.centerX; b[1] = sView.centerY; if( sView.dist(a, b) < sView.offsetY ){ touchValid = true; triggers = true; } return touchValid; } @Override public boolean onScroll(MotionEvent ev1, MotionEvent ev2, float dX, float dY){ if( Math.abs(ev2.getY() - sView.centerY)/(Math.abs(ev2.getX() - sView.centerX) + sView.offsetX) >= 1 ){ touchValid = false; triggers = false; } if( touchValid ){ lastX = X; X = ev2.getX(); return true; }else return false; } @Override public void onLongPress(MotionEvent ev){ } @SuppressLint("NewApi") @Override public boolean onFling(MotionEvent ev1, MotionEvent ev2, float vX, float vY){ if( sView.dist(a, b) < sView.offsetY ){ if( ev2.getX() <= sView.leftX && triggers ) dialog.cancel(); else if( ev2.getX() >= sView.rightX && triggers ){ dialog.cancel(); startActivity(new Intent(getApplicationContext(), Unlock.class)); }else if( android.os.Build.VERSION.SDK_INT >= 16 && !triggers && Math.abs(vY) > 4 * getResources().getDisplayMetrics().densityDpi && prefs.isExpansionAllowed(filter) ){ try{ notif.bigContentView.hashCode(); if( vY > 0 && big || vY < 0 && !big ) return true; dialog.dismiss(); big = !big; if( preparePopup() ) showPopupSlider(); else finish(); }catch(Exception e){ } } return true; }else{ return false; } } } }
Java
package org.tpmkranz.notifyme; /* Notify Me!, an app to enhance Android(TM)'s abilities to show notifications. Copyright (C) 2013 Tom Kranz This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Android is a trademark of Google Inc. */ import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; public class SliderSurfaceView extends SurfaceView implements SurfaceHolder.Callback{ protected boolean onDisplay; protected SurfaceHolder sHolder; private Bitmap lock, handle, dismiss, dismiss0, view, view0; private Canvas canvas; protected float centerY, centerX, leftX, rightX, drawX, offsetX, offsetY; private int color; Prefs prefs; public SliderSurfaceView(Context context, AttributeSet attrs) { super(context, attrs); prefs = new Prefs(context); onDisplay = false; color = Color.rgb(prefs.getSliderBackgroundR(), prefs.getSliderBackgroundG(), prefs.getSliderBackgroundB()); sHolder = this.getHolder(); sHolder.addCallback(this); } @Override public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) { } @Override public void surfaceCreated(SurfaceHolder arg0) { onDisplay = true; } @Override public void surfaceDestroyed(SurfaceHolder arg0) { onDisplay = false; } protected void setDimensions(float width, float height){ centerX = width / 2; centerY = height / 2; leftX = centerX - 3*width/8; rightX = centerX + 3*width/8; } protected void setBitmaps(Bitmap l, Bitmap h, Bitmap v, Bitmap v0, Bitmap d, Bitmap d0){ lock = l; handle = h; view = v; view0 = v0; dismiss = d; dismiss0 = d0; offsetX = l.getWidth() / 2; offsetY = l.getHeight() / 2; } protected double dist(float[] a, float[] b){ return Math.sqrt( Math.pow(a[0] - b[0], 2) + Math.pow(a[1] - b[1], 2) ); } protected void doDraw(float x, boolean touch){ canvas = sHolder.lockCanvas(); if( canvas == null ) return; if( x < centerX ){ drawX = ( x < leftX ? leftX : x ); }else{ drawX = ( x > rightX ? rightX : x ); } canvas.drawColor(color); if( drawX == leftX ) canvas.drawBitmap(dismiss0, leftX - offsetX, centerY - offsetY, null); else canvas.drawBitmap(dismiss, leftX - offsetX, centerY - offsetY, null); if( drawX == rightX ) canvas.drawBitmap(view0, rightX - offsetX, centerY - offsetY, null); else canvas.drawBitmap(view, rightX - offsetX, centerY - offsetY, null); if( !touch ) canvas.drawBitmap(lock, drawX - offsetX, centerY - offsetY, null); else if( drawX != leftX && drawX != rightX ) canvas.drawBitmap(handle, drawX - offsetX, centerY - offsetY, null); sHolder.unlockCanvasAndPost(canvas); } }
Java
/* Notify Me!, an app to enhance Android(TM)'s abilities to show notifications. Copyright (C) 2013 Tom Kranz This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Android is a trademark of Google Inc. */ package org.tpmkranz.notifyme; import java.util.Arrays; import java.util.List; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class AppPicker extends Activity{ PackageManager packMan; static List<ApplicationInfo> appInfos; static Drawable[] icons; static String[] appNames, appPackages; ProgressDialog plsWait; GetAppList stuff; boolean ready; int filter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_app_picker); filter = getIntent().getIntExtra("filter", -1); plsWait = new ProgressDialog(this); plsWait.setCancelable(false); stuff = new GetAppList(); } @Override protected void onStart(){ super.onStart(); if( appInfos != null ){ if( appNames[appInfos.size()-1] != null ){ ready = true; return; } } stuff.execute(); } @Override protected void onResume(){ super.onResume(); if( !ready ) return; ArrayAdapter<String> adapter = new AppPickerAdapter(this, appNames); ListView appPickerList = (ListView) findViewById(R.id.app_picker_list); appPickerList.setAdapter(adapter); appPickerList.setOnItemClickListener( new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id){ String app = appPackages[position]; Prefs prefs = new Prefs(view.getContext()); for( int i = 0 ; i < prefs.getNumberOfFilters() ; i++){ if( app.equals(prefs.getFilterApp(i)) && i != filter ){ finish(); Toast.makeText(view.getContext(), R.string.app_picker_duplicate, Toast.LENGTH_SHORT).show(); return; } } setResult(Activity.RESULT_OK, new Intent().setAction(app)); finish(); } } ); plsWait.dismiss(); } @Override protected void onStop(){ super.onStop(); stuff.cancel(true); } private class AppPickerAdapter extends ArrayAdapter<String>{ private final Context context; private final String[] appNames; public AppPickerAdapter(Context arg0, String[] arg1){ super(arg0, R.layout.list_item, arg1); this.context = arg0; this.appNames = arg1; } @Override public View getView(int position, View convertView, ViewGroup parent){ View itemView = ( (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) ).inflate(R.layout.list_item, parent, false); TextView textView = (TextView) itemView.findViewById(R.id.filter_item_name); textView.setText(appNames[position]); ImageView imageView = (ImageView) itemView.findViewById(R.id.filter_item_image); imageView.setImageDrawable(icons[position]); return itemView; } } private class GetAppList extends AsyncTask<Void, Integer, Void>{ String[] packageBuffer; Drawable[] iconBuffer; @Override protected void onPreExecute(){ packMan = getPackageManager(); appInfos = packMan.getInstalledApplications(0); publishProgress(0); } @Override protected Void doInBackground(Void... arg0) { appNames = new String[appInfos.size()]; appPackages = new String[appInfos.size()]; packageBuffer = new String[appInfos.size()]; icons = new Drawable[appInfos.size()]; iconBuffer = new Drawable[appInfos.size()]; for( int i = 0 ; i < appInfos.size() && !isCancelled(); i++){ appNames[i] = packMan.getApplicationLabel(appInfos.get(i)).toString()+" "+String.valueOf(i); packageBuffer[i] = appInfos.get(i).packageName; iconBuffer[i] = packMan.getApplicationIcon(appInfos.get(i)); publishProgress(i+1); } Arrays.sort(appNames); int j; for( int i = 0 ; i < appInfos.size() ; i++ ){ j = Integer.parseInt(appNames[i].substring(appNames[i].lastIndexOf(" ")+1)); appPackages[i] = packageBuffer[j]; icons[i] = iconBuffer[j]; appNames[i] = appNames[i].substring(0, appNames[i].lastIndexOf(" ")); publishProgress(i+1); } if( isCancelled() ) return null; publishProgress(-1); return null; } @Override protected void onProgressUpdate(Integer... progress){ if( progress[0] == 0 ){ plsWait.setMax(appInfos.size()); plsWait.setMessage(getText(R.string.app_picker_retrieve)); plsWait.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); plsWait.show(); }else if( progress[0] == -1 ){ ready = true; onResume(); } else{ plsWait.setProgress(progress[0]); } } } }
Java
/* Notify Me!, an app to enhance Android(TM)'s abilities to show notifications. Copyright (C) 2013 Tom Kranz This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Android is a trademark of Google Inc. */ package org.tpmkranz.notifyme; import android.app.Activity; import android.app.KeyguardManager; import android.app.Notification; import android.os.AsyncTask; import android.os.Bundle; import android.os.PowerManager; import android.view.WindowManager.LayoutParams; public class Unlock extends Activity { Notification notif; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD); notif = ((Notification) ((TemporaryStorage)getApplicationContext()).getParcelable()); new WaitForUnlock().execute(); } private class WaitForUnlock extends AsyncTask<Void,Void,Boolean>{ @Override protected Boolean doInBackground(Void... params) { while( ((KeyguardManager)getSystemService(KEYGUARD_SERVICE)).inKeyguardRestrictedInputMode() ){ try{ wait(100); }catch(Exception e){ } if( !((PowerManager)getSystemService(POWER_SERVICE)).isScreenOn() ) return false; } return true; } @Override protected void onPostExecute(Boolean result){ finish(); if( result.booleanValue() ){ try{ notif.contentIntent.send(); }catch(Exception e){ } } } } }
Java
/* Notify Me!, an app to enhance Android(TM)'s abilities to show notifications. Copyright (C) 2013 Tom Kranz This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Android is a trademark of Google Inc. */ package org.tpmkranz.notifyme; import android.app.Activity; import android.app.AlertDialog; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.text.Editable; import android.text.TextWatcher; import android.text.method.LinkMovementMethod; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; public class MainActivity extends Activity { Prefs prefs; CheckAccessibilityTask stuff; int version = 0; boolean access; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try{ if(getIntent().getAction().equals("redraw")){ finish(); return; } }catch(Exception e){ } setContentView(R.layout.activity_main); try{ version = getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode; }catch(Exception e){ } prefs = new Prefs(this); /* if( prefs.getPrevVersion() == 0 ){ prefs.setAccessibilityServiceRunning(false); prefs.setPrevVersion(version); }else if( prefs.getPrevVersion() < version ){ prefs.setAccessibilityServiceRunning(false); prefs.setPrevVersion(version); }else if( prefs.getPrevVersion() > version ){ prefs.setAccessibilityServiceRunning(false); prefs.setPrevVersion(version); }*/ access = ((TemporaryStorage)getApplicationContext()).hasAccess(); } @Override protected void onResume(){ super.onResume(); if( !access ){ ProgressDialog pDialog = new ProgressDialog(this); pDialog.setMessage(getResources().getString(R.string.main_check_checking)); pDialog.setMax(3000); pDialog.setCancelable(false); pDialog.show(); stuff = new CheckAccessibilityTask(); stuff.execute(pDialog); return; } ListView mainFilterList = (ListView) this.findViewById(R.id.main_filter_list); String[] filterApps = new String[prefs.getNumberOfFilters()+1]; for( int i = 0 ; i < filterApps.length ; i++ ){ if( i == prefs.getNumberOfFilters() ){ filterApps[i] = "JOKER"; }else{ filterApps[i] = prefs.getFilterApp(i); } } ArrayAdapter<String> adapter = new MainFilterAdapter(this, filterApps); mainFilterList.setAdapter(adapter); mainFilterList.setOnItemClickListener( new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id){ Intent editFilterIntent = new Intent(parent.getContext(), EditFilterActivity.class); if( position == prefs.getNumberOfFilters() ){ editFilterIntent.setAction("new"); }else{ editFilterIntent.setAction("edit"); editFilterIntent.putExtra("filter", position); } startActivity(editFilterIntent); } } ); mainFilterList.setOnItemLongClickListener( new OnItemLongClickListener(){ @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id){ final int filter = position; if( filter == prefs.getNumberOfFilters() ) return true; final View finalView = view; AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext()); try{ builder.setTitle(getResources().getString(R.string.main_remove_title1)+" "+ ((TextView)((RelativeLayout)view).getChildAt(1)).getText() +" "+getResources().getString(R.string.main_remove_title2)); builder.setIcon(((ImageView)((RelativeLayout)view).getChildAt(0)).getDrawable()); }catch(Exception e){ } builder.setPositiveButton(R.string.main_remove_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { prefs.removeFilter(filter); startActivity(new Intent(finalView.getContext(), MainActivity.class).setAction("redraw")); } } ); builder.setNegativeButton(R.string.main_remove_cancel, null); builder.show(); return true; } } ); } public class MainFilterAdapter extends ArrayAdapter<String> { private final Context context; private final String[] values; private final PackageManager packMan; public MainFilterAdapter(Context arg0, String[] arg1){ super(arg0, R.layout.list_item, arg1); this.context = arg0; this.values = arg1; this.packMan = context.getPackageManager(); } @Override public View getView(int position, View convertView, ViewGroup parent){ View itemView = ( (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) ).inflate(R.layout.list_item, parent, false); TextView textView = (TextView) itemView.findViewById(R.id.filter_item_name); ImageView imageView = (ImageView) itemView.findViewById(R.id.filter_item_image); if( values[position].equals("JOKER") ){ textView.setText(R.string.main_add_to_list); imageView.setImageDrawable(context.getResources().getDrawable(android.R.drawable.ic_menu_add)); return itemView; } ApplicationInfo appInfo; try { appInfo = packMan.getApplicationInfo( values[position], 0 ); textView.setText(packMan.getApplicationLabel(appInfo)); imageView.setImageDrawable(packMan.getApplicationIcon(appInfo)); } catch (NameNotFoundException e) { } return itemView; } } private class CheckAccessibilityTask extends AsyncTask<ProgressDialog, Long, Boolean>{ ProgressDialog pDialog; Notification notif; @Override protected Boolean doInBackground(ProgressDialog... args) { pDialog = args[0]; notif = new NotificationCompat.Builder(getApplicationContext()).setTicker("Actioni contrariam semper et aequalem esse reactionem.") .setSmallIcon(R.drawable.ic_launcher).setContentIntent(PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT)).build(); this.publishProgress(-1L); long t = System.currentTimeMillis() ; while( System.currentTimeMillis() - t < 3500L ){ if( ((TemporaryStorage)getApplicationContext()).hasAccess() ){ return true; }else{ publishProgress(System.currentTimeMillis()-t); } } return false; } @Override protected void onProgressUpdate(Long... progress){ if(progress[0].longValue() == -1L) ((NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE)).notify(21, notif); else pDialog.setProgress( progress[0].intValue() ); } @Override protected void onPostExecute(Boolean result){ pDialog.dismiss(); AlertDialog aDialog; access = result.booleanValue(); ((NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE)).cancel(21); if( access ) aDialog = new AlertDialog.Builder(pDialog.getContext()).setMessage(R.string.main_check_good_message).setPositiveButton(R.string.main_check_good_button, null).create(); else aDialog = new AlertDialog.Builder(pDialog.getContext()).setMessage(getResources().getString(R.string.main_check_bad_message) +(version == prefs.getPrevVersion() ? getResources().getString(R.string.main_check_bad_message0) : "")) .setPositiveButton(R.string.main_check_bad_button, null).setCancelable(false).create(); aDialog.setOnDismissListener( new DialogInterface.OnDismissListener(){ @Override public void onDismiss(DialogInterface dialog) { if( access ){ finish(); prefs.setPrevVersion(version); startActivity(getIntent()); }else{ startActivity(new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS)); } } } ); aDialog.show(); if( access && prefs.getPrevVersion() == version ){ aDialog.dismiss(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){ switch(item.getItemId()){ case R.id.main_menu_checkaccessibility: prefs.setPrevVersion(0); ((TemporaryStorage)getApplicationContext()).accessGranted(false); finish(); startActivity(getIntent()); return true; case R.id.main_menu_popup: final View view = ((LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.main_menu_popup, null); if( android.os.Build.VERSION.SDK_INT >= 11 ) view.findViewById(R.id.main_menu_popup_background).setVisibility(View.GONE); ((CheckBox)view.findViewById(R.id.main_menu_popup_background_checkbox)).setChecked(prefs.isBackgroundColorInverted()); view.findViewById(R.id.main_menu_popup_background_caption).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { ((CheckBox)view.findViewById(R.id.main_menu_popup_background_checkbox)).toggle(); } } ); ((SeekBar)view.findViewById(R.id.main_menu_popup_color_slider_r)).setMax(255); ((SeekBar)view.findViewById(R.id.main_menu_popup_color_slider_r)).setOnSeekBarChangeListener( new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if( fromUser ){ ((EditText)view.findViewById(R.id.main_menu_popup_color_edit_r)).setText(( progress == 0 ? "" : String.valueOf(progress) )); } ((ImageView)view.findViewById(R.id.main_menu_popup_color_preview)).setImageDrawable(new ColorDrawable(Color.rgb(progress, ((SeekBar)view.findViewById(R.id.main_menu_popup_color_slider_g)).getProgress(), ((SeekBar)view.findViewById(R.id.main_menu_popup_color_slider_b)).getProgress()))); } } ); ((EditText)view.findViewById(R.id.main_menu_popup_color_edit_r)).addTextChangedListener( new TextWatcher(){ @Override public void afterTextChanged(Editable s) { try{ if( Integer.parseInt(s.toString()) > 255 ){ s.replace(0, s.length(), "255"); return; }else if( Integer.parseInt(s.toString()) < 0 ){ s.replace(0, s.length(), "0"); return; } ((SeekBar)view.findViewById(R.id.main_menu_popup_color_slider_r)).setProgress(Integer.parseInt(s.toString())); }catch(Exception e){ ((SeekBar)view.findViewById(R.id.main_menu_popup_color_slider_r)).setProgress(0); s.clear(); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } } ); ((SeekBar)view.findViewById(R.id.main_menu_popup_color_slider_g)).setMax(255); ((SeekBar)view.findViewById(R.id.main_menu_popup_color_slider_g)).setOnSeekBarChangeListener( new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if( fromUser ){ ((EditText)view.findViewById(R.id.main_menu_popup_color_edit_g)).setText(( progress == 0 ? "" : String.valueOf(progress) )); } ((ImageView)view.findViewById(R.id.main_menu_popup_color_preview)).setImageDrawable(new ColorDrawable(Color.rgb(((SeekBar)view.findViewById(R.id.main_menu_popup_color_slider_r)).getProgress(), progress, ((SeekBar)view.findViewById(R.id.main_menu_popup_color_slider_b)).getProgress()))); } } ); ((EditText)view.findViewById(R.id.main_menu_popup_color_edit_g)).addTextChangedListener( new TextWatcher(){ @Override public void afterTextChanged(Editable s) { try{ if( Integer.parseInt(s.toString()) > 255 ){ s.replace(0, s.length(), "255"); return; }else if( Integer.parseInt(s.toString()) < 0 ){ s.replace(0, s.length(), "0"); return; } ((SeekBar)view.findViewById(R.id.main_menu_popup_color_slider_g)).setProgress(Integer.parseInt(s.toString())); }catch(Exception e){ ((SeekBar)view.findViewById(R.id.main_menu_popup_color_slider_g)).setProgress(0); s.clear(); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } } ); ((SeekBar)view.findViewById(R.id.main_menu_popup_color_slider_b)).setMax(255); ((SeekBar)view.findViewById(R.id.main_menu_popup_color_slider_b)).setOnSeekBarChangeListener( new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if( fromUser ){ ((EditText)view.findViewById(R.id.main_menu_popup_color_edit_b)).setText(( progress == 0 ? "" : String.valueOf(progress) )); } ((ImageView)view.findViewById(R.id.main_menu_popup_color_preview)).setImageDrawable(new ColorDrawable(Color.rgb(((SeekBar)view.findViewById(R.id.main_menu_popup_color_slider_r)).getProgress(), ((SeekBar)view.findViewById(R.id.main_menu_popup_color_slider_g)).getProgress(), progress))); } } ); ((EditText)view.findViewById(R.id.main_menu_popup_color_edit_b)).addTextChangedListener( new TextWatcher(){ @Override public void afterTextChanged(Editable s) { try{ if( Integer.parseInt(s.toString()) > 255 ){ s.replace(0, s.length(), "255"); return; }else if( Integer.parseInt(s.toString()) < 0 ){ s.replace(0, s.length(), "0"); return; } ((SeekBar)view.findViewById(R.id.main_menu_popup_color_slider_b)).setProgress(Integer.parseInt(s.toString())); }catch(Exception e){ ((SeekBar)view.findViewById(R.id.main_menu_popup_color_slider_b)).setProgress(0); s.clear(); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } } ); ((ImageView)view.findViewById(R.id.main_menu_popup_color_preview)).setImageDrawable(new ColorDrawable(Color.rgb(prefs.getSliderBackgroundR(), prefs.getSliderBackgroundG(), prefs.getSliderBackgroundB()))); ((EditText)view.findViewById(R.id.main_menu_popup_color_edit_r)).setText(String.valueOf(prefs.getSliderBackgroundR())); ((EditText)view.findViewById(R.id.main_menu_popup_color_edit_g)).setText(String.valueOf(prefs.getSliderBackgroundG())); ((EditText)view.findViewById(R.id.main_menu_popup_color_edit_b)).setText(String.valueOf(prefs.getSliderBackgroundB())); ((EditText)view.findViewById(R.id.main_menu_popup_timeout_editor)).setText(( prefs.getScreenTimeout() == 0L ? "" : String.valueOf(prefs.getScreenTimeout()/1000L) )); ((EditText)view.findViewById(R.id.main_menu_popup_timeout_editor)).addTextChangedListener( new TextWatcher(){ @Override public void afterTextChanged(Editable s) { if( s.toString().equals("") ) return; try{ if( Long.parseLong(s.toString()) > 9999L ) s.replace(0, s.length(), "9999"); else if( Long.parseLong(s.toString()) < 0L ) s.replace(0, s.length(), "0"); }catch(Exception e){ s.clear(); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } } ); ((CheckBox)view.findViewById(R.id.main_menu_popup_interface_checkbox)).setChecked(prefs.isInterfaceSlider()); ((CheckBox)view.findViewById(R.id.main_menu_popup_interface_checkbox)).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { ((ViewGroup)view.findViewById(R.id.main_menu_popup_color)).getChildAt(0).setEnabled(((CheckBox)v).isChecked()); for( int i = 0 ; i < 3 ; i++){ ((ViewGroup)((ViewGroup)((ViewGroup)view.findViewById(R.id.main_menu_popup_color)).getChildAt(1)).getChildAt(i)).getChildAt(0).setEnabled(((CheckBox)v).isChecked()); ((ViewGroup)((ViewGroup)((ViewGroup)view.findViewById(R.id.main_menu_popup_color)).getChildAt(1)).getChildAt(i)).getChildAt(1).setEnabled(((CheckBox)v).isChecked()); } ((ViewGroup)view.findViewById(R.id.main_menu_popup_color)).getChildAt(2).setVisibility(( ((CheckBox)v).isChecked() ? View.VISIBLE : View.INVISIBLE )); } } ); ((ViewGroup)view.findViewById(R.id.main_menu_popup_color)).getChildAt(0).setEnabled(((CheckBox)view.findViewById(R.id.main_menu_popup_interface_checkbox)).isChecked()); for( int i = 0 ; i < 3 ; i++){ ((ViewGroup)((ViewGroup)((ViewGroup)view.findViewById(R.id.main_menu_popup_color)).getChildAt(1)).getChildAt(i)).getChildAt(0).setEnabled(((CheckBox)view.findViewById(R.id.main_menu_popup_interface_checkbox)).isChecked()); ((ViewGroup)((ViewGroup)((ViewGroup)view.findViewById(R.id.main_menu_popup_color)).getChildAt(1)).getChildAt(i)).getChildAt(1).setEnabled(((CheckBox)view.findViewById(R.id.main_menu_popup_interface_checkbox)).isChecked()); } ((ViewGroup)view.findViewById(R.id.main_menu_popup_color)).getChildAt(2).setVisibility(( ((CheckBox)view.findViewById(R.id.main_menu_popup_interface_checkbox)).isChecked() ? View.VISIBLE : View.INVISIBLE )); view.findViewById(R.id.main_menu_popup_interface_caption).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { ((CheckBox)view.findViewById(R.id.main_menu_popup_interface_checkbox)).toggle(); ((ViewGroup)view.findViewById(R.id.main_menu_popup_color)).getChildAt(0).setEnabled(((CheckBox)view.findViewById(R.id.main_menu_popup_interface_checkbox)).isChecked()); for( int i = 0 ; i < 3 ; i++){ ((ViewGroup)((ViewGroup)((ViewGroup)view.findViewById(R.id.main_menu_popup_color)).getChildAt(1)).getChildAt(i)).getChildAt(0).setEnabled(((CheckBox)view.findViewById(R.id.main_menu_popup_interface_checkbox)).isChecked()); ((ViewGroup)((ViewGroup)((ViewGroup)view.findViewById(R.id.main_menu_popup_color)).getChildAt(1)).getChildAt(i)).getChildAt(1).setEnabled(((CheckBox)view.findViewById(R.id.main_menu_popup_interface_checkbox)).isChecked()); } ((ViewGroup)view.findViewById(R.id.main_menu_popup_color)).getChildAt(2).setVisibility(( ((CheckBox)view.findViewById(R.id.main_menu_popup_interface_checkbox)).isChecked() ? View.VISIBLE : View.INVISIBLE )); } } ); new AlertDialog.Builder(this).setView(view).setPositiveButton("Save", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { prefs.setBackgroundColorInverted(((CheckBox)view.findViewById(R.id.main_menu_popup_background_checkbox)).isChecked()); prefs.setInterfaceSlider(((CheckBox)view.findViewById(R.id.main_menu_popup_interface_checkbox)).isChecked()); prefs.setSliderBackground(((SeekBar)view.findViewById(R.id.main_menu_popup_color_slider_r)).getProgress(), ((SeekBar)view.findViewById(R.id.main_menu_popup_color_slider_g)).getProgress(), ((SeekBar)view.findViewById(R.id.main_menu_popup_color_slider_b)).getProgress()); prefs.setScreenTimeout(( ((EditText)view.findViewById(R.id.main_menu_popup_timeout_editor)).getText().toString().equals("") ? 0L : Long.parseLong(((EditText)view.findViewById(R.id.main_menu_popup_timeout_editor)).getText().toString())*1000L )); } } ).setNegativeButton("Cancel", null).show(); return true; case R.id.main_menu_help: new AlertDialog.Builder(this).setMessage(R.string.main_menu_help_message).setTitle(R.string.main_menu_help_title) .setPositiveButton(R.string.main_menu_help_ok_button, null).setNegativeButton(R.string.main_menu_help_question_button, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://forum.xda-developers.com/showthread.php?t=2173226")).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } } ).show(); return true; case R.id.main_menu_about: ViewGroup about = (ViewGroup) ((LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.main_menu_about, null); ((TextView)about.getChildAt(0)).setMovementMethod(LinkMovementMethod.getInstance()); new AlertDialog.Builder(this).setView(about).setTitle(R.string.main_menu_about_title) .setPositiveButton(R.string.main_menu_about_ok_button, null).show(); return true; default: return super.onOptionsItemSelected(item); } } }
Java
/** * A customizable timer that allows you to keep track of in-game time. * To use in an actor, simply declare a new Timer. * * Example usage: * * public class Player extends Actor * { * private Timer timer=new Timer(); * ... * * public Player * { * ... * } * * act() * { * timer.tick(); * ... * } * * ... * * } * * Since it runs along Greenfoot, your time based ineractions won't be broken when Greenfoot is * paused nor stopped. * * @author Jesus Trejo * @version 2.1, 17/May/14 */ public class Timer { private boolean isWaiting; private boolean isCounting; private float time; public Timer() { isWaiting=false; isCounting=false; time=0; } /** * Increases the timer by a set amount (needs to be adjusted manually * depending on your game speed). It MUST to be called in every actor's act cycle a single * time (and only one) in order to work properly. */ public void tick() { time+=0.016; } /** * Returns the actual time. */ public int getTime() { return((int)(time*1000)); } /** * Resets the time to 0, so it can start a new count. */ public void mark() { time=0; } /** * Checks if the timer is waiting. * Receives as parameter the time it should wait in milliseconds, it'll automatically * mark and check if the time elapsed is minor than the time it should wait. * * Returns true if it's waiting (time elapsed < time it should wait) and false * if the time elapsed is bigger or equal. * * Examples: if(timer.wait(1000)) * return; * * if(!timer.wait(50)) * turn(10); * * In the first example, the timer will return true for ~1 second, after that, it'll return false. * If it was called in an Actor's act(), it'll return true for 1 second, after * that, it'll return false for a fraction of second, then true once again since it'll be * automatically reset. * * In the second example, the actor will turn 10 degrees aproximately every 50 milliseconds. */ public boolean wait(int t) { if(isWaiting==false) { isWaiting=true; mark(); } if(getTime() < t) return(true); else { isWaiting=false; return(false); } } /** * Resets the timer. */ public void reset() { isWaiting=false; isCounting=false; time=0; } /** * Starts a count. It can be called multiple times without being reset. Use the method reset() * to start a new count (must to be reset manually unlike wait()). */ public void count() { if(isCounting==false) { time=0; isCounting=true; } } /** * Changes the current time to a given value */ public void setTime(int num) { time=num; } }
Java