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:com.android.launcher3.Utilities.java

private static void checkPermissionForRingtone(Activity activity) {
    NotificationManager notificationManager = (NotificationManager) activity.getApplicationContext()
            .getSystemService(Context.NOTIFICATION_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
            && !notificationManager.isNotificationPolicyAccessGranted()) {

        Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);

        activity.startActivity(intent);/* w  w w .j a v  a2  s  .c  o m*/
    }
}

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

/**
 * Helper method to display a toast message.
 *
 * @param aCallingActivity calling Activity instance
 * @param aMsgToDisplay    message to display
 */// w w w.j a va 2s.c o m
public static void displayToastOnUiThread(final Activity aCallingActivity, final String aMsgToDisplay) {
    if (null != aCallingActivity) {
        aCallingActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                CommonActivityUtils.displayToast(aCallingActivity.getApplicationContext(), aMsgToDisplay);
            }
        });
    }
}

From source file:com.remobile.file.FileUtils.java

protected HashMap<String, String> getAvailableFileSystems(Activity activity) {
    Context context = activity.getApplicationContext();
    HashMap<String, String> availableFileSystems = new HashMap<String, String>();

    availableFileSystems.put("files", context.getFilesDir().getAbsolutePath());
    availableFileSystems.put("documents", new File(context.getFilesDir(), "Documents").getAbsolutePath());
    availableFileSystems.put("cache", context.getCacheDir().getAbsolutePath());
    availableFileSystems.put("root", "/");
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        try {//  ww  w . j av a 2s . co m
            availableFileSystems.put("files-external", context.getExternalFilesDir(null).getAbsolutePath());
            availableFileSystems.put("sdcard", Environment.getExternalStorageDirectory().getAbsolutePath());
            availableFileSystems.put("cache-external", context.getExternalCacheDir().getAbsolutePath());
        } catch (NullPointerException e) {
            Log.d(LOG_TAG, "External storage unavailable, check to see if USB Mass Storage Mode is on");
        }
    }

    return availableFileSystems;
}

From source file:paulscode.android.mupen64plusae.ScanRomsFragment.java

private void ActuallyRefreshRoms(Activity activity) {
    mInProgress = true;// w  w w .j  a  va2  s  . c o  m

    CharSequence title = getString(R.string.scanning_title);
    CharSequence message = getString(R.string.toast_pleaseWait);
    mProgress = new ProgressDialog(mProgress, getActivity(), title, mStartDir.getAbsolutePath(), message, true);
    mProgress.show();

    /** Defines callbacks for service binding, passed to bindService() */
    mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {

            // We've bound to LocalService, cast the IBinder and get LocalService instance
            LocalBinder binder = (LocalBinder) service;
            CacheRomInfoService cacheRomInfoService = binder.getService();
            cacheRomInfoService.SetCacheRomInfoListener(ScanRomsFragment.this);
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            //Nothing to do here
        }
    };

    // Asynchronously search for ROMs
    ActivityHelper.startCacheRomInfoService(activity.getApplicationContext(), mServiceConnection,
            mStartDir.getAbsolutePath(), mAppData.mupen64plus_ini, mGlobalPrefs.romInfoCache_cfg,
            mGlobalPrefs.coverArtDir, mGlobalPrefs.unzippedRomsDir, mSearchZips, mDownloadArt, mClearGallery);
}

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

/**
 * Launches Apptentive features based on a push notification Intent. Before you call this, you must call
 * {@link Apptentive#setPendingPushNotification(Context, Intent)} in your Broadcast receiver when a push notification
 * is opened by the user. This method must be called from the Activity that you launched from the
 * BroadcastReceiver. This method will only handle Apptentive originated push notifications, so call is any time you
 * receive a push./*from  www  . j av  a 2  s  .  c om*/
 * <p/>
 * <strong>Note: </strong>If you are using Parse, do not use this method. Instead, see the Apptentive
 * <a href="http://www.apptentive.com/docs/android/integration/"> integration guide</a> for Parse.
 *
 * @param activity The Activity from which this method is called.
 * @return True if a call to this method resulted in Apptentive displaying a View.
 */
public static boolean handleOpenedPushNotification(Activity activity) {
    SharedPreferences prefs = activity.getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE);
    String pushData = prefs.getString(Constants.PREF_KEY_PENDING_PUSH_NOTIFICATION, null);
    prefs.edit().remove(Constants.PREF_KEY_PENDING_PUSH_NOTIFICATION).commit(); // Remove our data so this won't run twice.
    if (pushData != null) {
        Log.i("Handling Apptentive Push Intent.");
        try {
            JSONObject pushJson = new JSONObject(pushData);
            ApptentiveInternal.PushAction action = ApptentiveInternal.PushAction.unknown;
            if (pushJson.has(ApptentiveInternal.PUSH_ACTION)) {
                action = ApptentiveInternal.PushAction
                        .parse(pushJson.getString(ApptentiveInternal.PUSH_ACTION));
            }
            switch (action) {
            case pmc:
                Apptentive.showMessageCenter(activity);
                return true;
            default:
                Log.v("Unknown Push Notification Action \"%s\"", action.name());
            }
        } catch (JSONException e) {
            Log.w("Error parsing JSON from push notification.", e);
            MetricModule.sendError(activity.getApplicationContext(), e, "Parsing Push notification", pushData);
        }
    }
    return false;
}

From source file:uk.org.rivernile.edinburghbustracker.android.fragments.dialogs.AboutDialogFragment.java

/**
 * {@inheritDoc}//from  w  ww . j  av  a 2  s.  c  om
 */
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
    final Activity activity = getActivity();

    // Get the inflater then inflate the view from XML.
    final LayoutInflater inflater = LayoutInflater.from(activity);
    final View layout = inflater.inflate(R.layout.about, null);

    final TextView temp = (TextView) layout.findViewById(R.id.aboutVersion);

    // Set the version text.
    try {
        temp.setText(getString(R.string.aboutdialog_version,
                activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0).versionName,
                activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0).versionCode));
    } catch (NameNotFoundException e) {
        // This should never occur.
        temp.setText("Unknown");
    }

    final TextView txtDBVersion = (TextView) layout.findViewById(R.id.aboutDBVersion);
    final TextView txtTopoVersion = (TextView) layout.findViewById(R.id.aboutTopoVersion);

    // Get the database mod time.
    long dbtime;
    final Calendar date = Calendar.getInstance();
    final BusStopDatabase bsd = BusStopDatabase.getInstance(activity.getApplicationContext());
    try {
        dbtime = bsd.getLastDBModTime();
    } catch (SQLException e) {
        dbtime = 0;
    }

    date.setTimeInMillis(dbtime);

    // Set the DB version text.
    txtDBVersion.setText(getString(R.string.aboutdialog_dbversion, dbtime, dateFormat.format(date.getTime())));
    // Set the topology ID text.
    txtTopoVersion.setText(getString(R.string.aboutdialog_topology, bsd.getTopoId()));

    final Button btnLicenses = (Button) layout.findViewById(R.id.btnLicenses);
    btnLicenses.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            callbacks.onShowLicences();
        }
    });

    // Get the AlertDialog.Builder with the correct theme set.
    final AlertDialog.Builder builder;
    if (isHoneycombOrGreater) {
        builder = getHoneycombDialog(activity);
    } else {
        builder = new AlertDialog.Builder(activity);
    }

    // Build the Dialog.
    builder.setView(layout).setNegativeButton(R.string.close, null);

    return builder.create();
}

From source file:com.breadwallet.tools.security.RequestHandler.java

public static boolean tryBitIdUri(final Activity app, String uri, JSONObject jsonBody) {
    if (uri == null)
        return false;
    boolean isBitUri = false;

    URI bitIdUri = null;//w w  w. ja va  2s .  c  o m
    try {
        bitIdUri = new URI(uri);
        if ("bitid".equals(bitIdUri.getScheme()))
            isBitUri = true;
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    _bitUri = uri;

    if (jsonBody != null) {
        try {
            _authString = jsonBody.getString("prompt_string");
            _bitCallback = jsonBody.getString("bitid_url");
            _index = jsonBody.getInt("bitid_index");
            _strToSign = jsonBody.getString("string_to_sign");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } else if (bitIdUri != null && "bitid".equals(bitIdUri.getScheme())) {
        if (app == null) {
            Log.e(TAG, "tryBitIdUri: app is null, returning true still");
            return isBitUri;
        }

        //ask for phrase, will system auth if needed

        _authString = "BitID Authentication Request";
    }

    //        Log.e(TAG, "tryBitIdUri: _bitUri: " + _bitUri);
    //        Log.e(TAG, "tryBitIdUri: _strToSign: " + _strToSign);
    //        Log.e(TAG, "tryBitIdUri: _index: " + _index);

    new Thread(new Runnable() {
        @Override
        public void run() {
            byte[] phrase = null;
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Uri tmpUri = Uri.parse(_bitUri);
            try {
                phrase = KeyStoreManager.getKeyStorePhrase(app, REQUEST_PHRASE_BITID);
                ((BreadWalletApp) app.getApplicationContext()).promptForAuthentication(app, AUTH_FOR_BIT_ID,
                        null, tmpUri.getHost(), _authString, null, false);
            } catch (BRKeystoreErrorException e) {
                //asked the system, no need for local auth
                e.printStackTrace();
            } finally {
                //free the phrase
                if (phrase != null)
                    Arrays.fill(phrase, (byte) 0);
            }
        }
    }).start();
    return isBitUri;

}

From source file:paulscode.android.mupen64plusae.ExtractTexturesFragment.java

private void actuallyExtractTextures(Activity activity) {
    mInProgress = true;/*from  ww w  .j av  a2  s  .com*/

    CharSequence title = getString(R.string.pathHiResTexturesTask_title);
    CharSequence message = getString(R.string.toast_pleaseWait);
    mProgress = new ProgressDialog(mProgress, getActivity(), title, mTexturesZipPath.getAbsolutePath(), message,
            true);
    mProgress.show();

    /** Defines callbacks for service binding, passed to bindService() */
    mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {

            // We've bound to LocalService, cast the IBinder and get LocalService instance
            LocalBinder binder = (LocalBinder) service;
            ExtractTexturesService extractTexturesService = binder.getService();
            extractTexturesService.setExtractTexturesListener(ExtractTexturesFragment.this);
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            //Nothing to do here
        }
    };

    // Asynchronously extract textures
    ActivityHelper.startExtractTexturesService(activity.getApplicationContext(), mServiceConnection,
            mTexturesZipPath.getAbsolutePath());
}

From source file:cm.aptoide.com.facebook.android.Facebook.java

/**
 * Full authorize method./* www .jav  a 2 s. c o m*/
 *
 * Starts either an Activity or a dialog which prompts the user to log in to
 * Facebook and grant the requested permissions to the given application.
 *
 * This method will, when possible, use Facebook's single sign-on for
 * Android to obtain an access token. This involves proxying a call through
 * the Facebook for Android stand-alone application, which will handle the
 * authentication flow, and return an OAuth access token for making API
 * calls.
 *
 * Because this process will not be available for all users, if single
 * sign-on is not possible, this method will automatically fall back to the
 * OAuth 2.0 User-Agent flow. In this flow, the user credentials are handled
 * by Facebook in an embedded WebView, not by the client application. As
 * such, the dialog makes a network request and renders HTML content rather
 * than a native UI. The access token is retrieved from a redirect to a
 * special URL that the WebView handles.
 *
 * Note that User credentials could be handled natively using the OAuth 2.0
 * Username and Password Flow, but this is not supported by this SDK.
 *
 * See http://developers.facebook.com/docs/authentication/ and
 * http://wiki.oauth.net/OAuth-2 for more details.
 *
 * Note that this method is asynchronous and the callback will be invoked in
 * the original calling thread (not in a background thread).
 *
 * Also note that requests may be made to the API without calling authorize
 * first, in which case only public information is returned.
 *
 * IMPORTANT: Note that single sign-on authentication will not function
 * correctly if you do not include a call to the authorizeCallback() method
 * in your onActivityResult() function! Please see below for more
 * information. single sign-on may be disabled by passing FORCE_DIALOG_AUTH
 * as the activityCode parameter in your call to authorize().
 *
 * @param activity
 *            The Android activity in which we want to display the
 *            authorization dialog.
 * @param applicationId
 *            The Facebook application identifier e.g. "350685531728"
 * @param permissions
 *            A list of permissions required for this application: e.g.
 *            "read_stream", "publish_stream", "offline_access", etc. see
 *            http://developers.facebook.com/docs/authentication/permissions
 *            This parameter should not be null -- if you do not require any
 *            permissions, then pass in an empty String array.
 * @param activityCode
 *            Single sign-on requires an activity result to be called back
 *            to the client application -- if you are waiting on other
 *            activities to return data, pass a custom activity code here to
 *            avoid collisions. If you would like to force the use of legacy
 *            dialog-based authorization, pass FORCE_DIALOG_AUTH for this
 *            parameter. Otherwise just omit this parameter and Facebook
 *            will use a suitable default. See
 *            http://developer.android.com/reference/android/
 *              app/Activity.html for more information.
 * @param listener
 *            Callback interface for notifying the calling application when
 *            the authentication dialog has completed, failed, or been
 *            canceled.
 */
public void authorize(Activity activity, String[] permissions, int activityCode,
        final DialogListener listener) {

    boolean singleSignOnStarted = false;

    mAuthDialogListener = listener;

    // fire off an auto-attribution publish if appropriate.
    autoPublishAsync(activity.getApplicationContext());

    // Prefer single sign-on, where available.
    if (activityCode >= 0) {
        singleSignOnStarted = startSingleSignOn(activity, mAppId, permissions, activityCode);
    }
    // Otherwise fall back to traditional dialog.
    if (!singleSignOnStarted) {
        startDialogAuth(activity, permissions);
    }
}

From source file:com.vuze.android.remote.AndroidUtils.java

public static void openFileChooser(Activity activity, String mimeType, int requestCode) {

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType(mimeType);/*from   ww w.  j  a v  a2  s .c  o m*/
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    // special intent for Samsung file manager
    Intent sIntent = new Intent("com.sec.android.app.myfiles.PICK_DATA");

    sIntent.putExtra("CONTENT_TYPE", mimeType);
    sIntent.addCategory(Intent.CATEGORY_DEFAULT);

    Intent chooserIntent;
    if (activity.getPackageManager().resolveActivity(sIntent, 0) != null) {
        chooserIntent = Intent.createChooser(sIntent, "Open file");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { intent });
    } else {
        chooserIntent = Intent.createChooser(intent, "Open file");
    }

    if (chooserIntent != null) {
        try {
            activity.startActivityForResult(chooserIntent, requestCode);
            return;
        } catch (android.content.ActivityNotFoundException ex) {
        }
    }
    Toast.makeText(activity.getApplicationContext(),
            activity.getResources().getString(R.string.no_file_chooser), Toast.LENGTH_SHORT).show();
}