Example usage for android.app ProgressDialog setCanceledOnTouchOutside

List of usage examples for android.app ProgressDialog setCanceledOnTouchOutside

Introduction

In this page you can find the example usage for android.app ProgressDialog setCanceledOnTouchOutside.

Prototype

public void setCanceledOnTouchOutside(boolean cancel) 

Source Link

Document

Sets whether this dialog is canceled when touched outside the window's bounds.

Usage

From source file:com.yeldi.yeldibazaar.AppDetails.java

private ProgressDialog createProgressDialog(String file, int p, int max) {
    final ProgressDialog pd = new ProgressDialog(this);
    pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    pd.setMessage(getString(R.string.download_server) + ":\n " + file);
    pd.setMax(max);/*from   w  w w.  j  a  v  a  2 s  . co m*/
    pd.setProgress(p);
    pd.setCancelable(true);
    pd.setCanceledOnTouchOutside(false);
    pd.setOnCancelListener(new DialogInterface.OnCancelListener() {
        public void onCancel(DialogInterface dialog) {
            downloadHandler.cancel();
        }
    });
    pd.setButton(DialogInterface.BUTTON_NEUTRAL, getString(R.string.cancel),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    pd.cancel();
                }
            });
    pd.show();
    return pd;
}

From source file:com.nttec.everychan.chans.ponyach.PonyachModule.java

@Override
public void addPreferencesOnScreen(PreferenceGroup preferenceGroup) {
    final Context context = preferenceGroup.getContext();
    ListPreference captchaLevel = new LazyPreferences.ListPreference(context);
    captchaLevel.setTitle(R.string.ponyach_prefs_captcha);
    captchaLevel.setDialogTitle(R.string.ponyach_prefs_captcha);
    captchaLevel.setKey(getSharedKey(PREF_KEY_CAPTCHA_LEVEL));
    captchaLevel.setEntryValues(new String[] { "3", "2", "1" });
    captchaLevel.setEntries(new String[] { "Easy", "Easy++", "Medium" });
    captchaLevel.setDefaultValue("1");
    preferenceGroup.addPreference(captchaLevel);

    EditTextPreference passcodePref = new EditTextPreference(context);
    passcodePref.setTitle(R.string.ponyach_prefs_passcode);
    passcodePref.setDialogTitle(R.string.ponyach_prefs_passcode);
    passcodePref.getEditText().setFilters(new InputFilter[] { new InputFilter.LengthFilter(6) });
    passcodePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override//w w  w .  j  a va 2 s  . c om
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            final String newPasscode = (String) newValue;
            final CancellableTask passAuthTask = new CancellableTask.BaseCancellableTask();
            final ProgressDialog passAuthProgressDialog = new ProgressDialog(context);
            passAuthProgressDialog.setMessage("Logging in");
            passAuthProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    passAuthTask.cancel();
                }
            });
            passAuthProgressDialog.setCanceledOnTouchOutside(false);
            passAuthProgressDialog.show();
            Async.runAsync(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (passAuthTask.isCancelled())
                            return;
                        String url = getUsingUrl() + "passcode.php";
                        List<BasicNameValuePair> pairs = Collections
                                .singletonList(new BasicNameValuePair("passcode_just_set", newPasscode));
                        HttpRequestModel request = HttpRequestModel.builder()
                                .setPOST(new UrlEncodedFormEntity(pairs, "UTF-8")).build();
                        HttpStreamer.getInstance().getStringFromUrl(url, request, httpClient, null,
                                passAuthTask, false);
                        savePhpCookies();
                    } catch (final Exception e) {
                        if (context instanceof Activity) {
                            ((Activity) context).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    String message = e.getMessage() == null
                                            ? resources.getString(R.string.error_unknown)
                                            : e.getMessage();
                                    Toast.makeText(context, message, Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    } finally {
                        passAuthProgressDialog.dismiss();
                    }
                }
            });
            return false;
        }
    });
    preferenceGroup.addPreference(passcodePref);

    ListPreference domainPref = new LazyPreferences.ListPreference(context);
    domainPref.setTitle(R.string.pref_domain);
    domainPref.setDialogTitle(R.string.pref_domain);
    domainPref.setKey(getSharedKey(PREF_KEY_DOMAIN));
    domainPref.setEntryValues(DOMAINS);
    domainPref.setEntries(DOMAINS);
    domainPref.setDefaultValue(DEFAULT_DOMAIN);
    domainPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            loadPhpCookies((String) newValue);
            return true;
        }
    });
    preferenceGroup.addPreference(domainPref);

    addHttpsPreference(preferenceGroup, useHttpsDefaultValue());
    addProxyPreferences(preferenceGroup);
    captchaLevel.setSummary(captchaLevel.getEntry());
    domainPref.setSummary(domainPref.getEntry());
}

From source file:com.zhenlaidian.ui.InputCarNumberActivity.java

public void createOrderForPos() throws UnsupportedEncodingException {
    if (System.currentTimeMillis() - currentM > 1000) {
        SharedPreferences pfs = this.getSharedPreferences("autologin", Context.MODE_PRIVATE);
        uid = pfs.getString("account", "");
        final String carnumber = URLEncoder.encode(getStringFromPreference("carnumber"), "utf-8");
        String url = BaseActivity.baseurl + "collectorrequest.do?action=posincome&token=" + BaseActivity.token
                + "&carnumber=" + URLEncoder.encode(carnumber, "utf-8") + "&bid="
                + getStringFromPreference("bowei") + "&berthid="
                + SharedPreferencesUtils.getIntance(this).getberthid() + "&workid="
                + SharedPreferencesUtils.getIntance(this).getworkid() + "&prepay=0&ismonthuser=" + ismonthuser
                + "&berthorderid=" + getStringFromPreference("berthorderid") + "&orderid="
                + getStringFromPreference("preorderid") + "&car_type=" + cartypecode;
        MyLog.w("InCarDialogActivity", "??URL--->" + url);
        final ProgressDialog dialog = ProgressDialog.show(this, "??", "????...",
                true, true);/* w  ww. j a  va  2  s . c om*/
        dialog.setCanceledOnTouchOutside(false);
        AQuery aQuery = new AQuery(this);
        aQuery.ajax(url, String.class, new AjaxCallback<String>() {

            @Override
            public void callback(String url, String object, AjaxStatus status) {
                if (status.getCode() == 200 && object != null) {
                    dialog.dismiss();
                    MyLog.i("InCarDialogActivity", "??--->" + object);
                    Gson gson = new Gson();
                    InCarDialogInfo info = gson.fromJson(object, InCarDialogInfo.class);
                    infos = info;
                    if (info != null) {
                        MyLog.d("InCarDialogActivity", info.toString());
                        if ("1".equals(info.getResult())) {
                            //?????
                            putStringToPreference("berthorderid", "");
                            putBooleanToPreference("next", false);
                            voice = new VoiceSynthesizerUtil(context);
                            voice.playText("??");
                            bt_ok.setOnClickListener(null);
                            //                                if (CommontUtils.checkList(files)) {
                            //                                    for (int i = 0; i < files.size(); i++) {
                            //                                        String SDState = Environment.getExternalStorageState();
                            //                                        if (SDState.equals(Environment.MEDIA_MOUNTED)) {
                            //                                            File dir = new File(Environment.getExternalStorageDirectory() + "/TingCheBao");
                            //                                            if (!dir.exists()) {
                            //                                                dir.mkdirs();
                            //                                            }
                            //                                            files.get(i).renameTo(new File(dir.getAbsolutePath(), info.getOrderid() + "in" + i + ".jpeg"));
                            //                                            CameraBitmapUtil.upload(context, i, info.getOrderid(), 0);
                            //                                        }
                            //                                    }
                            //                                }
                            if (CommontUtils.checkList(listPath)) {
                                for (int i = 0; i < listPath.size(); i++) {
                                    String SDState = Environment.getExternalStorageState();
                                    if (SDState.equals(Environment.MEDIA_MOUNTED)) {
                                        File dir = new File(
                                                Environment.getExternalStorageDirectory() + "/TingCheBao");
                                        if (!dir.exists()) {
                                            dir.mkdirs();
                                        }
                                        (new File(listPath.get(i))).renameTo(new File(dir.getAbsolutePath(),
                                                info.getOrderid() + "in" + i + ".jpeg"));
                                        CameraBitmapUtil.upload(context, i, info.getOrderid(), 0);
                                    }
                                }
                            }
                            if (PullMsgService.CanPrint) {
                                //                                if (mService.getState() != BluetoothService.STATE_CONNECTED) {
                                //                                    conn2bluetooth2();
                                //                                } else {
                                prient(uid, info);
                                //                                }
                            } else {
                                FinishAction();
                            }

                            //                            if (parkPositionListener != null && !SharedPreferencesUtils.getIntance(InCarDialogActivity.this).getSelectParkPosition()) {
                            //                                parkPositionListener.doSelectParkPosition(tv_add_carnumber.getText().toString(), info.getOrderid());
                            //                            }
                            //                            InCarDialogActivity.this.finish();
                        } else {
                            Toast.makeText(context, info.getErrmsg(), Toast.LENGTH_SHORT).show();
                        }
                    }
                } else {
                    dialog.dismiss();
                    switch (status.getCode()) {
                    case -101:
                        Toast.makeText(context, "?--????",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case 500:
                        Toast.makeText(context, "??--????",
                                Toast.LENGTH_SHORT).show();
                        break;
                    }
                }
            }
        });
        currentM = System.currentTimeMillis();
    }
}

From source file:org.telegram.ui.CacheControlActivity.java

@Override
public View createView(Context context) {
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    actionBar.setTitle(LocaleController.getString("CacheSettings", R.string.CacheSettings));
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override//from ww w. ja  va  2  s  .c o  m
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            }
        }
    });

    listAdapter = new ListAdapter(context);

    fragmentView = new FrameLayout(context);
    FrameLayout frameLayout = (FrameLayout) fragmentView;
    frameLayout.setBackgroundColor(ContextCompat.getColor(context, R.color.settings_background));

    ListView listView = new ListView(context);
    listView.setDivider(null);
    listView.setDividerHeight(0);
    listView.setVerticalScrollBarEnabled(false);
    listView.setDrawSelectorOnTop(true);
    frameLayout.addView(listView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    listView.setAdapter(listAdapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(final AdapterView<?> adapterView, View view, final int i, long l) {
            if (getParentActivity() == null) {
                return;
            }
            if (i == keepMediaRow) {
                BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity());
                builder.setItems(
                        new CharSequence[] { LocaleController.formatPluralString("Weeks", 1),
                                LocaleController.formatPluralString("Months", 1),
                                LocaleController.getString("KeepMediaForever", R.string.KeepMediaForever) },
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, final int which) {
                                SharedPreferences.Editor editor = ApplicationLoader.applicationContext
                                        .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).edit();
                                editor.putInt("keep_media", which).commit();
                                if (listAdapter != null) {
                                    listAdapter.notifyDataSetChanged();
                                }
                                PendingIntent pintent = PendingIntent.getService(
                                        ApplicationLoader.applicationContext, 0,
                                        new Intent(ApplicationLoader.applicationContext,
                                                ClearCacheService.class),
                                        0);
                                AlarmManager alarmManager = (AlarmManager) ApplicationLoader.applicationContext
                                        .getSystemService(Context.ALARM_SERVICE);
                                if (which == 2) {
                                    alarmManager.cancel(pintent);
                                } else {
                                    alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                                            AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY, pintent);
                                }
                            }
                        });
                showDialog(builder.create());
            } else if (i == databaseRow) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                builder.setMessage(
                        LocaleController.getString("LocalDatabaseClear", R.string.LocalDatabaseClear));
                builder.setPositiveButton(LocaleController.getString("CacheClear", R.string.CacheClear),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                final ProgressDialog progressDialog = new ProgressDialog(getParentActivity());
                                progressDialog
                                        .setMessage(LocaleController.getString("Loading", R.string.Loading));
                                progressDialog.setCanceledOnTouchOutside(false);
                                progressDialog.setCancelable(false);
                                progressDialog.show();
                                MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            SQLiteDatabase database = MessagesStorage.getInstance()
                                                    .getDatabase();
                                            ArrayList<Long> dialogsToCleanup = new ArrayList<>();
                                            SQLiteCursor cursor = database
                                                    .queryFinalized("SELECT did FROM dialogs WHERE 1");
                                            StringBuilder ids = new StringBuilder();
                                            while (cursor.next()) {
                                                long did = cursor.longValue(0);
                                                int lower_id = (int) did;
                                                int high_id = (int) (did >> 32);
                                                if (lower_id != 0 && high_id != 1) {
                                                    dialogsToCleanup.add(did);
                                                }
                                            }
                                            cursor.dispose();

                                            SQLitePreparedStatement state5 = database
                                                    .executeFast("REPLACE INTO messages_holes VALUES(?, ?, ?)");
                                            SQLitePreparedStatement state6 = database.executeFast(
                                                    "REPLACE INTO media_holes_v2 VALUES(?, ?, ?, ?)");

                                            database.beginTransaction();
                                            for (int a = 0; a < dialogsToCleanup.size(); a++) {
                                                Long did = dialogsToCleanup.get(a);
                                                int messagesCount = 0;
                                                cursor = database.queryFinalized(
                                                        "SELECT COUNT(mid) FROM messages WHERE uid = " + did);
                                                if (cursor.next()) {
                                                    messagesCount = cursor.intValue(0);
                                                }
                                                cursor.dispose();
                                                if (messagesCount <= 2) {
                                                    continue;
                                                }

                                                cursor = database.queryFinalized(
                                                        "SELECT last_mid_i, last_mid FROM dialogs WHERE did = "
                                                                + did);
                                                int messageId = -1;
                                                if (cursor.next()) {
                                                    long last_mid_i = cursor.longValue(0);
                                                    long last_mid = cursor.longValue(1);
                                                    SQLiteCursor cursor2 = database.queryFinalized(
                                                            "SELECT data FROM messages WHERE uid = " + did
                                                                    + " AND mid IN (" + last_mid_i + ","
                                                                    + last_mid + ")");
                                                    try {
                                                        while (cursor2.next()) {
                                                            NativeByteBuffer data = cursor2.byteBufferValue(0);
                                                            if (data != null) {
                                                                TLRPC.Message message = TLRPC.Message
                                                                        .TLdeserialize(data,
                                                                                data.readInt32(false), false);
                                                                data.reuse();
                                                                if (message != null) {
                                                                    messageId = message.id;
                                                                }
                                                            }
                                                        }
                                                    } catch (Exception e) {
                                                        FileLog.e("tmessages", e);
                                                    }
                                                    cursor2.dispose();

                                                    database.executeFast("DELETE FROM messages WHERE uid = "
                                                            + did + " AND mid != " + last_mid_i + " AND mid != "
                                                            + last_mid).stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM messages_holes WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM bot_keyboard WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM media_counts_v2 WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM media_v2 WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM media_holes_v2 WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    BotQuery.clearBotKeyboard(did, null);
                                                    if (messageId != -1) {
                                                        MessagesStorage.createFirstHoles(did, state5, state6,
                                                                messageId);
                                                    }
                                                }
                                                cursor.dispose();
                                            }
                                            state5.dispose();
                                            state6.dispose();
                                            database.commitTransaction();
                                            database.executeFast("VACUUM").stepThis().dispose();
                                        } catch (Exception e) {
                                            FileLog.e("tmessages", e);
                                        } finally {
                                            AndroidUtilities.runOnUIThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    try {
                                                        progressDialog.dismiss();
                                                    } catch (Exception e) {
                                                        FileLog.e("tmessages", e);
                                                    }
                                                    if (listAdapter != null) {
                                                        File file = new File(
                                                                ApplicationLoader.getFilesDirFixed(),
                                                                "cache4.db");
                                                        databaseSize = file.length();
                                                        listAdapter.notifyDataSetChanged();
                                                    }
                                                }
                                            });
                                        }
                                    }
                                });
                            }
                        });
                showDialog(builder.create());
            } else if (i == cacheRow) {
                if (totalSize <= 0 || getParentActivity() == null) {
                    return;
                }
                BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity());
                builder.setApplyTopPadding(false);
                builder.setApplyBottomPadding(false);
                LinearLayout linearLayout = new LinearLayout(getParentActivity());
                linearLayout.setOrientation(LinearLayout.VERTICAL);
                for (int a = 0; a < 6; a++) {
                    long size = 0;
                    String name = null;
                    if (a == 0) {
                        size = photoSize;
                        name = LocaleController.getString("LocalPhotoCache", R.string.LocalPhotoCache);
                    } else if (a == 1) {
                        size = videoSize;
                        name = LocaleController.getString("LocalVideoCache", R.string.LocalVideoCache);
                    } else if (a == 2) {
                        size = documentsSize;
                        name = LocaleController.getString("LocalDocumentCache", R.string.LocalDocumentCache);
                    } else if (a == 3) {
                        size = musicSize;
                        name = LocaleController.getString("LocalMusicCache", R.string.LocalMusicCache);
                    } else if (a == 4) {
                        size = audioSize;
                        name = LocaleController.getString("LocalAudioCache", R.string.LocalAudioCache);
                    } else if (a == 5) {
                        size = cacheSize;
                        name = LocaleController.getString("LocalCache", R.string.LocalCache);
                    }
                    if (size > 0) {
                        clear[a] = true;
                        CheckBoxCell checkBoxCell = new CheckBoxCell(getParentActivity());
                        checkBoxCell.setTag(a);
                        checkBoxCell.setBackgroundResource(R.drawable.list_selector);
                        linearLayout.addView(checkBoxCell,
                                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
                        checkBoxCell.setText(name, AndroidUtilities.formatFileSize(size), true, true);
                        checkBoxCell.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                CheckBoxCell cell = (CheckBoxCell) v;
                                int num = (Integer) cell.getTag();
                                clear[num] = !clear[num];
                                cell.setChecked(clear[num], true);
                            }
                        });
                    } else {
                        clear[a] = false;
                    }
                }
                BottomSheet.BottomSheetCell cell = new BottomSheet.BottomSheetCell(getParentActivity(), 1);
                cell.setBackgroundResource(R.drawable.list_selector);
                cell.setTextAndIcon(
                        LocaleController.getString("ClearMediaCache", R.string.ClearMediaCache).toUpperCase(),
                        0);
                cell.setTextColor(Theme.STICKERS_SHEET_REMOVE_TEXT_COLOR);
                cell.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            if (visibleDialog != null) {
                                visibleDialog.dismiss();
                            }
                        } catch (Exception e) {
                            FileLog.e("tmessages", e);
                        }
                        cleanupFolders();
                    }
                });
                linearLayout.addView(cell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
                builder.setCustomView(linearLayout);
                showDialog(builder.create());
            }
        }
    });

    return fragmentView;
}

From source file:com.nttec.everychan.chans.fourchan.FourchanModule.java

private void addPasscodePreference(PreferenceGroup preferenceGroup) {
    final Context context = preferenceGroup.getContext();
    PreferenceScreen passScreen = preferenceGroup.getPreferenceManager().createPreferenceScreen(context);
    passScreen.setTitle("4chan pass");
    EditTextPreference passTokenPreference = new EditTextPreference(context);
    EditTextPreference passPINPreference = new EditTextPreference(context);
    Preference passLoginPreference = new Preference(context);
    Preference passClearPreference = new Preference(context);
    passTokenPreference.setTitle("Token");
    passTokenPreference.setDialogTitle("Token");
    passTokenPreference.setKey(getSharedKey(PREF_KEY_PASS_TOKEN));
    passTokenPreference.getEditText().setSingleLine();
    passTokenPreference.getEditText()// w  ww .ja  va 2s.com
            .setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
    passPINPreference.setTitle("PIN");
    passPINPreference.setDialogTitle("PIN");
    passPINPreference.setKey(getSharedKey(PREF_KEY_PASS_PIN));
    passPINPreference.getEditText().setSingleLine();
    passPINPreference.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
    passLoginPreference.setTitle("Log In");
    passLoginPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            if (!useHttps())
                Toast.makeText(context, "Using HTTPS even if HTTP is selected", Toast.LENGTH_SHORT).show();
            final String token = preferences.getString(getSharedKey(PREF_KEY_PASS_TOKEN), "");
            final String pin = preferences.getString(getSharedKey(PREF_KEY_PASS_PIN), "");
            final String authUrl = "https://sys.4chan.org/auth"; //only https
            final CancellableTask passAuthTask = new CancellableTask.BaseCancellableTask();
            final ProgressDialog passAuthProgressDialog = new ProgressDialog(context);
            passAuthProgressDialog.setMessage("Logging in");
            passAuthProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    passAuthTask.cancel();
                }
            });
            passAuthProgressDialog.setCanceledOnTouchOutside(false);
            passAuthProgressDialog.show();
            Async.runAsync(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (passAuthTask.isCancelled())
                            return;
                        setPasscodeCookie(null, true);
                        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                        pairs.add(new BasicNameValuePair("act", "do_login"));
                        pairs.add(new BasicNameValuePair("id", token));
                        pairs.add(new BasicNameValuePair("pin", pin));
                        HttpRequestModel request = HttpRequestModel.builder()
                                .setPOST(new UrlEncodedFormEntity(pairs, "UTF-8")).build();
                        String response = HttpStreamer.getInstance().getStringFromUrl(authUrl, request,
                                httpClient, null, passAuthTask, false);
                        if (passAuthTask.isCancelled())
                            return;
                        if (response.contains("Your device is now authorized")) {
                            String passId = null;
                            for (Cookie cookie : httpClient.getCookieStore().getCookies()) {
                                if (cookie.getName().equals("pass_id")) {
                                    String value = cookie.getValue();
                                    if (!value.equals("0")) {
                                        passId = value;
                                        break;
                                    }
                                }
                            }
                            if (passId == null) {
                                showToast("Could not get pass id");
                            } else {
                                setPasscodeCookie(passId, true);
                                showToast("Success! Your device is now authorized.");
                            }
                        } else if (response.contains("Your Token must be exactly 10 characters")) {
                            showToast("Incorrect token");
                        } else if (response.contains("You have left one or more fields blank")) {
                            showToast("You have left one or more fields blank");
                        } else if (response.contains("Incorrect Token or PIN")) {
                            showToast("Incorrect Token or PIN");
                        } else {
                            Matcher m = Pattern
                                    .compile("<strong style=\"color: red; font-size: larger;\">(.*?)</strong>")
                                    .matcher(response);
                            if (m.find()) {
                                showToast(m.group(1));
                            } else {
                                showWebView(response);
                            }
                        }
                    } catch (Exception e) {
                        showToast(e.getMessage() == null ? resources.getString(R.string.error_unknown)
                                : e.getMessage());
                    } finally {
                        passAuthProgressDialog.dismiss();
                    }
                }

                private void showToast(final String message) {
                    if (context instanceof Activity) {
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(context, message, Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }

                private void showWebView(final String html) {
                    if (context instanceof Activity) {
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                WebView webView = new WebView(context);
                                webView.getSettings().setSupportZoom(true);
                                webView.loadData(html, "text/html", null);
                                new AlertDialog.Builder(context).setView(webView)
                                        .setNeutralButton(android.R.string.ok, null).show();
                            }
                        });
                    }
                }
            });
            return true;
        }
    });
    passClearPreference.setTitle("Reset pass cookie");
    passClearPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            setPasscodeCookie(null, true);
            Toast.makeText(context, "Cookie is reset", Toast.LENGTH_LONG).show();
            return true;
        }
    });
    passScreen.addPreference(passTokenPreference);
    passScreen.addPreference(passPINPreference);
    passScreen.addPreference(passLoginPreference);
    passScreen.addPreference(passClearPreference);
    preferenceGroup.addPreference(passScreen);
}

From source file:com.juick.android.MessageMenu.java

public void translateToRussian(final String body, final Utils.Function<Void, String[]> callback) {
    final ProgressDialog mDialog = new ProgressDialog(activity);
    mDialog.setMessage("Google Translate...");
    mDialog.setCancelable(true);//  w  ww .  j ava 2s .  c o  m
    mDialog.setCanceledOnTouchOutside(true);
    final ArrayList<HttpGet> actions = new ArrayList<HttpGet>();

    final String[] split = body.split("\\.");
    final String[] results = new String[split.length];
    final int[] pieces = new int[] { 0 };
    for (int i = 0; i < split.length; i++) {
        final String s = split[i];
        if (s.trim().length() == 0) {
            results[i] = split[i];
            synchronized (pieces) {
                pieces[0]++;
                if (pieces[0] == results.length) {
                    mDialog.hide();
                    callback.apply(results);
                }
            }
        } else {
            Uri.Builder builder = new Uri.Builder().scheme("http").authority("translate.google.com")
                    .path("translate_a/t");
            builder = builder.appendQueryParameter("client", "at");
            builder = builder.appendQueryParameter("v", "2.0");
            builder = builder.appendQueryParameter("sl", "auto");
            builder = builder.appendQueryParameter("tl", "ru");
            builder = builder.appendQueryParameter("hl", "en_US");
            builder = builder.appendQueryParameter("ie", "UTF-8");
            builder = builder.appendQueryParameter("oe", "UTF-8");
            builder = builder.appendQueryParameter("inputm", "2");
            builder = builder.appendQueryParameter("source", "edit");
            builder = builder.appendQueryParameter("text", s);
            final HttpClient client = new DefaultHttpClient();
            // AndroidHttpClient.newInstance("AndroidTranslate/2.4.2 2.3.6 (gzip)", activity);
            final HttpGet verb = new HttpGet(builder.build().toString());
            actions.add(verb);
            verb.setHeader("Accept-Charset", "UTF-8");
            final int finalI = i;
            final Thread thread = new Thread("google translate") {
                @Override
                public void run() {
                    final StringBuilder out = new StringBuilder("");
                    try {
                        final String retval = client.execute(verb, new BasicResponseHandler());
                        out.setLength(0);
                        out.append(retval);
                    } catch (IOException e) {
                        if (s.length() > 0)
                            out.append("[error: " + e.toString() + "]");
                        Log.e("com.juickadvanced", "Error calling google translate", e);
                    } finally {
                        client.getConnectionManager().shutdown();
                        synchronized (pieces) {
                            pieces[0]++;
                            results[finalI] = out.toString();
                            if (pieces[0] == results.length) {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mDialog.hide();
                                        callback.apply(results);
                                    }
                                });
                            }
                        }
                    }
                }

            };
            thread.start();
        }

    }

    mDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialogInterface) {
            for (HttpGet action : actions) {
                action.abort();
            }
            synchronized (pieces) {
                pieces[0] = -10000;
            }
            mDialog.hide();
        }
    });
    mDialog.show();
}

From source file:com.easemob.chatuidemo.activity.main.MainActivity.java

void logout() {
    final ProgressDialog pd = new ProgressDialog(this);
    String st = getResources().getString(R.string.Are_logged_out);
    pd.setMessage(st);/*  w w w . ja va2  s  . c o m*/
    pd.setCanceledOnTouchOutside(false);
    pd.show();
    DemoHXSDKHelper.getInstance().logout(true, new EMCallBack() {

        @Override
        public void onSuccess() {
            runOnUiThread(new Runnable() {
                public void run() {
                    pd.dismiss();
                    // ??
                    finish();
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));

                }
            });
        }

        @Override
        public void onProgress(int progress, String status) {

        }

        @Override
        public void onError(int code, String message) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    pd.dismiss();
                    Toast.makeText(MainActivity.this, "unbind devicetokens failed", Toast.LENGTH_SHORT).show();

                }
            });
        }
    });
}

From source file:id.ridon.keude.AppDetailsData.java

private ProgressDialog getProgressDialog(String file) {
    if (progressDialog == null) {
        final ProgressDialog pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage(getString(R.string.download_server) + ":\n " + file);
        pd.setCancelable(true);//from   ww w  . j a va  2 s. c  om
        pd.setCanceledOnTouchOutside(false);

        // The indeterminate-ness will get overridden on the first progress event we receive.
        pd.setIndeterminate(true);

        pd.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                Log.d(TAG, "User clicked 'cancel' on download, attempting to interrupt download thread.");
                if (downloadHandler != null) {
                    downloadHandler.cancel();
                    cleanUpFinishedDownload();
                } else {
                    Log.e(TAG, "Tried to cancel, but the downloadHandler doesn't exist.");
                }
                progressDialog = null;
                Toast.makeText(AppDetails.this, getString(R.string.download_cancelled), Toast.LENGTH_LONG)
                        .show();
            }
        });
        pd.setButton(DialogInterface.BUTTON_NEUTRAL, getString(R.string.cancel),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        pd.cancel();
                    }
                });
        progressDialog = pd;
    }
    return progressDialog;
}

From source file:cn.ucai.yizhesale.activity.ChatActivity.java

/**
 * ???/*from  ww w  .  j a v  a2 s .c o m*/
 * 
 * @param username
 */
private void addUserToBlacklist(final String username) {
    final ProgressDialog pd = new ProgressDialog(this);
    pd.setMessage(getString(cn.ucai.yizhesale.R.string.Is_moved_into_blacklist));
    pd.setCanceledOnTouchOutside(false);
    pd.show();
    new Thread(new Runnable() {
        public void run() {
            try {
                EMContactManager.getInstance().addUserToBlackList(username, false);
                runOnUiThread(new Runnable() {
                    public void run() {
                        pd.dismiss();
                        Toast.makeText(getApplicationContext(),
                                cn.ucai.yizhesale.R.string.Move_into_blacklist_success, Toast.LENGTH_SHORT)
                                .show();
                    }
                });
            } catch (EaseMobException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    public void run() {
                        pd.dismiss();
                        Toast.makeText(getApplicationContext(),
                                cn.ucai.yizhesale.R.string.Move_into_blacklist_failure, Toast.LENGTH_SHORT)
                                .show();
                    }
                });
            }
        }
    }).start();
}