List of usage examples for android.content Context getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
From source file:com.adwhirl.AdWhirlLayout.java
protected String getAdWhirlKey(Context context) { final String packageName = context.getPackageName(); final String activityName = context.getClass().getName(); final PackageManager pm = context.getPackageManager(); Bundle bundle = null;/*from w ww. j a v a2 s . c om*/ // Attempts to retrieve Activity-specific AdWhirl key first. If not // found, retrieve Application-wide AdWhirl key. try { ActivityInfo activityInfo = pm.getActivityInfo(new ComponentName(packageName, activityName), PackageManager.GET_META_DATA); bundle = activityInfo.metaData; if (bundle != null) { return bundle.getString(AdWhirlLayout.ADWHIRL_KEY); } } catch (NameNotFoundException exception) { // Activity cannot be found. Shouldn't be here. return null; } try { ApplicationInfo appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA); bundle = appInfo.metaData; if (bundle != null) { return bundle.getString(AdWhirlLayout.ADWHIRL_KEY); } } catch (NameNotFoundException exception) { // Application cannot be found. Shouldn't be here. return null; } return null; }
From source file:com.nttec.everychan.ui.theme.CustomThemeHelper.java
private static void processWindow(Context context, SparseIntArray attrs, int textColorPrimaryOriginal, int textColorPrimaryOverridden) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) return;/*from w w w.j a v a2 s . c om*/ boolean isLollipop = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP; int materialPrimaryIndex = attrs.indexOfKey(R.attr.materialPrimary); int materialPrimaryDarkIndex = attrs.indexOfKey(R.attr.materialPrimaryDark); int materialNavigationBarIndex = attrs.indexOfKey(R.attr.materialNavigationBar); boolean overrideActionbarColor = materialPrimaryIndex >= 0; boolean overridePanelsColor = Math.max(materialPrimaryDarkIndex, materialNavigationBarIndex) >= 0; boolean overrideTextColor = textColorPrimaryOriginal != textColorPrimaryOverridden; if (!overrideTextColor && !overrideActionbarColor && !overridePanelsColor) return; Window window = ((Activity) context).getWindow(); final View decorView = window.getDecorView(); Resources resources = context.getResources(); if (overrideActionbarColor) { try { Drawable background = new ColorDrawable(attrs.valueAt(materialPrimaryIndex)); Object actionBar = context.getClass().getMethod("getActionBar").invoke(context); actionBar.getClass().getMethod("setBackgroundDrawable", Drawable.class).invoke(actionBar, background); } catch (Exception e) { Logger.e(TAG, e); } } if (overrideTextColor) { int id = resources.getIdentifier("action_bar_title", "id", "android"); if (id != 0) { View v = decorView.findViewById(id); if (v instanceof TextView) ((TextView) v).setTextColor(textColorPrimaryOverridden); } } if (isLollipop && overrideTextColor) { try { int id = resources.getIdentifier("action_bar", "id", "android"); if (id == 0) throw new Exception("'android:id/action_bar' identifier not found"); View v = decorView.findViewById(id); if (v == null) throw new Exception("view with id 'android:id/action_bar' not found"); Class<?> toolbarClass = Class.forName("android.widget.Toolbar"); if (!toolbarClass.isInstance(v)) throw new Exception("view 'android:id/action_bar' is not instance of android.widget.Toolbar"); toolbarClass.getMethod("setTitleTextColor", int.class).invoke(v, textColorPrimaryOverridden); setLollipopMenuOverflowIconColor((ViewGroup) v, textColorPrimaryOverridden); } catch (Exception e) { Logger.e(TAG, e); } } if (isLollipop && overridePanelsColor) { try { if (materialPrimaryDarkIndex >= 0) { window.getClass().getMethod("setStatusBarColor", int.class).invoke(window, attrs.valueAt(materialPrimaryDarkIndex)); } if (materialNavigationBarIndex >= 0) { window.getClass().getMethod("setNavigationBarColor", int.class).invoke(window, attrs.valueAt(materialNavigationBarIndex)); } } catch (Exception e) { Logger.e(TAG, e); } } }
From source file:org.opendatakit.common.android.logic.PropertiesSingleton.java
void setCurrentContext(Context context) { try {//www . j a v a 2s. co m mBaseContext = context; // if we are re-using the existing one, pick up any changes by other apps // including, e.g., the reset of the configuration by ODK Services. if (isModified()) { init(); } } catch (Exception e) { // TODO: remove the mocking logic? it looks like garbage... if (isMocked) { mBaseContext = context; } else { boolean faked = false; Context app = context.getApplicationContext(); Class<?> classObj = app.getClass(); String appName = classObj.getSimpleName(); while (!appName.equals("CommonApplication")) { classObj = classObj.getSuperclass(); if (classObj == null) break; appName = classObj.getSimpleName(); } if (classObj != null) { try { Class<?>[] argClassList = new Class[] {}; Method m = classObj.getDeclaredMethod("isMocked", argClassList); Object[] argList = new Object[] {}; Object o = m.invoke(null, argList); if (((Boolean) o).booleanValue()) { mBaseContext = context; isMocked = true; faked = true; } } catch (Exception e1) { } } if (!faked) { e.printStackTrace(); throw new IllegalStateException("ODK Services must be installed!"); } } init(); } }
From source file:org.solovyev.android.calculator.AndroidCalculatorDisplayView.java
public synchronized void init(@Nonnull Context context, boolean fromApp) { if (!initialized) { if (fromApp) { final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); final CalculatorPreferences.Gui.Layout layout = CalculatorPreferences.Gui.getLayout(preferences); if (!layout.isOptimized()) { setTextSize(TypedValue.COMPLEX_UNIT_SP, getResources().getDimension(R.dimen.cpp_display_text_size_mobile)); }/* ww w. ja v a 2s . c om*/ if (context instanceof FragmentActivity) { this.setOnClickListener(new CalculatorDisplayOnClickListener((FragmentActivity) context)); } else { throw new IllegalArgumentException("Must be fragment activity, got " + context.getClass()); } } this.initialized = true; } }
From source file:com.smartnsoft.droid4me.app.ActivityController.java
/** * Dispatches the exception to the {@link ActivityController.ExceptionHandler}, and invokes the right method depending on its nature. * /*from www . j av a2 s .com*/ * <p> * The framework is responsible for invoking that method every time an unhandled exception is thrown. If no * {@link ActivityController#registerExceptionHandler(ExceptionHandler) exception handler is registered}, the exception will be only logged, and the * method will return {@code false}. * </p> * * <p> * Note that this method is {@code synchronized}, which prevents it from being invoking while it is already being executed, and which involves that * only one {@link Throwable} may be handled at the same time. * </p> * * @param isRecoverable * indicates whether the application is about to crash when the exception has been triggered * @param context * the context that originated the exception ; may be {@code null} * @param component * when not {@code null}, this will be the {@link android.app.Fragment} the exception has been thrown from * @param throwable * the reported exception * @return {@code true} if the exception has been handled ; in particular, if no {@link ActivityController#getExceptionHandler() exception handled * has been set}, returns {@code false} */ public synchronized boolean handleException(boolean isRecoverable, Context context, Object component, Throwable throwable) { if (exceptionHandler == null) { if (log.isWarnEnabled()) { log.warn( "Detected an exception which will not be handled during the processing of the context with name '" + (context == null ? "null" : context.getClass().getName()) + "'", throwable); } return false; } final Activity activity; if (context instanceof Activity) { activity = (Activity) context; } else { activity = null; } try { if (activity != null && throwable instanceof BusinessObjectUnavailableException) { // Should only occur with a non-null activity final BusinessObjectUnavailableException exception = (BusinessObjectUnavailableException) throwable; if (log.isWarnEnabled()) { log.warn( "Caught an exception during the retrieval of the business objects from the activity from class with name '" + activity.getClass().getName() + "'", exception); } // We do nothing if the activity is dying if (activity != null && activity.isFinishing() == true) { return true; } return exceptionHandler.onBusinessObjectAvailableException(activity, component, exception); } else { if (log.isWarnEnabled()) { log.warn( "Caught an exception during the processing of " + (context == null ? "a null Context" : "the Context from class with name '" + context.getClass().getName()) + "'", throwable); } // For this special case, we ignore the case when the activity is dying if (activity != null) { return exceptionHandler.onActivityException(activity, component, throwable); } else if (context != null) { return exceptionHandler.onContextException(isRecoverable, context, throwable); } else { return exceptionHandler.onException(isRecoverable, throwable); } } } catch (Throwable otherThrowable) { // Just to make sure that handled exceptions do not trigger un-handled exceptions on their turn ;( if (log.isErrorEnabled()) { log.error( "An error occurred while attempting to handle an exception coming from " + (context == null ? "a null Context" : "the Context from class with name '" + context.getClass().getName()) + "'", otherThrowable); } return false; } }
From source file:air.com.snagfilms.cast.chromecast.VideoChromeCastManager.java
/** * Returns the initialized instances of this class. If it is not initialized * yet, a {@link CastException} will be thrown. The {@link Context} that is * passed as the argument will be used to update the context for the * <code>VideoChromeCastManager</code> instance. The main purpose of * updating context is to enable the library to provide {@link Context} * related functionalities, e.g. it can create an error dialog if needed. * This method is preferred over the similar one without a context argument. * /*from ww w . j a va 2 s. com*/ * @param context * the current Context * @return * @throws CastException * @see {@link initialize()}, {@link setContext()} */ public static VideoChromeCastManager getInstance(Context context) throws CastException { if (null == sInstance) { Log.e(TAG, "No VideoChromeCastManager instance was built, you need to build one first " + "(called from Context: " + context + ")"); throw new CastException(); } Log.d(TAG, "Updated context to: " + context.getClass().getName()); sInstance.mContext = context; return sInstance; }
From source file:com.licenta.android.licenseapp.alarm.AlarmReceiver.java
public static void setAlarm(Context context) { AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, AlarmReceiver.class); PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); /*//from w ww .j a v a 2s. c om * If you don't have precise time requirements, use an inexact repeating alarm * the minimize the drain on the device battery. * * The call below specifies the alarm type, the trigger time, the interval at * which the alarm is fired, and the alarm's associated PendingIntent. * It uses the alarm type RTC_WAKEUP ("Real Time Clock" wake up), which wakes up * the device and triggers the alarm according to the time of the device's clock. * * Alternatively, you can use the alarm type ELAPSED_REALTIME_WAKEUP to trigger * an alarm based on how much time has elapsed since the device was booted. This * is the preferred choice if your alarm is based on elapsed time--for example, if * you simply want your alarm to fire every 60 minutes. You only need to use * RTC_WAKEUP if you want your alarm to fire at a particular date/time. Remember * that clock-based time may not translate well to other locales, and that your * app's behavior could be affected by the user changing the device's time setting. * */ // Wake up the device to fire the alarm in 30 minutes, and every 30 minutes // after that. long intervalMillis; String intervalVal = prefs.getString("repeat_interval", "0"); switch (intervalVal) { case "15": intervalMillis = AlarmManager.INTERVAL_FIFTEEN_MINUTES; break; case "30": intervalMillis = AlarmManager.INTERVAL_HALF_HOUR; break; case "60": intervalMillis = AlarmManager.INTERVAL_HOUR; break; default: intervalMillis = 0; break; } // for testing intervalMillis = 6000; alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + intervalMillis, intervalMillis, alarmIntent); prefs.edit().putBoolean(Constants.PREF_KEY_IS_ALARM_ON, true).apply(); Log.d(context.getClass().getName(), "Alarm started"); }
From source file:com.taobao.weex.WXSDKInstance.java
public void init(Context context) { mContext = context;/*from w w w.j a v a2 s.c o m*/ mContainerInfo = new HashMap<>(4); mNativeInvokeHelper = new NativeInvokeHelper(mInstanceId); mWXPerformance = new WXPerformance(mInstanceId); mApmForInstance = new WXInstanceApm(mInstanceId); mExceptionRecorder = new WXInstanceExceptionRecord(mInstanceId); mWXPerformance.WXSDKVersion = WXEnvironment.WXSDK_VERSION; mWXPerformance.JSLibInitTime = WXEnvironment.sJSLibInitTime; mUserTrackAdapter = WXSDKManager.getInstance().getIWXUserTrackAdapter(); WXSDKManager.getInstance().getAllInstanceMap().put(mInstanceId, this); mContainerInfo.put(WXInstanceApm.KEY_PAGE_PROPERTIES_CONTAINER_NAME, context instanceof Activity ? context.getClass().getSimpleName() : "unKnowContainer"); mContainerInfo.put(WXInstanceApm.KEY_PAGE_PROPERTIES_INSTANCE_TYPE, "page"); }
From source file:org.cowboycoders.cyclisimo.turbo.TurboService.java
public synchronized void start(final long trackId, final Context context) { if (running) { return;// w w w.j a va 2 s . c om } running = true; preferences = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); preferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); syncScaleFactor(); this.selectedTurboTrainer = preferences.getString(context.getString(R.string.turbotrainer_selected), context.getString(R.string.turbotrainer_tacx_bushido_headunit_value)); Log.d(TAG, selectedTurboTrainer); // accessing database so should be put into a task double userWeight; double bikeWeight; Bike selectedBike; CyclismoProviderUtils providerUtils = MyTracksProviderUtils.Factory.getCyclimso(context); User currentUser = providerUtils .getUser(PreferencesUtils.getLong(context, R.string.settings_select_user_current_selection_key)); if (currentUser != null) { userWeight = currentUser.getWeight(); selectedBike = providerUtils.getBike( PreferencesUtils.getLong(context, R.string.settings_select_bike_current_selection_key)); } else { Log.w(TAG, "using default user weight"); userWeight = DEFAULT_USER_WEIGHT; //kg selectedBike = null; } if (selectedBike != null) { bikeWeight = selectedBike.getWeight(); } else { Log.w(TAG, "using default bike weight"); bikeWeight = DEFAULT_BIKE_WEIGHT; //kg } setParameterBuilder(new Parameters.Builder(userWeight, bikeWeight)); Log.d(TAG, "user weight: " + userWeight); Log.d(TAG, "bike weight: " + bikeWeight); attachAntLogger = PreferencesUtils.getBoolean(context, R.string.settings_ant_diagnostic_logging_state_key, false); wakeLock.acquire(); recordingTrackId = PreferencesUtils.getLong(this, R.string.recording_track_id_key); List<LatLongAlt> latLongAlts = null; context.getClass(); CourseLoader cl = new CourseLoader(context, trackId); try { latLongAlts = cl.getLatLongAlts(); } catch (InterruptedException e) { String error = "interrupted whilst loading course"; Log.e(TAG, error); handleException(e, "Error loading course", true, NOTIFCATION_ID_STARTUP); } latLongAlts = org.cowboycoders.location.LocationUtils.interpolatePoints(latLongAlts, TARGET_TRACKPOINT_DISTANCE_METRES); this.courseTracker = new CourseTracker(latLongAlts); Log.d(TAG, "latlong length: " + latLongAlts.size()); enableMockLocations(); // start in background as otherwise it is destroyed in onDestory() before we // can disconnect startServiceInBackround(); doBindService(); registerRecordingReceiver(); Intent notificationIntent = new Intent(this, TurboService.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); Notification noti = new NotificationCompat.Builder(this) .setContentTitle(getString(R.string.turbo_mode_service_running_notification_title)) .setContentText(getString(R.string.turbo_mode_service_running_notification_text)) .setSmallIcon(R.drawable.track_bike).setContentIntent(pendingIntent).setOngoing(true).build(); // build api 16 only ;/ startForeground(ONGOING_NOTIFICATION, noti); // currentLatLongIndex = latLongAlts.size() -3; puts in near end so we can // test ending }
From source file:org.cowboycoders.cyclismo.turbo.TurboService.java
public synchronized void start(final long trackId, final Context context) { if (running) { return;//from w w w . jav a2s . c o m } running = true; preferences = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); preferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); syncScaleFactor(); this.selectedTurboTrainer = preferences.getString( this.getApplication().getString(R.string.turbotrainer_selected), this.getApplication().getString(R.string.turbotrainer_tacx_bushido_headunit_value)); // accessing database so should be put into a task double userWeight; double bikeWeight; Bike selectedBike; CyclismoProviderUtils providerUtils = MyTracksProviderUtils.Factory.getCyclimso(context); User currentUser = providerUtils .getUser(PreferencesUtils.getLong(context, R.string.settings_select_user_current_selection_key)); if (currentUser != null) { userWeight = currentUser.getWeight(); selectedBike = providerUtils.getBike( PreferencesUtils.getLong(context, R.string.settings_select_bike_current_selection_key)); } else { Log.w(TAG, "using default user weight"); userWeight = DEFAULT_USER_WEIGHT; //kg selectedBike = null; } if (selectedBike != null) { bikeWeight = selectedBike.getWeight(); } else { Log.w(TAG, "using default bike weight"); bikeWeight = DEFAULT_BIKE_WEIGHT; //kg } setParameterBuilder(new Parameters.Builder(userWeight, bikeWeight)); Log.d(TAG, "user weight: " + userWeight); Log.d(TAG, "bike weight: " + bikeWeight); attachAntLogger = PreferencesUtils.getBoolean(context, R.string.settings_ant_diagnostic_logging_state_key, false); wakeLock.acquire(); recordingTrackId = PreferencesUtils.getLong(this, R.string.recording_track_id_key); List<LatLongAlt> latLongAlts = null; context.getClass(); CourseLoader cl = new CourseLoader(context, trackId); try { latLongAlts = cl.getLatLongAlts(); } catch (InterruptedException e) { Log.e(TAG, "interrupted whilst loading course"); handleException(e, "Error loading course", true, NOTIFCATION_ID_STARTUP); } this.courseTracker = new CourseTracker(latLongAlts, TARGET_TRACKPOINT_DISTANCE_METRES); Log.d(TAG, "latlong length: " + latLongAlts.size()); // start in background as otherwise it is destroyed in onDestory() before we // can disconnect startServiceInBackround(); doBindService(); registerRecordingReceiver(); showStartNotification(); // currentLatLongIndex = latLongAlts.size() -3; puts in near end so we can // test ending }