Example usage for android.app Activity getApplicationContext

List of usage examples for android.app Activity getApplicationContext

Introduction

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

Prototype

@Override
    public Context getApplicationContext() 

Source Link

Usage

From source file:im.vector.activity.CommonActivityUtils.java

public static void goToOneToOneRoom(final MXSession aSession, final String otherUserId,
        final Activity fromActivity, final ApiCallback<Void> callback) {
    // sanity check
    if (null == otherUserId) {
        return;/*from  ww w .j av  a  2  s . c o m*/
    }

    // check first if the 1:1 room already exists
    MXSession session = (aSession == null) ? Matrix.getMXSession(fromActivity, null) : aSession;

    // no session is provided
    if (null == session) {
        // get the default one.
        session = Matrix.getInstance(fromActivity.getApplicationContext()).getDefaultSession();
    }

    // sanity check
    if ((null == session) || !session.isActive()) {
        return;
    }

    final MXSession fSession = session;

    // so, list the existing room, and search the 2 users room with this other users
    String roomId = null;
    Collection<Room> rooms = session.getDataHandler().getStore().getRooms();

    for (Room room : rooms) {
        Collection<RoomMember> members = room.getMembers();

        if (members.size() == 2) {
            for (RoomMember member : members) {
                if (member.getUserId().equals(otherUserId)) {
                    roomId = room.getRoomId();
                    break;
                }
            }
        }
    }

    // the room already exists -> switch to it
    if (null != roomId) {
        CommonActivityUtils.goToRoomPage(session, roomId, fromActivity, null);

        // everything is ok
        if (null != callback) {
            callback.onSuccess(null);
        }
    } else {
        session.createRoom(null, null, RoomState.VISIBILITY_PRIVATE, null,
                new SimpleApiCallback<String>(fromActivity) {

                    @Override
                    public void onSuccess(String roomId) {
                        final Room room = fSession.getDataHandler().getRoom(roomId);

                        room.invite(otherUserId, new SimpleApiCallback<Void>(this) {
                            @Override
                            public void onSuccess(Void info) {
                                CommonActivityUtils.goToRoomPage(fSession, room.getRoomId(), fromActivity,
                                        null);

                                callback.onSuccess(null);
                            }

                            @Override
                            public void onMatrixError(MatrixError e) {
                                if (null != callback) {
                                    callback.onMatrixError(e);
                                }
                            }

                            @Override
                            public void onNetworkError(Exception e) {
                                if (null != callback) {
                                    callback.onNetworkError(e);
                                }
                            }

                            @Override
                            public void onUnexpectedError(Exception e) {
                                if (null != callback) {
                                    callback.onUnexpectedError(e);
                                }
                            }

                        });
                    }

                    @Override
                    public void onMatrixError(MatrixError e) {
                        if (null != callback) {
                            callback.onMatrixError(e);
                        }
                    }

                    @Override
                    public void onNetworkError(Exception e) {
                        if (null != callback) {
                            callback.onNetworkError(e);
                        }
                    }

                    @Override
                    public void onUnexpectedError(Exception e) {
                        if (null != callback) {
                            callback.onUnexpectedError(e);
                        }
                    }
                });
    }
}

From source file:com.fatelon.partyphotobooth.setup.fragments.PhotoBoothSetupFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Activity activity = getActivity();
    final Context appContext = activity.getApplicationContext();

    /*//from  w ww.j a v  a 2 s.  c o m
     * Configure views with saved preferences and functionalize.
     */
    final PhotoBoothModeAdapter modeAdapter = new PhotoBoothModeAdapter(activity);
    mMode.setAdapter(modeAdapter);
    mMode.setSelection(mPreferencesHelper.getPhotoBoothMode(appContext).ordinal());
    mMode.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            PreferencesHelper.PhotoBoothMode selectedMode = modeAdapter.getPhotoBoothMode(position);
            mPreferencesHelper.storePhotoBoothMode(appContext, selectedMode);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // Do nothing.
        }
    });

    final PhotoBoothThemeAdapter themeAdapter = new PhotoBoothThemeAdapter(activity);
    mTheme.setAdapter(themeAdapter);
    mTheme.setSelection(mPreferencesHelper.getPhotoBoothTheme(appContext).ordinal());
    mTheme.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            PreferencesHelper.PhotoBoothTheme selectedTheme = themeAdapter.getPhotoBoothTheme(position);
            mPreferencesHelper.storePhotoBoothTheme(appContext, selectedTheme);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // Do nothing.
        }
    });

    final PhotoStripTemplateAdapter templateAdapter = new PhotoStripTemplateAdapter(activity);
    mTemplate.setAdapter(templateAdapter);
    mTemplate.setSelection(mPreferencesHelper.getPhotoStripTemplate(appContext).ordinal());
    mTemplate.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            PreferencesHelper.PhotoStripTemplate selectedTemplate = templateAdapter
                    .getPhotoStripTemplate(position);
            mPreferencesHelper.storePhotoStripTemplate(appContext, selectedTemplate);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // Do nothing.
        }
    });

    mNext.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // Call to client.
            ICallbacks callbacks = getCallbacks();
            if (callbacks != null) {
                callbacks.onPhotoBoothSetupCompleted();
            }
        }
    });
}

From source file:com.groundupworks.partyphotobooth.setup.fragments.PhotoBoothSetupFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Activity activity = getActivity();
    final Context appContext = activity.getApplicationContext();

    /*//from w w  w .j  av a 2s. c o m
     * Configure views with saved preferences and functionalize.
     */
    final PhotoBoothModeAdapter modeAdapter = new PhotoBoothModeAdapter(activity);
    mMode.setAdapter(modeAdapter);
    mMode.setSelection(mPreferencesHelper.getPhotoBoothMode(appContext).ordinal());
    mMode.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            PhotoBoothMode selectedMode = modeAdapter.getPhotoBoothMode(position);
            mPreferencesHelper.storePhotoBoothMode(appContext, selectedMode);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // Do nothing.
        }
    });

    final PhotoBoothThemeAdapter themeAdapter = new PhotoBoothThemeAdapter(activity);
    mTheme.setAdapter(themeAdapter);
    mTheme.setSelection(mPreferencesHelper.getPhotoBoothTheme(appContext).ordinal());
    mTheme.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            PhotoBoothTheme selectedTheme = themeAdapter.getPhotoBoothTheme(position);
            mPreferencesHelper.storePhotoBoothTheme(appContext, selectedTheme);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // Do nothing.
        }
    });

    final PhotoStripTemplateAdapter templateAdapter = new PhotoStripTemplateAdapter(activity);
    mTemplate.setAdapter(templateAdapter);
    mTemplate.setSelection(mPreferencesHelper.getPhotoStripTemplate(appContext).ordinal());
    mTemplate.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            PhotoStripTemplate selectedTemplate = templateAdapter.getPhotoStripTemplate(position);
            mPreferencesHelper.storePhotoStripTemplate(appContext, selectedTemplate);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // Do nothing.
        }
    });

    mNext.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // Call to client.
            ICallbacks callbacks = getCallbacks();
            if (callbacks != null) {
                callbacks.onPhotoBoothSetupCompleted();
            }
        }
    });
}

From source file:com.apptentive.android.sdk.Apptentive.java

private static void init(Activity activity) {

    ///*from   ww  w. ja  va2  s  . c o  m*/
    // First, initialize data relies on synchronous reads from local resources.
    //

    final Context appContext = activity.getApplicationContext();

    if (!GlobalInfo.initialized) {
        SharedPreferences prefs = appContext.getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE);

        // First, Get the api key, and figure out if app is debuggable.
        GlobalInfo.isAppDebuggable = false;
        String apiKey = null;
        boolean apptentiveDebug = false;
        String logLevelOverride = null;
        try {
            ApplicationInfo ai = appContext.getPackageManager().getApplicationInfo(appContext.getPackageName(),
                    PackageManager.GET_META_DATA);
            Bundle metaData = ai.metaData;
            if (metaData != null) {
                apiKey = metaData.getString(Constants.MANIFEST_KEY_APPTENTIVE_API_KEY);
                logLevelOverride = metaData.getString(Constants.MANIFEST_KEY_APPTENTIVE_LOG_LEVEL);
                apptentiveDebug = metaData.getBoolean(Constants.MANIFEST_KEY_APPTENTIVE_DEBUG);
                ApptentiveClient.useStagingServer = metaData
                        .getBoolean(Constants.MANIFEST_KEY_USE_STAGING_SERVER);
            }
            if (apptentiveDebug) {
                Log.i("Apptentive debug logging set to VERBOSE.");
                ApptentiveInternal.setMinimumLogLevel(Log.Level.VERBOSE);
            } else if (logLevelOverride != null) {
                Log.i("Overriding log level: %s", logLevelOverride);
                ApptentiveInternal.setMinimumLogLevel(Log.Level.parse(logLevelOverride));
            } else {
                GlobalInfo.isAppDebuggable = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
                if (GlobalInfo.isAppDebuggable) {
                    ApptentiveInternal.setMinimumLogLevel(Log.Level.VERBOSE);
                }
            }
        } catch (Exception e) {
            Log.e("Unexpected error while reading application info.", e);
        }

        Log.i("Debug mode enabled? %b", GlobalInfo.isAppDebuggable);

        // If we are in debug mode, but no api key is found, throw an exception. Otherwise, just assert log. We don't want to crash a production app.
        String errorString = "No Apptentive api key specified. Please make sure you have specified your api key in your AndroidManifest.xml";
        if ((Util.isEmpty(apiKey))) {
            if (GlobalInfo.isAppDebuggable) {
                AlertDialog alertDialog = new AlertDialog.Builder(activity).setTitle("Error")
                        .setMessage(errorString).setPositiveButton("OK", null).create();
                alertDialog.setCanceledOnTouchOutside(false);
                alertDialog.show();
            }
            Log.e(errorString);
        }
        GlobalInfo.apiKey = apiKey;

        Log.i("API Key: %s", GlobalInfo.apiKey);

        // Grab app info we need to access later on.
        GlobalInfo.appPackage = appContext.getPackageName();
        GlobalInfo.androidId = Settings.Secure.getString(appContext.getContentResolver(),
                android.provider.Settings.Secure.ANDROID_ID);

        // Check the host app version, and notify modules if it's changed.
        try {
            PackageManager packageManager = appContext.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(appContext.getPackageName(), 0);

            Integer currentVersionCode = packageInfo.versionCode;
            String currentVersionName = packageInfo.versionName;
            VersionHistoryStore.VersionHistoryEntry lastVersionEntrySeen = VersionHistoryStore
                    .getLastVersionSeen(appContext);
            if (lastVersionEntrySeen == null) {
                onVersionChanged(appContext, null, currentVersionCode, null, currentVersionName);
            } else {
                if (!currentVersionCode.equals(lastVersionEntrySeen.versionCode)
                        || !currentVersionName.equals(lastVersionEntrySeen.versionName)) {
                    onVersionChanged(appContext, lastVersionEntrySeen.versionCode, currentVersionCode,
                            lastVersionEntrySeen.versionName, currentVersionName);
                }
            }

            GlobalInfo.appDisplayName = packageManager
                    .getApplicationLabel(packageManager.getApplicationInfo(packageInfo.packageName, 0))
                    .toString();
        } catch (PackageManager.NameNotFoundException e) {
            // Nothing we can do then.
            GlobalInfo.appDisplayName = "this app";
        }

        // Grab the conversation token from shared preferences.
        if (prefs.contains(Constants.PREF_KEY_CONVERSATION_TOKEN)
                && prefs.contains(Constants.PREF_KEY_PERSON_ID)) {
            GlobalInfo.conversationToken = prefs.getString(Constants.PREF_KEY_CONVERSATION_TOKEN, null);
            GlobalInfo.personId = prefs.getString(Constants.PREF_KEY_PERSON_ID, null);
        }

        GlobalInfo.initialized = true;
        Log.v("Done initializing...");
    } else {
        Log.v("Already initialized...");
    }

    // Initialize the Conversation Token, or fetch if needed. Fetch config it the token is available.
    if (GlobalInfo.conversationToken == null || GlobalInfo.personId == null) {
        asyncFetchConversationToken(appContext.getApplicationContext());
    } else {
        asyncFetchAppConfiguration(appContext.getApplicationContext());
        InteractionManager.asyncFetchAndStoreInteractions(appContext.getApplicationContext());
    }

    // TODO: Do this on a dedicated thread if it takes too long. Some devices are slow to read device data.
    syncDevice(appContext);
    syncSdk(appContext);
    syncPerson(appContext);

    Log.d("Default Locale: %s", Locale.getDefault().toString());
    SharedPreferences prefs = appContext.getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE);
    Log.d("Conversation id: %s", prefs.getString(Constants.PREF_KEY_CONVERSATION_ID, "null"));
}

From source file:com.marianhello.cordova.bgloc.BackgroundGpsPlugin.java

public boolean execute(String action, JSONArray data, CallbackContext callbackContext) {
    Activity activity = this.cordova.getActivity();
    Context context = activity.getApplicationContext();
    Boolean result = false;/*w w  w  . j ava  2 s  .  co m*/
    updateServiceIntent = new Intent(activity, LocationUpdateService.class);

    if (ACTION_START.equalsIgnoreCase(action) && !isEnabled) {
        result = true;
        if (params == null || headers == null) {
            callbackContext.error("Call configure before calling start");
        } else {
            IntentFilter intentFilter = new IntentFilter(Constant.FILTER);
            // LocalBroadcastManager.getInstance(activity).registerReceiver(mMessageReceiver, intentFilter);
            context.registerReceiver(mMessageReceiver, intentFilter);

            updateServiceIntent.putExtra("url", url);
            updateServiceIntent.putExtra("params", params);
            updateServiceIntent.putExtra("headers", headers);
            updateServiceIntent.putExtra("stationaryRadius", stationaryRadius);
            updateServiceIntent.putExtra("desiredAccuracy", desiredAccuracy);
            updateServiceIntent.putExtra("distanceFilter", distanceFilter);
            updateServiceIntent.putExtra("locationTimeout", locationTimeout);
            updateServiceIntent.putExtra("desiredAccuracy", desiredAccuracy);
            updateServiceIntent.putExtra("isDebugging", isDebugging);
            updateServiceIntent.putExtra("notificationTitle", notificationTitle);
            updateServiceIntent.putExtra("notificationText", notificationText);
            updateServiceIntent.putExtra("stopOnTerminate", stopOnTerminate);

            activity.startService(updateServiceIntent);
            isEnabled = true;
            Log.d(TAG, "bg service has been started");
        }
    } else if (ACTION_STOP.equalsIgnoreCase(action)) {
        // LocalBroadcastManager.getInstance(activity).unregisterReceiver(mMessageReceiver);
        context.unregisterReceiver(mMessageReceiver);

        isEnabled = false;
        result = true;
        activity.stopService(updateServiceIntent);
        callbackContext.success();
        Log.d(TAG, "bg service has been stopped");
    } else if (ACTION_CONFIGURE.equalsIgnoreCase(action)) {
        result = true;
        try {
            this.callbackContext = callbackContext;
            // Params.
            //    0       1       2           3               4                5               6            7           8                9               10              11
            //[params, headers, url, stationaryRadius, distanceFilter, locationTimeout, desiredAccuracy, debug, notificationTitle, notificationText, activityType, stopOnTerminate]
            this.params = data.getString(0);
            this.headers = data.getString(1);
            this.url = data.getString(2);
            this.stationaryRadius = data.getString(3);
            this.distanceFilter = data.getString(4);
            this.locationTimeout = data.getString(5);
            this.desiredAccuracy = data.getString(6);
            this.isDebugging = data.getString(7);
            this.notificationTitle = data.getString(8);
            this.notificationText = data.getString(9);
            this.stopOnTerminate = data.getString(11);
            Log.d(TAG, "bg service configured");
        } catch (JSONException e) {
            callbackContext.error("authToken/url required as parameters: " + e.getMessage());
        }
    } else if (ACTION_SET_CONFIG.equalsIgnoreCase(action)) {
        result = true;
        // TODO reconfigure Service
        callbackContext.success();
        Log.d(TAG, "bg service reconfigured");
    } else if (ACTION_LOCATION_ENABLED_CHECK.equalsIgnoreCase(action)) {
        Log.d(TAG, "location services enabled check");
        try {
            int isLocationEnabled = BackgroundGpsPlugin.isLocationEnabled(context) ? 1 : 0;
            callbackContext.success(isLocationEnabled);
        } catch (SettingNotFoundException e) {
            callbackContext.error("Location setting not found on this platform");
        }
    }

    return result;
}

From source file:com.anysoftkeyboard.ui.settings.KeyboardAddOnSettingsFragment.java

@Override
public void onStart() {
    super.onStart();

    PreferenceCategory keyboardsGroup = (PreferenceCategory) findPreference("keyboard_addons_group");
    Activity activity = getActivity();
    PassengerFragmentSupport.setActivityTitle(this, getString(R.string.keyboards_group));
    // getting all keyboards
    final ArrayList<KeyboardAddOnAndBuilder> creators = KeyboardFactory
            .getAllAvailableKeyboards(activity.getApplicationContext());

    keyboardsGroup.removeAll();/*from  w w w  .  j a  v  a2 s . co m*/

    for (final KeyboardAddOnAndBuilder creator : creators) {
        final AddOnCheckBoxPreference checkBox = new AddOnCheckBoxPreference(activity, null,
                R.style.Theme_AppCompat_Light);
        checkBox.setAddOn(creator);
        keyboardsGroup.addPreference(checkBox);
    }
}

From source file:cn.newgxu.android.bbs.ui.RepliesFragment.java

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    app = (BBSApplication) activity.getApplicationContext();
}

From source file:org.angellist.angellistmobile.UserRolesJSONAdapter.java

UserRolesJSONAdapter(Activity activity, JSONArray jsonArray) {
    assert activity != null;
    assert jsonArray != null;

    this.jsonArray = jsonArray;
    this.activity = activity;
    imageLoader = new ImageLoader(activity.getApplicationContext());
}

From source file:org.gluu.super_gluu.app.fragments.SettingsFragment.SettingsList.SettingsListFragmentAdapter.java

public SettingsListFragmentAdapter(Activity activity, List<Map<String, Integer>> listContact,
        SettingsListFragment.SettingsListListener settingsListListener) {
    list = listContact;//from  w w  w  . j a v  a2s .c  o  m
    this.activity = activity;
    this.context = activity.getApplicationContext();
    mInflater = LayoutInflater.from(activity);
    mListener = settingsListListener;
    face = Typeface.createFromAsset(activity.getAssets(), "ProximaNova-Regular.otf");
    initIAPurchaseService();
}

From source file:com.anandmuralidhar.assimpandroid.GestureClass.java

public GestureClass(Activity activity) {

    // instantiate two listeners for detecting double-tap/drag and pinch-zoom
    mTapScrollDetector = new GestureDetectorCompat(activity, new MyTapScrollListener());
    mScaleDetector = new ScaleGestureDetector(activity.getApplicationContext(), new ScaleListener());

}