Example usage for android.app Activity getClass

List of usage examples for android.app Activity getClass

Introduction

In this page you can find the example usage for android.app Activity getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:szjy.advtech.BuildInfo.java

/**
 * init/*w  ww .  j a  va 2 s  .c om*/
 * @param buildConfigClassName null or specified BuildConfig class name
 * @param callbackContext
 */
private void init(String buildConfigClassName, CallbackContext callbackContext) {
    // Cached check
    if (null != mBuildInfoCache) {
        callbackContext.success(mBuildInfoCache);
        return;
    }

    // Load PackageInfo
    Activity activity = cordova.getActivity();
    String packageName = activity.getPackageName();
    String basePackageName = packageName;
    CharSequence displayName = "";

    PackageManager pm = activity.getPackageManager();

    try {
        PackageInfo pi = pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);

        if (null != pi.applicationInfo) {
            displayName = pi.applicationInfo.loadLabel(pm);
        }
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

    // Load BuildConfig class
    Class c = null;

    if (null == buildConfigClassName) {
        buildConfigClassName = packageName + ".BuildConfig";
    }

    try {
        c = Class.forName(buildConfigClassName);
    } catch (ClassNotFoundException e) {
    }

    if (null == c) {
        basePackageName = activity.getClass().getPackage().getName();
        buildConfigClassName = basePackageName + ".BuildConfig";

        try {
            c = Class.forName(buildConfigClassName);
        } catch (ClassNotFoundException e) {
            callbackContext.error("BuildConfig ClassNotFoundException: " + e.getMessage());
            return;
        }
    }

    // Create result
    mBuildInfoCache = new JSONObject();
    try {
        boolean debug = getClassFieldBoolean(c, "DEBUG", false);

        mBuildInfoCache.put("packageName", packageName);
        mBuildInfoCache.put("basePackageName", basePackageName);
        mBuildInfoCache.put("displayName", displayName);
        mBuildInfoCache.put("name", displayName); // same as displayName
        mBuildInfoCache.put("version", getClassFieldString(c, "VERSION_NAME", ""));
        mBuildInfoCache.put("versionCode", getClassFieldInt(c, "VERSION_CODE", 0));
        mBuildInfoCache.put("debug", debug);
        mBuildInfoCache.put("buildType", getClassFieldString(c, "BUILD_TYPE", ""));
        mBuildInfoCache.put("flavor", getClassFieldString(c, "FLAVOR", ""));

        if (debug) {
            Log.d(TAG, "packageName    : \"" + mBuildInfoCache.getString("packageName") + "\"");
            Log.d(TAG, "basePackageName: \"" + mBuildInfoCache.getString("basePackageName") + "\"");
            Log.d(TAG, "displayName    : \"" + mBuildInfoCache.getString("displayName") + "\"");
            Log.d(TAG, "name           : \"" + mBuildInfoCache.getString("name") + "\"");
            Log.d(TAG, "version        : \"" + mBuildInfoCache.getString("version") + "\"");
            Log.d(TAG, "versionCode    : " + mBuildInfoCache.getInt("versionCode"));
            Log.d(TAG, "debug          : " + (mBuildInfoCache.getBoolean("debug") ? "true" : "false"));
            Log.d(TAG, "buildType      : \"" + mBuildInfoCache.getString("buildType") + "\"");
            Log.d(TAG, "flavor         : \"" + mBuildInfoCache.getString("flavor") + "\"");
        }
    } catch (JSONException e) {
        e.printStackTrace();
        callbackContext.error("JSONException: " + e.getMessage());
        return;
    }

    callbackContext.success(mBuildInfoCache);
}

From source file:org.acra.ErrorReporter.java

/**
 * Can only be constructed from within this class.
 *
 * @param context/*from w  ww .ja  v a  2 s . c  om*/
 *            Context for the application in which ACRA is running.
 * @param prefs
 *            SharedPreferences used by ACRA.
 * @param enabled
 *            Whether this ErrorReporter should capture Exceptions and
 *            forward their reports.
 */
ErrorReporter(Application context, SharedPreferences prefs, boolean enabled) {

    this.mContext = context;
    this.prefs = prefs;
    this.enabled = enabled;

    // Store the initial Configuration state.
    // This is expensive to gather, so only do so if we plan to report it.
    final String initialConfiguration;
    if (ACRA.getConfig().getReportFields().contains(ReportField.INITIAL_CONFIGURATION)) {
        initialConfiguration = ConfigurationCollector.collectConfiguration(mContext);
    } else {
        initialConfiguration = null;
    }

    // Sets the application start date.
    // This will be included in the reports, will be helpful compared to
    // user_crash date.
    final Calendar appStartDate = new GregorianCalendar();

    if (Compatibility.getAPILevel() >= Compatibility.VERSION_CODES.ICE_CREAM_SANDWICH) { // ActivityLifecycleCallback
        // only available for API14+
        ApplicationHelper.registerActivityLifecycleCallbacks(context, new ActivityLifecycleCallbacksCompat() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                if (ACRA.DEV_LOGGING)
                    ACRA.log.d(LOG_TAG, "onActivityCreated " + activity.getClass());
                if (!(activity instanceof BaseCrashReportDialog)) {
                    // Ignore CrashReportDialog because we want the last
                    // application Activity that was started so that we can
                    // explicitly kill it off.
                    lastActivityCreated = new WeakReference<Activity>(activity);
                }
            }

            @Override
            public void onActivityStarted(Activity activity) {
                if (ACRA.DEV_LOGGING)
                    ACRA.log.d(LOG_TAG, "onActivityStarted " + activity.getClass());
            }

            @Override
            public void onActivityResumed(Activity activity) {
                if (ACRA.DEV_LOGGING)
                    ACRA.log.d(LOG_TAG, "onActivityResumed " + activity.getClass());
            }

            @Override
            public void onActivityPaused(Activity activity) {
                if (ACRA.DEV_LOGGING)
                    ACRA.log.d(LOG_TAG, "onActivityPaused " + activity.getClass());
            }

            @Override
            public void onActivityStopped(Activity activity) {
                if (ACRA.DEV_LOGGING)
                    ACRA.log.d(LOG_TAG, "onActivityStopped " + activity.getClass());
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                if (ACRA.DEV_LOGGING)
                    ACRA.log.i(LOG_TAG, "onActivitySaveInstanceState " + activity.getClass());
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                if (ACRA.DEV_LOGGING)
                    ACRA.log.i(LOG_TAG, "onActivityDestroyed " + activity.getClass());
            }
        });
    }

    crashReportDataFactory = new CrashReportDataFactory(mContext, prefs, appStartDate, initialConfiguration);

    // If mDfltExceptionHandler is not null, initialization is already done.
    // Don't do it twice to avoid losing the original handler.
    mDfltExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(this);
}

From source file:com.money.manager.ex.common.AllDataListFragment.java

/**
 * Add options to the action bar of the host activity.
 * This is not called in ActionBar Activity, i.e. Search.
 * @param menu// ww  w.j  a va2  s. c o  m
 * @param inflater
 */
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);

    Activity activity = getActivity();
    if (activity == null)
        return;

    MenuItem itemExportToCsv = menu.findItem(R.id.menu_export_to_csv);
    if (itemExportToCsv != null)
        itemExportToCsv.setVisible(true);
    MenuItem itemSearch = menu.findItem(R.id.menu_search_transaction);

    if (itemSearch != null) {
        itemSearch
                .setVisible(!activity.getClass().getSimpleName().equals(SearchActivity.class.getSimpleName()));
    }

    // show this on all transactions lists later?
    // show this menu only when on Search Activity for now.
    if (activity.getClass().getSimpleName().equals(SearchActivity.class.getSimpleName())) {
        // Add default menu options. todo: check why this is executed twice.
        // Includes menu item for .qif export
        MenuItem qifExport = menu.findItem(R.id.menu_qif_export);
        if (qifExport == null) {
            inflater.inflate(R.menu.menu_alldata_operations, menu);
        }
    }
}

From source file:org.acra.ErrorReporter.java

/**
 * End the application./*from w ww  . j a v  a 2s . c  o  m*/
 */
private void endApplication(Thread uncaughtExceptionThread, Throwable th) {
    // TODO It would be better to create an explicit config attribute #letDefaultHandlerEndApplication
    // as the intent is clearer and would allows you to switch it off for SILENT.
    final boolean letDefaultHandlerEndApplication = (ACRA.getConfig().mode() == ReportingInteractionMode.SILENT
            || (ACRA.getConfig().mode() == ReportingInteractionMode.TOAST
                    && ACRA.getConfig().forceCloseDialogAfterToast()));

    final boolean handlingUncaughtException = uncaughtExceptionThread != null;
    if (handlingUncaughtException && letDefaultHandlerEndApplication && (mDfltExceptionHandler != null)) {
        // Let the system default handler do it's job and display the force close dialog.
        ACRA.log.d(LOG_TAG, "Handing Exception on to default ExceptionHandler");
        mDfltExceptionHandler.uncaughtException(uncaughtExceptionThread, th);
    } else {
        // If ACRA handles user notifications with a Toast or a Notification
        // the Force Close dialog is one more notification to the user...
        // We choose to close the process ourselves using the same actions.
        ACRA.log.e(LOG_TAG, mContext.getPackageName() + " fatal error : " + th.getMessage(), th);

        // Trying to solve
        // https://github.com/ACRA/acra/issues/42#issuecomment-12134144
        // Determine the current/last Activity that was started and close
        // it. Activity#finish (and maybe it's parent too).
        final Activity lastActivity = lastActivityCreated.get();
        if (lastActivity != null) {
            ACRA.log.i(LOG_TAG, "Finishing the last Activity prior to killing the Process");
            lastActivity.finish();
            ACRA.log.i(LOG_TAG, "Finished " + lastActivity.getClass());
            lastActivityCreated.clear();
        }

        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(10);
    }
}

From source file:org.ubicompforall.cityexplorer.CityExplorer.java

/***
 * Ping Google//from  w  ww. j  ava 2  s . c om
 * Start a browser if the page contains a (log-in) "redirect="
 */
public static boolean pingConnection(Activity context, String url) {
    boolean urlAvailable = false;
    if (ensureConnected(context)) {
        showProgressDialog(context);
        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpResponse response = httpclient.execute(new HttpGet(url));
            StatusLine statusLine = response.getStatusLine();
            debug(2, "statusLine is " + statusLine);

            // HTTP status is OK even if not logged in to NTNU
            //Toast.makeText( context, "Status-line is "+statusLine, Toast.LENGTH_LONG).show();
            if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                String responseString = out.toString();
                if (responseString.contains("redirect=")) { // Connection to url should be checked.
                    debug(2, "Redirect detected for url: " + url);
                    //Toast.makeText( context, "Mismatched url: "+url, Toast.LENGTH_LONG).show();
                } else {
                    urlAvailable = true;
                } // if redirect page, else probably OK
            } else {//if status OK, else: Closes the connection on failure
                response.getEntity().getContent().close();
            } //if httpStatus OK, else close

            //Start browser to log in
            if (!urlAvailable) {
                //throw new IOException( statusLine.getReasonPhrase() );

                //String activity = Thread.currentThread().getStackTrace()[3].getClassName();
                Toast.makeText(context, "Web access needed! Are you logged in?", Toast.LENGTH_LONG).show();
                //Uri uri = Uri.parse( url +"#"+ context.getClass().getCanonicalName() );
                Uri uri = Uri.parse(url + "?activity=" + context.getClass().getCanonicalName());
                debug(0, "Pinging magic url: " + uri);
                debug(0, " Need the web for uri: " + uri);
                context.startActivityForResult(new Intent(Intent.ACTION_VIEW, uri), REQUEST_KILL_BROWSER);
                //urlAvailable=true;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) { // Caused by bad url for example, missing http:// etc. Can still use cached maps...
            urlAvailable = false;
            debug(0, "Missing http:// in " + url + " ?");
        } catch (IOException e) { // e.g. UnknownHostException // try downloading db's from the Web, catch (and print) exceptions
            e.printStackTrace();
            urlAvailable = false;
        }
    } // if not already loaded once before
    return urlAvailable;
}

From source file:com.facebook.react.ReactInstanceManager.java

/**
 * Call this from {@link Activity#onPause()}. This notifies any listening modules so they can do
 * any necessary cleanup. The passed Activity is the current Activity being paused. This will
 * always be the foreground activity that would be returned by
 * {@link ReactContext#getCurrentActivity()}.
 *
 * @param activity the activity being paused
 *///from   w  w  w. j  ava2s.c  o  m
@ThreadConfined(UI)
public void onHostPause(Activity activity) {
    Assertions.assertNotNull(mCurrentActivity);
    Assertions.assertCondition(activity == mCurrentActivity,
            "Pausing an activity that is not the current activity, this is incorrect! " + "Current activity: "
                    + mCurrentActivity.getClass().getSimpleName() + " " + "Paused activity: "
                    + activity.getClass().getSimpleName());
    onHostPause();
}

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.
 * // w  w w. j a v a 2s. c  om
 * <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:com.silentcircle.contacts.group.GroupEditorFragment.java

/**
 * Saves or creates the group based on the mode, and if successful
 * finishes the activity. This actually only handles saving the group name.
 * @return true when successful// w w w. j a va 2s  . c om
 */
public boolean save() {
    if (!hasValidGroupName() || mStatus != Status.EDITING) {
        return false;
    }

    // If we are about to close the editor - there is no need to refresh the data
    getLoaderManager().destroyLoader(LOADER_EXISTING_MEMBERS);

    // If there are no changes, then go straight to onSaveCompleted()
    if (!hasNameChange() && !hasMembershipChange()) {
        onSaveCompleted(false, mGroupUri);
        return true;
    }

    mStatus = Status.SAVING;

    Activity activity = getActivity();
    // If the activity is not there anymore, then we can't continue with the save process.
    if (activity == null) {
        return false;
    }
    Intent saveIntent = null;
    if (Intent.ACTION_INSERT.equals(mAction)) {
        // Create array of raw contact IDs for contacts to add to the group
        long[] membersToAddArray = convertToArray(mListMembersToAdd);

        // Create the save intent to create the group and add members at the same time
        saveIntent = ScContactSaveService.createNewGroupIntent(activity, mGroupNameView.getText().toString(),
                membersToAddArray, activity.getClass(), GroupEditorActivity.ACTION_SAVE_COMPLETED);
    } else if (Intent.ACTION_EDIT.equals(mAction)) {
        // Create array of raw contact IDs for contacts to add to the group
        long[] membersToAddArray = convertToArray(mListMembersToAdd);

        // Create array of raw contact IDs for contacts to add to the group
        long[] membersToRemoveArray = convertToArray(mListMembersToRemove);

        // Create the update intent (which includes the updated group name if necessary)
        saveIntent = ScContactSaveService.createGroupUpdateIntent(activity, mGroupId, getUpdatedName(),
                membersToAddArray, membersToRemoveArray, activity.getClass(),
                GroupEditorActivity.ACTION_SAVE_COMPLETED);
    } else {
        throw new IllegalStateException("Invalid intent action type " + mAction);
    }
    activity.startService(saveIntent);
    return true;
}

From source file:im.vector.VectorApp.java

/**
 * A new activity has been resumed//from w w w  .j a  va  2  s . c o  m
 *
 * @param activity the new activity
 */
private void onNewScreen(Activity activity) {
    if (PreferencesManager.useAnalytics(this)) {
        Tracker tracker = getPiwikTracker();
        if (null != tracker) {
            try {
                TrackHelper.Screen screen = TrackHelper.track()
                        .screen("/android/" + Matrix.getApplicationName() + "/"
                                + this.getString(R.string.flavor_description) + "/" + SHORT_VERSION + "/"
                                + activity.getClass().getName().replace(".", "/"));
                addCustomVariables(screen).with(tracker);
            } catch (Throwable t) {
                Log.e(LOG_TAG, "## onNewScreen() : failed " + t.getMessage());
            }
        }
    }
}

From source file:com.amazonaws.mobile.client.AWSMobileClient.java

private Runnable _showSignIn(final Activity callingActivity, final SignInUIOptions signInUIOptions,
        final Callback<UserStateDetails> callback) {

    return new Runnable() {
        @Override//from  w w  w.  j  av a2 s  . c  om
        public void run() {
            synchronized (showSignInLockObject) {
                UserState userState = getUserStateDetails(false).getUserState();
                if (UserState.SIGNED_IN.equals(userState)) {
                    callback.onError(new RuntimeException("Called showSignIn while user is already signed-in"));
                    return;
                }

                final AuthUIConfiguration.Builder authUIConfigBuilder = new AuthUIConfiguration.Builder()
                        .canCancel(signInUIOptions.canCancel()).isBackgroundColorFullScreen(false);

                if (signInUIOptions.getLogo() != null) {
                    authUIConfigBuilder.logoResId(signInUIOptions.getLogo());
                }
                if (signInUIOptions.getBackgroundColor() != null) {
                    authUIConfigBuilder.backgroundColor(signInUIOptions.getBackgroundColor());
                }

                final IdentityManager identityManager = IdentityManager.getDefaultIdentityManager();

                if (isConfigurationKeyPresent(USER_POOLS)) {
                    authUIConfigBuilder.userPools(true);
                    identityManager.addSignInProvider(CognitoUserPoolsSignInProvider.class);
                }

                if (isConfigurationKeyPresent(FACEBOOK)) {
                    authUIConfigBuilder.signInButton(FacebookButton.class);
                    identityManager.addSignInProvider(FacebookSignInProvider.class);
                }

                if (isConfigurationKeyPresent(GOOGLE)) {
                    authUIConfigBuilder.signInButton(GoogleButton.class);
                    identityManager.addSignInProvider(GoogleSignInProvider.class);
                }

                Class<? extends Activity> nextActivityClass = signInUIOptions.nextActivity() == null
                        ? callingActivity.getClass()
                        : signInUIOptions.nextActivity();
                SignInUI signin = (SignInUI) getClient(mContext, SignInUI.class);
                signin.login(callingActivity, nextActivityClass)
                        .authUIConfiguration(authUIConfigBuilder.build()).enableFederation(false).execute();

                showSignInWaitLatch = new CountDownLatch(1);
                try {
                    showSignInWaitLatch.await();
                    Log.d(TAG, "run: showSignIn completed");
                } catch (InterruptedException e) {
                    callback.onError(e);
                }
            }
        }
    };
}