Example usage for android.app Activity getResources

List of usage examples for android.app Activity getResources

Introduction

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

Prototype

@Override
    public Resources getResources() 

Source Link

Usage

From source file:com.android.mms.ui.MessageUtils.java

public static void addNumberOrEmailtoContact(final String numberOrEmail, final int REQUEST_CODE,
        final Activity activity) {
    if (!TextUtils.isEmpty(numberOrEmail)) {
        String message = activity.getResources().getString(R.string.add_contact_dialog_message, numberOrEmail);
        AlertDialog.Builder builder = new AlertDialog.Builder(activity).setTitle(numberOrEmail)
                .setMessage(message);//from w w  w.ja  v a 2s .c  o m
        AlertDialog dialog = builder.create();
        dialog.setButton(AlertDialog.BUTTON_POSITIVE,
                activity.getResources().getString(R.string.add_contact_dialog_existing),
                new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
                        intent.setType(Contacts.CONTENT_ITEM_TYPE);
                        if (Mms.isEmailAddress(numberOrEmail)) {
                            intent.putExtra(ContactsContract.Intents.Insert.EMAIL, numberOrEmail);
                        } else {
                            intent.putExtra(ContactsContract.Intents.Insert.PHONE, numberOrEmail);
                        }
                        if (REQUEST_CODE > 0) {
                            activity.startActivityForResult(intent, REQUEST_CODE);
                        } else {
                            activity.startActivity(intent);
                        }
                    }
                });

        dialog.setButton(AlertDialog.BUTTON_NEGATIVE,
                activity.getResources().getString(R.string.add_contact_dialog_new),
                new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        final Intent intent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI);
                        if (Mms.isEmailAddress(numberOrEmail)) {
                            intent.putExtra(ContactsContract.Intents.Insert.EMAIL, numberOrEmail);
                        } else {
                            intent.putExtra(ContactsContract.Intents.Insert.PHONE, numberOrEmail);
                        }
                        if (REQUEST_CODE > 0) {
                            activity.startActivityForResult(intent, REQUEST_CODE);
                        } else {
                            activity.startActivity(intent);
                        }
                    }
                });
        dialog.show();
    }
}

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

/**
 * Check if the permissions provided in the list are granted.
 * This is an asynchronous method if permissions are requested, the final response
 * is provided in onRequestPermissionsResult(). In this case checkPermissions()
 * returns false./*from  w w w  .j  ava 2s.  com*/
 * <br>If checkPermissions() returns true, the permissions were already granted.
 * The permissions to be granted are given as bit map in aPermissionsToBeGrantedBitMap (ex: {@link #REQUEST_CODE_PERMISSION_TAKE_PHOTO}).
 * <br>aPermissionsToBeGrantedBitMap is passed as the request code in onRequestPermissionsResult().
 * <p>
 * If a permission was already denied by the user, a popup is displayed to
 * explain why vector needs the corresponding permission.
 *
 * @param aPermissionsToBeGrantedBitMap the permissions bit map to be granted
 * @param aCallingActivity              the calling Activity that is requesting the permissions
 * @return true if the permissions are granted (synchronous flow), false otherwise (asynchronous flow)
 */
public static boolean checkPermissions(final int aPermissionsToBeGrantedBitMap,
        final Activity aCallingActivity) {
    boolean isPermissionGranted = false;

    // sanity check
    if (null == aCallingActivity) {
        Log.w(LOG_TAG, "## checkPermissions(): invalid input data");
        isPermissionGranted = false;
    } else if (REQUEST_CODE_PERMISSION_BY_PASS == aPermissionsToBeGrantedBitMap) {
        isPermissionGranted = true;
    } else if ((REQUEST_CODE_PERMISSION_TAKE_PHOTO != aPermissionsToBeGrantedBitMap)
            && (REQUEST_CODE_PERMISSION_AUDIO_IP_CALL != aPermissionsToBeGrantedBitMap)
            && (REQUEST_CODE_PERMISSION_VIDEO_IP_CALL != aPermissionsToBeGrantedBitMap)
            && (REQUEST_CODE_PERMISSION_MEMBERS_SEARCH != aPermissionsToBeGrantedBitMap)
            && (REQUEST_CODE_PERMISSION_HOME_ACTIVITY != aPermissionsToBeGrantedBitMap)
            && (REQUEST_CODE_PERMISSION_MEMBER_DETAILS != aPermissionsToBeGrantedBitMap)
            && (REQUEST_CODE_PERMISSION_ROOM_DETAILS != aPermissionsToBeGrantedBitMap)) {
        Log.w(LOG_TAG, "## checkPermissions(): permissions to be granted are not supported");
        isPermissionGranted = false;
    } else {
        List<String> permissionListAlreadyDenied = new ArrayList<>();
        List<String> permissionsListToBeGranted = new ArrayList<>();
        final List<String> finalPermissionsListToBeGranted;
        boolean isRequestPermissionRequired = false;
        Resources resource = aCallingActivity.getResources();
        String explanationMessage = "";
        String permissionType;

        // retrieve the permissions to be granted according to the request code bit map
        if (PERMISSION_CAMERA == (aPermissionsToBeGrantedBitMap & PERMISSION_CAMERA)) {
            permissionType = Manifest.permission.CAMERA;
            isRequestPermissionRequired |= updatePermissionsToBeGranted(aCallingActivity,
                    permissionListAlreadyDenied, permissionsListToBeGranted, permissionType);
        }

        if (PERMISSION_RECORD_AUDIO == (aPermissionsToBeGrantedBitMap & PERMISSION_RECORD_AUDIO)) {
            permissionType = Manifest.permission.RECORD_AUDIO;
            isRequestPermissionRequired |= updatePermissionsToBeGranted(aCallingActivity,
                    permissionListAlreadyDenied, permissionsListToBeGranted, permissionType);
        }

        if (PERMISSION_WRITE_EXTERNAL_STORAGE == (aPermissionsToBeGrantedBitMap
                & PERMISSION_WRITE_EXTERNAL_STORAGE)) {
            permissionType = Manifest.permission.WRITE_EXTERNAL_STORAGE;
            isRequestPermissionRequired |= updatePermissionsToBeGranted(aCallingActivity,
                    permissionListAlreadyDenied, permissionsListToBeGranted, permissionType);
        }

        // the contact book access is requested for any android platforms
        // for android M, we use the system preferences
        // for android < M, we use a dedicated settings
        if (PERMISSION_READ_CONTACTS == (aPermissionsToBeGrantedBitMap & PERMISSION_READ_CONTACTS)) {
            permissionType = Manifest.permission.READ_CONTACTS;

            if (Build.VERSION.SDK_INT >= 23) {
                isRequestPermissionRequired |= updatePermissionsToBeGranted(aCallingActivity,
                        permissionListAlreadyDenied, permissionsListToBeGranted, permissionType);
            } else {
                if (!ContactsManager.getInstance().isContactBookAccessRequested()) {
                    isRequestPermissionRequired = true;
                    permissionsListToBeGranted.add(permissionType);
                }
            }
        }

        finalPermissionsListToBeGranted = permissionsListToBeGranted;

        // if some permissions were already denied: display a dialog to the user before asking again..
        // if some permissions were already denied: display a dialog to the user before asking again..
        if (!permissionListAlreadyDenied.isEmpty()) {
            if (null != resource) {
                // add the user info text to be displayed to explain why the permission is required by the App
                if (aPermissionsToBeGrantedBitMap == REQUEST_CODE_PERMISSION_VIDEO_IP_CALL
                        || aPermissionsToBeGrantedBitMap == REQUEST_CODE_PERMISSION_AUDIO_IP_CALL) {
                    // Permission request for VOIP call
                    if (permissionListAlreadyDenied.contains(Manifest.permission.CAMERA)
                            && permissionListAlreadyDenied.contains(Manifest.permission.RECORD_AUDIO)) {
                        // Both missing
                        explanationMessage += resource
                                .getString(R.string.permissions_rationale_msg_camera_and_audio);
                    } else if (permissionListAlreadyDenied.contains(Manifest.permission.RECORD_AUDIO)) {
                        // Audio missing
                        explanationMessage += resource
                                .getString(R.string.permissions_rationale_msg_record_audio);
                        explanationMessage += resource
                                .getString(R.string.permissions_rationale_msg_record_audio_explanation);
                    } else if (permissionListAlreadyDenied.contains(Manifest.permission.CAMERA)) {
                        // Camera missing
                        explanationMessage += resource.getString(R.string.permissions_rationale_msg_camera);
                        explanationMessage += resource
                                .getString(R.string.permissions_rationale_msg_camera_explanation);
                    }
                } else {
                    for (String permissionAlreadyDenied : permissionListAlreadyDenied) {
                        if (Manifest.permission.CAMERA.equals(permissionAlreadyDenied)) {
                            if (!TextUtils.isEmpty(explanationMessage)) {
                                explanationMessage += "\n\n";
                            }
                            explanationMessage += resource.getString(R.string.permissions_rationale_msg_camera);
                        } else if (Manifest.permission.RECORD_AUDIO.equals(permissionAlreadyDenied)) {
                            if (!TextUtils.isEmpty(explanationMessage)) {
                                explanationMessage += "\n\n";
                            }
                            explanationMessage += resource
                                    .getString(R.string.permissions_rationale_msg_record_audio);
                        } else if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permissionAlreadyDenied)) {
                            if (!TextUtils.isEmpty(explanationMessage)) {
                                explanationMessage += "\n\n";
                            }
                            explanationMessage += resource
                                    .getString(R.string.permissions_rationale_msg_storage);
                        } else if (Manifest.permission.READ_CONTACTS.equals(permissionAlreadyDenied)) {
                            if (!TextUtils.isEmpty(explanationMessage)) {
                                explanationMessage += "\n\n";
                            }
                            explanationMessage += resource
                                    .getString(R.string.permissions_rationale_msg_contacts);
                        } else {
                            Log.d(LOG_TAG, "## checkPermissions(): already denied permission not supported");
                        }
                    }
                }
            } else { // fall back if resource is null.. very unlikely
                explanationMessage = "You are about to be asked to grant permissions..\n\n";
            }

            // display the dialog with the info text
            AlertDialog.Builder permissionsInfoDialog = new AlertDialog.Builder(aCallingActivity);
            if (null != resource) {
                permissionsInfoDialog.setTitle(resource.getString(R.string.permissions_rationale_popup_title));
            }

            permissionsInfoDialog.setMessage(explanationMessage);
            permissionsInfoDialog.setPositiveButton(aCallingActivity.getString(R.string.ok),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (!finalPermissionsListToBeGranted.isEmpty()) {
                                ActivityCompat.requestPermissions(aCallingActivity,
                                        finalPermissionsListToBeGranted
                                                .toArray(new String[finalPermissionsListToBeGranted.size()]),
                                        aPermissionsToBeGrantedBitMap);
                            }
                        }
                    });

            Dialog dialog = permissionsInfoDialog.show();

            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    CommonActivityUtils.displayToast(aCallingActivity,
                            aCallingActivity.getString(R.string.missing_permissions_warning));
                }
            });

        } else {
            // some permissions are not granted, ask permissions
            if (isRequestPermissionRequired) {
                final String[] fPermissionsArrayToBeGranted = finalPermissionsListToBeGranted
                        .toArray(new String[finalPermissionsListToBeGranted.size()]);

                // for android < M, we use a custom dialog to request the contacts book access.
                if (permissionsListToBeGranted.contains(Manifest.permission.READ_CONTACTS)
                        && (Build.VERSION.SDK_INT < 23)) {
                    AlertDialog.Builder permissionsInfoDialog = new AlertDialog.Builder(aCallingActivity);
                    permissionsInfoDialog.setIcon(android.R.drawable.ic_dialog_info);

                    if (null != resource) {
                        permissionsInfoDialog
                                .setTitle(resource.getString(R.string.permissions_rationale_popup_title));
                    }

                    permissionsInfoDialog.setMessage(
                            resource.getString(R.string.permissions_msg_contacts_warning_other_androids));

                    // gives the contacts book access
                    permissionsInfoDialog.setPositiveButton(aCallingActivity.getString(R.string.yes),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    ContactsManager.getInstance().setIsContactBookAccessAllowed(true);
                                    ActivityCompat.requestPermissions(aCallingActivity,
                                            fPermissionsArrayToBeGranted, aPermissionsToBeGrantedBitMap);
                                }
                            });

                    // or reject it
                    permissionsInfoDialog.setNegativeButton(aCallingActivity.getString(R.string.no),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    ContactsManager.getInstance().setIsContactBookAccessAllowed(false);
                                    ActivityCompat.requestPermissions(aCallingActivity,
                                            fPermissionsArrayToBeGranted, aPermissionsToBeGrantedBitMap);
                                }
                            });

                    permissionsInfoDialog.show();

                } else {
                    ActivityCompat.requestPermissions(aCallingActivity, fPermissionsArrayToBeGranted,
                            aPermissionsToBeGrantedBitMap);
                }
            } else {
                // permissions were granted, start now..
                isPermissionGranted = true;
            }
        }
    }
    return isPermissionGranted;
}

From source file:com.amaze.filemanager.utils.Futils.java

public void showProps(final HFile f, final Activity c, int theme1) {
    String date = null;/*  w  w  w  .java2s.co  m*/
    try {
        date = getdate(f.lastModified());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (SmbException e) {
        e.printStackTrace();
    }
    String items = getString(c, R.string.calculating), size = getString(c, R.string.calculating), name, parent;
    name = f.getName();
    parent = f.getReadablePath(f.getParent());
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(c);
    String fabskin = PreferenceUtils.getAccentString(sp);
    MaterialDialog.Builder a = new MaterialDialog.Builder(c);
    a.title(getString(c, R.string.properties));
    if (theme1 == 1)
        a.theme(Theme.DARK);

    View v = c.getLayoutInflater().inflate(R.layout.properties_dialog, null);
    v.findViewById(R.id.appX).setVisibility(View.GONE);
    a.customView(v, true);
    a.positiveText(R.string.copy_path);
    a.negativeText(getString(c, R.string.md5_2));
    a.positiveColor(Color.parseColor(fabskin));
    a.negativeColor(Color.parseColor(fabskin));
    a.neutralText(R.string.cancel);
    a.neutralColor(Color.parseColor(fabskin));
    a.callback(new MaterialDialog.ButtonCallback() {
        @Override
        public void onPositive(MaterialDialog materialDialog) {
            copyToClipboard(c, f.getPath());
            Toast.makeText(c, c.getResources().getString(R.string.pathcopied), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNegative(MaterialDialog materialDialog) {
        }
    });
    MaterialDialog materialDialog = a.build();
    materialDialog.show();
    new GenerateMD5Task(materialDialog, (f), name, parent, size, items, date, c, v).execute(f.getPath());
}

From source file:com.clanofthecloud.cotcpushnotifications.MyGcmListenerService.java

/**
 * Create and show a simple notification containing the received GCM message.
 *
 * @param message GCM message received.//from  w w  w .ja v  a  2 s.  c  om
 */
private void sendNotification(String message) {
    Activity currentAct = UnityPlayer.currentActivity;
    Class activityToOpen = currentAct != null ? currentAct.getClass() : UnityPlayerActivity.class;
    Intent intent = new Intent(this, activityToOpen);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    ApplicationInfo ai = null;
    try {
        ai = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
        int notificationIcon = ai.metaData.getInt("cotc.GcmNotificationIcon", -1);
        if (notificationIcon == -1) {
            Log.e(TAG,
                    "!!!!!!!!! cotc.GcmNotificationIcon not configured in manifest, push notifications won't work !!!!!!!!!");
            return;
        }
        int notificationLargeIcon = ai.metaData.getInt("cotc.GcmNotificationLargeIcon", -1);
        if (notificationLargeIcon == -1) {
            Log.e(TAG, "There is no large icon for push notifs, will only use default icon");
            return;
        }

        String pushNotifName = ai.metaData.getString("cotc.GcmNotificationTitle");
        if (pushNotifName == null) {
            Log.e(TAG,
                    "!!!!!!!!! cotc.GcmNotificationTitle not configured in manifest, push notifications won't work !!!!!!!!!");
            return;
        }

        if (notifManager == null)
            notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder notificationBuilder;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel channel = new NotificationChannel("CotC Channel", "CotC Channel", importance);
            channel.setDescription("CotC Channel");
            notifManager.createNotificationChannel(channel);
            notificationBuilder = new NotificationCompat.Builder(this, "CotC Channel");
        } else
            notificationBuilder = new NotificationCompat.Builder(this);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        notificationBuilder.setSmallIcon(notificationIcon).setContentTitle(pushNotifName)
                .setContentText(message).setAutoCancel(true).setSound(defaultSoundUri)
                .setContentIntent(pendingIntent).setPriority(Notification.PRIORITY_HIGH);
        if (notificationLargeIcon != -1)
            notificationBuilder.setLargeIcon(
                    BitmapFactory.decodeResource(currentAct.getResources(), notificationLargeIcon));

        notifManager.notify(0 /* ID of notification */, notificationBuilder.build());
    } catch (Exception e) {
        Log.w(TAG, "Failed to handle push notification", e);
    }
}

From source file:org.chromium.chrome.browser.payments.PaymentRequestImpl.java

private void buildUI(Activity activity) {
    assert activity != null;

    List<AutofillProfile> profiles = null;
    if (mRequestShipping || mRequestPayerName || mRequestPayerPhone || mRequestPayerEmail) {
        profiles = PersonalDataManager.getInstance().getProfilesToSuggest(false /* includeNameInLabel */);
    }//from www .j  av a  2  s  . com

    if (mRequestShipping) {
        createShippingSection(activity, Collections.unmodifiableList(profiles));
    }

    if (mRequestPayerName || mRequestPayerPhone || mRequestPayerEmail) {
        mContactEditor = new ContactEditor(mRequestPayerName, mRequestPayerPhone, mRequestPayerEmail);
        mContactSection = new ContactDetailsSection(activity, Collections.unmodifiableList(profiles),
                mContactEditor);
    }

    setIsAnyPaymentRequestShowing(true);
    mUI = new PaymentRequestUI(activity, this, mRequestShipping,
            mRequestPayerName || mRequestPayerPhone || mRequestPayerEmail,
            mMerchantSupportsAutofillPaymentInstruments, !PaymentPreferencesUtil.isPaymentCompleteOnce(),
            mMerchantName, mOrigin, new ShippingStrings(mShippingType));

    final FaviconHelper faviconHelper = new FaviconHelper();
    faviconHelper.getLocalFaviconImageForURL(Profile.getLastUsedProfile(), mWebContents.getLastCommittedUrl(),
            activity.getResources().getDimensionPixelSize(R.dimen.payments_favicon_size),
            new FaviconHelper.FaviconImageCallback() {
                @Override
                public void onFaviconAvailable(Bitmap bitmap, String iconUrl) {
                    if (bitmap != null)
                        mUI.setTitleBitmap(bitmap);
                    faviconHelper.destroy();
                }
            });

    // Add the callback to change the label of shipping addresses depending on the focus.
    if (mRequestShipping)
        mUI.setShippingAddressSectionFocusChangedObserver(this);

    mAddressEditor.setEditorView(mUI.getEditorView());
    mCardEditor.setEditorView(mUI.getCardEditorView());
    if (mContactEditor != null)
        mContactEditor.setEditorView(mUI.getEditorView());
}

From source file:com.apptentive.android.sdk.module.messagecenter.ApptentiveMessageCenter.java

static void showIntroDialog(final Activity activity, boolean emailRequired) {
    final MessageCenterIntroDialog dialog = new MessageCenterIntroDialog(activity);
    dialog.setEmailRequired(emailRequired);

    String personEnteredEmail = PersonManager.loadPersonEmail(activity);
    String personInitialEmail = PersonManager.loadInitialPersonEmail(activity);
    if (Util.isEmpty(personEnteredEmail)) {
        if (!Util.isEmpty(personInitialEmail)) {
            dialog.setEmailFieldHidden(false);
            dialog.prePopulateEmail(personInitialEmail);
        }//from www .  ja va  2 s .co  m
    } else {
        dialog.setEmailFieldHidden(true);
    }
    dialog.setCanceledOnTouchOutside(false);

    dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialogInterface) {
            MetricModule.sendMetric(activity, Event.EventLabel.message_center__intro__cancel);
            dialog.dismiss();
        }
    });

    dialog.setOnSendListener(new MessageCenterIntroDialog.OnSendListener() {
        @Override
        public void onSend(String email, String message) {
            SharedPreferences prefs = activity.getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE);
            prefs.edit().putBoolean(Constants.PREF_KEY_MESSAGE_CENTER_SHOULD_SHOW_INTRO_DIALOG, false).commit();
            // Save the email.
            if (dialog.isEmailFieldVisible()) {
                if (email != null && email.length() != 0) {
                    PersonManager.storePersonEmail(activity, email);
                    Person person = PersonManager.storePersonAndReturnDiff(activity);
                    if (person != null) {
                        Log.d("Person was updated.");
                        Log.v(person.toString());
                        ApptentiveDatabase.getInstance(activity).addPayload(person);
                    } else {
                        Log.d("Person was not updated.");
                    }
                }
            }
            // Send the message.
            final TextMessage textMessage = new TextMessage();
            textMessage.setBody(message);
            textMessage.setRead(true);
            textMessage.setCustomData(customData);
            customData = null;
            MessageManager.sendMessage(activity, textMessage);
            MetricModule.sendMetric(activity, Event.EventLabel.message_center__intro__send);
            dialog.dismiss();

            final MessageCenterThankYouDialog messageCenterThankYouDialog = new MessageCenterThankYouDialog(
                    activity);
            messageCenterThankYouDialog.setValidEmailProvided(email != null && Util.isEmailValid(email));
            messageCenterThankYouDialog
                    .setOnChoiceMadeListener(new MessageCenterThankYouDialog.OnChoiceMadeListener() {
                        @Override
                        public void onNo() {
                            MetricModule.sendMetric(activity,
                                    Event.EventLabel.message_center__thank_you__close);
                        }

                        @Override
                        public void onYes() {
                            MetricModule.sendMetric(activity,
                                    Event.EventLabel.message_center__thank_you__messages);
                            show(activity);
                        }
                    });
            MetricModule.sendMetric(activity, Event.EventLabel.message_center__thank_you__launch);
            messageCenterThankYouDialog.show();
        }
    });

    String appDisplayName = Configuration.load(activity).getAppDisplayName();
    switch (trigger) {
    case enjoyment_dialog:
        dialog.setTitle(R.string.apptentive_intro_dialog_title_no_love);
        dialog.setBody(
                activity.getResources().getString(R.string.apptentive_intro_dialog_body, appDisplayName));
        break;
    case message_center:
        dialog.setTitle(R.string.apptentive_intro_dialog_title_default);
        dialog.setBody(
                activity.getResources().getString(R.string.apptentive_intro_dialog_body, appDisplayName));
        break;
    default:
        return;
    }
    MetricModule.sendMetric(activity, Event.EventLabel.message_center__intro__launch, trigger.name());
    dialog.show();
}

From source file:org.brandroid.openmanager.activities.OpenExplorer.java

@SuppressWarnings("deprecation")
public static void launchTranslator(Activity a) {
    new Preferences(a).setSetting("warn", "translate", true);
    String lang = DialogHandler.getLangCode();
    Uri uri = Uri.parse("http://brandroid.org/translation_helper.php?lang=" + lang + "&full="
            + Locale.getDefault().getDisplayLanguage() + "&wid="
            + a.getWindowManager().getDefaultDisplay().getWidth());
    //Intent intent = new Intent(a, WebViewActivity.class);
    //intent.setData();
    //a.startActivity(intent);
    WebViewFragment web = new WebViewFragment().setUri(uri);
    if (Build.VERSION.SDK_INT < 100) {
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        a.startActivity(intent);/*  w w  w.j  ava 2  s.c o  m*/
    } else if (a.findViewById(R.id.frag_log) != null) {
        ((FragmentActivity) a).getSupportFragmentManager().beginTransaction().replace(R.id.frag_log, web)
                .addToBackStack("trans").commit();
        a.findViewById(R.id.frag_log).setVisibility(View.VISIBLE);
        LayoutParams lp = a.findViewById(R.id.frag_log).getLayoutParams();
        lp.width = a.getResources().getDimensionPixelSize(R.dimen.bookmarks_width) * 2;
        a.findViewById(R.id.frag_log).setLayoutParams(lp);
    } else {
        web.setShowsDialog(true);
        web.show(((FragmentActivity) a).getSupportFragmentManager(), "trans");
        if (web.getDialog() != null)
            web.getDialog().setTitle(R.string.button_translate);
        web.setUri(uri);
    }
}

From source file:com.nttec.everychan.http.recaptcha.Recaptcha2fallback.java

@Override
public void handle(final Activity activity, final CancellableTask task, final Callback callback) {
    try {//from   ww  w. j ava  2s.co m
        final HttpClient httpClient = ((HttpChanModule) MainApplication.getInstance().getChanModule(chanName))
                .getHttpClient();
        final String usingURL = scheme + RECAPTCHA_FALLBACK_URL + publicKey
                + (sToken != null && sToken.length() > 0 ? ("&stoken=" + sToken) : "");
        String refererURL = baseUrl != null && baseUrl.length() > 0 ? baseUrl : usingURL;
        Header[] customHeaders = new Header[] { new BasicHeader(HttpHeaders.REFERER, refererURL) };
        String htmlChallenge;
        if (lastChallenge != null && lastChallenge.getLeft().equals(usingURL)) {
            htmlChallenge = lastChallenge.getRight();
        } else {
            htmlChallenge = HttpStreamer.getInstance().getStringFromUrl(usingURL,
                    HttpRequestModel.builder().setGET().setCustomHeaders(customHeaders).build(), httpClient,
                    null, task, false);
        }
        lastChallenge = null;

        Matcher challengeMatcher = Pattern.compile("name=\"c\" value=\"([\\w-]+)").matcher(htmlChallenge);
        if (challengeMatcher.find()) {
            final String challenge = challengeMatcher.group(1);
            HttpResponseModel responseModel = HttpStreamer.getInstance().getFromUrl(
                    scheme + RECAPTCHA_IMAGE_URL + challenge + "&k=" + publicKey,
                    HttpRequestModel.builder().setGET().setCustomHeaders(customHeaders).build(), httpClient,
                    null, task);
            try {
                InputStream imageStream = responseModel.stream;
                final Bitmap challengeBitmap = BitmapFactory.decodeStream(imageStream);

                final String message;
                Matcher messageMatcher = Pattern.compile("imageselect-message(?:.*?)>(.*?)</div>")
                        .matcher(htmlChallenge);
                if (messageMatcher.find())
                    message = RegexUtils.removeHtmlTags(messageMatcher.group(1));
                else
                    message = null;

                final Bitmap candidateBitmap;
                Matcher candidateMatcher = Pattern
                        .compile("fbc-imageselect-candidates(?:.*?)src=\"data:image/(?:.*?);base64,([^\"]*)\"")
                        .matcher(htmlChallenge);
                if (candidateMatcher.find()) {
                    Bitmap bmp = null;
                    try {
                        byte[] imgData = Base64.decode(candidateMatcher.group(1), Base64.DEFAULT);
                        bmp = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
                    } catch (Exception e) {
                    }
                    candidateBitmap = bmp;
                } else
                    candidateBitmap = null;

                activity.runOnUiThread(new Runnable() {
                    final int maxX = 3;
                    final int maxY = 3;
                    final boolean[] isSelected = new boolean[maxX * maxY];

                    @SuppressLint("InlinedApi")
                    @Override
                    public void run() {
                        LinearLayout rootLayout = new LinearLayout(activity);
                        rootLayout.setOrientation(LinearLayout.VERTICAL);

                        if (candidateBitmap != null) {
                            ImageView candidateView = new ImageView(activity);
                            candidateView.setImageBitmap(candidateBitmap);
                            int picSize = (int) (activity.getResources().getDisplayMetrics().density * 50
                                    + 0.5f);
                            candidateView.setLayoutParams(new LinearLayout.LayoutParams(picSize, picSize));
                            candidateView.setScaleType(ImageView.ScaleType.FIT_XY);
                            rootLayout.addView(candidateView);
                        }

                        if (message != null) {
                            TextView textView = new TextView(activity);
                            textView.setText(message);
                            CompatibilityUtils.setTextAppearance(textView, android.R.style.TextAppearance);
                            textView.setLayoutParams(
                                    new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                            LinearLayout.LayoutParams.WRAP_CONTENT));
                            rootLayout.addView(textView);
                        }

                        FrameLayout frame = new FrameLayout(activity);
                        frame.setLayoutParams(
                                new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                        LinearLayout.LayoutParams.WRAP_CONTENT));

                        final ImageView imageView = new ImageView(activity);
                        imageView.setLayoutParams(new FrameLayout.LayoutParams(
                                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
                        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        imageView.setImageBitmap(challengeBitmap);
                        frame.addView(imageView);

                        final LinearLayout selector = new LinearLayout(activity);
                        selector.setLayoutParams(new FrameLayout.LayoutParams(
                                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
                        AppearanceUtils.callWhenLoaded(imageView, new Runnable() {
                            @Override
                            public void run() {
                                selector.setLayoutParams(new FrameLayout.LayoutParams(imageView.getWidth(),
                                        imageView.getHeight()));
                            }
                        });
                        selector.setOrientation(LinearLayout.VERTICAL);
                        selector.setWeightSum(maxY);
                        for (int y = 0; y < maxY; ++y) {
                            LinearLayout subSelector = new LinearLayout(activity);
                            subSelector.setLayoutParams(new LinearLayout.LayoutParams(
                                    LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f));
                            subSelector.setOrientation(LinearLayout.HORIZONTAL);
                            subSelector.setWeightSum(maxX);
                            for (int x = 0; x < maxX; ++x) {
                                FrameLayout switcher = new FrameLayout(activity);
                                switcher.setLayoutParams(new LinearLayout.LayoutParams(0,
                                        LinearLayout.LayoutParams.MATCH_PARENT, 1f));
                                switcher.setTag(new int[] { x, y });
                                switcher.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        int[] coord = (int[]) v.getTag();
                                        int index = coord[1] * maxX + coord[0];
                                        isSelected[index] = !isSelected[index];
                                        v.setBackgroundColor(isSelected[index] ? Color.argb(128, 0, 255, 0)
                                                : Color.TRANSPARENT);
                                    }
                                });
                                subSelector.addView(switcher);
                            }
                            selector.addView(subSelector);
                        }

                        frame.addView(selector);
                        rootLayout.addView(frame);

                        Button checkButton = new Button(activity);
                        checkButton.setLayoutParams(
                                new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                        LinearLayout.LayoutParams.WRAP_CONTENT));
                        checkButton.setText(android.R.string.ok);
                        rootLayout.addView(checkButton);

                        ScrollView dlgView = new ScrollView(activity);
                        dlgView.addView(rootLayout);

                        final Dialog dialog = new Dialog(activity);
                        dialog.setTitle("Recaptcha");
                        dialog.setContentView(dlgView);
                        dialog.setCanceledOnTouchOutside(false);
                        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                if (!task.isCancelled()) {
                                    callback.onError("Cancelled");
                                }
                            }
                        });
                        dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
                                ViewGroup.LayoutParams.WRAP_CONTENT);
                        dialog.show();

                        checkButton.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                if (task.isCancelled())
                                    return;
                                Async.runAsync(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                                            pairs.add(new BasicNameValuePair("c", challenge));
                                            for (int i = 0; i < isSelected.length; ++i)
                                                if (isSelected[i])
                                                    pairs.add(new BasicNameValuePair("response",
                                                            Integer.toString(i)));

                                            HttpRequestModel request = HttpRequestModel.builder()
                                                    .setPOST(new UrlEncodedFormEntity(pairs, "UTF-8"))
                                                    .setCustomHeaders(new Header[] {
                                                            new BasicHeader(HttpHeaders.REFERER, usingURL) })
                                                    .build();
                                            String response = HttpStreamer.getInstance().getStringFromUrl(
                                                    usingURL, request, httpClient, null, task, false);
                                            String hash = "";
                                            Matcher matcher = Pattern.compile(
                                                    "fbc-verification-token(?:.*?)<textarea[^>]*>([^<]*)<",
                                                    Pattern.DOTALL).matcher(response);
                                            if (matcher.find())
                                                hash = matcher.group(1);

                                            if (hash.length() > 0) {
                                                Recaptcha2solved.push(publicKey, hash);
                                                activity.runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        callback.onSuccess();
                                                    }
                                                });
                                            } else {
                                                lastChallenge = Pair.of(usingURL, response);
                                                throw new RecaptchaException(
                                                        "incorrect answer (hash is empty)");
                                            }
                                        } catch (final Exception e) {
                                            Logger.e(TAG, e);
                                            if (task.isCancelled())
                                                return;
                                            handle(activity, task, callback);
                                        }
                                    }
                                });
                            }
                        });
                    }
                });
            } finally {
                responseModel.release();
            }
        } else
            throw new Exception("can't parse recaptcha challenge answer");
    } catch (final Exception e) {
        Logger.e(TAG, e);
        if (!task.isCancelled()) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    callback.onError(e.getMessage() != null ? e.getMessage() : e.toString());
                }
            });
        }
    }
}

From source file:com.xperia64.timidityae.Globals.java

public static boolean initialize(final Activity a) {
    if (firstRun) {
        final File rootStorage = new File(
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/TimidityAE/");
        if (!rootStorage.exists()) {
            rootStorage.mkdir();/*from   ww  w  .j a  v a  2  s .co  m*/
        }
        File playlistDir = new File(rootStorage.getAbsolutePath() + "/playlists/");
        if (!playlistDir.exists()) {
            playlistDir.mkdir();
        }
        File tcfgDir = new File(rootStorage.getAbsolutePath() + "/timidity/");
        if (!tcfgDir.exists()) {
            tcfgDir.mkdir();
        }
        File sfDir = new File(rootStorage.getAbsolutePath() + "/soundfonts/");
        if (!sfDir.exists()) {
            sfDir.mkdir();
        }
        updateBuffers(updateRates());
        aRate = Integer.parseInt(prefs.getString("tplusRate",
                Integer.toString(AudioTrack.getNativeOutputSampleRate(AudioTrack.MODE_STREAM))));
        buff = Integer.parseInt(prefs.getString("tplusBuff", "192000")); // This is usually a safe number, but should probably do a test or something
        migrateFrom1X(rootStorage);
        final Editor eee = prefs.edit();
        firstRun = false;
        eee.putBoolean("tplusFirstRun", false);
        eee.putString("dataDir", Environment.getExternalStorageDirectory().getAbsolutePath() + "/TimidityAE/");
        if (new File(dataFolder + "/timidity/timidity.cfg").exists()) {
            if (manConfig = !cfgIsAuto(dataFolder + "/timidity/timidity.cfg")) {
                eee.putBoolean("manConfig", true);
            } else {
                eee.putBoolean("manConfig", false);
                ArrayList<String> soundfonts = new ArrayList<String>();
                FileInputStream fstream = null;
                try {
                    fstream = new FileInputStream(dataFolder + "/timidity/timidity.cfg");
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                // Get the object of DataInputStream
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                //Read File Line By Line
                try {
                    br.readLine(); // skip first line
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String line;
                try {
                    while ((line = br.readLine()) != null) {
                        if (line.indexOf("soundfont \"") >= 0 && line.lastIndexOf('"') >= 0) {
                            try {
                                String st = line.substring(line.indexOf("soundfont \"") + 11,
                                        line.lastIndexOf('"'));
                                soundfonts.add(st);
                            } catch (ArrayIndexOutOfBoundsException e1) {
                                e1.printStackTrace();
                            }

                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    eee.putString("tplusSoundfonts", ObjectSerializer.serialize(soundfonts));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            eee.commit();
            return true;
        } else {
            // Should probably check if 8rock11e exists no matter what
            eee.putBoolean("manConfig", false);

            AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {

                ProgressDialog pd;

                @Override
                protected void onPreExecute() {
                    pd = new ProgressDialog(a);
                    pd.setTitle(a.getResources().getString(R.string.extract));
                    pd.setMessage(a.getResources().getString(R.string.extract_sum));
                    pd.setCancelable(false);
                    pd.setIndeterminate(true);
                    pd.show();
                }

                @Override
                protected Void doInBackground(Void... arg0) {

                    if (extract8Rock(a) != 777) {
                        Toast.makeText(a, "Could not extrct default soundfont", Toast.LENGTH_SHORT).show();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(Void result) {
                    if (pd != null)
                        pd.dismiss();
                    ArrayList<String> tmpConfig = new ArrayList<String>();
                    tmpConfig.add(rootStorage.getAbsolutePath() + "/soundfonts/8Rock11e.sf2");
                    try {
                        eee.putString("tplusSoundfonts", ObjectSerializer.serialize(tmpConfig));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    eee.commit();
                    writeCfg(a, rootStorage.getAbsolutePath() + "/timidity/timidity.cfg", tmpConfig);
                    ((TimidityActivity) a).initCallback();
                }

            };
            task.execute((Void[]) null);
            return false;
        }

    } else {
        return true;
    }
}