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:org.cafemember.ui.LaunchActivity.java

private void runLinkRequest(final String username, final String group, final String sticker,
        final String botUser, final String botChat, final String message, final boolean hasUrl,
        final Integer messageId, final int state) {
    final ProgressDialog progressDialog = new ProgressDialog(this);
    progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading));
    progressDialog.setCanceledOnTouchOutside(false);
    progressDialog.setCancelable(false);
    int requestId = 0;

    if (username != null) {
        TLRPC.TL_contacts_resolveUsername req = new TLRPC.TL_contacts_resolveUsername();
        req.username = username;/*from   w w w  . j av  a  2  s. c o m*/
        requestId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
            @Override
            public void run(final TLObject response, final TLRPC.TL_error error) {
                AndroidUtilities.runOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!LaunchActivity.this.isFinishing()) {
                            try {
                                progressDialog.dismiss();
                            } catch (Exception e) {
                                FileLog.e("tmessages", e);
                            }
                            if (error == null && actionBarLayout != null) {
                                final TLRPC.TL_contacts_resolvedPeer res = (TLRPC.TL_contacts_resolvedPeer) response;
                                MessagesController.getInstance().putUsers(res.users, false);
                                MessagesController.getInstance().putChats(res.chats, false);
                                MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, false,
                                        true);

                                if (botChat != null) {
                                    final TLRPC.User user = !res.users.isEmpty() ? res.users.get(0) : null;
                                    if (user == null || user.bot && user.bot_nochats) {
                                        try {
                                            Toast.makeText(LaunchActivity.this,
                                                    LocaleController.getString("BotCantJoinGroups",
                                                            R.string.BotCantJoinGroups),
                                                    Toast.LENGTH_SHORT).show();
                                        } catch (Exception e) {
                                            FileLog.e("tmessages", e);
                                        }
                                        return;
                                    }
                                    Bundle args = new Bundle();
                                    args.putBoolean("onlySelect", true);
                                    args.putInt("dialogsType", 2);
                                    args.putString("addToGroupAlertString",
                                            LocaleController.formatString("AddToTheGroupTitle",
                                                    R.string.AddToTheGroupTitle, UserObject.getUserName(user),
                                                    "%1$s"));
                                    DialogsActivity fragment = new DialogsActivity(args);
                                    fragment.setDelegate(new DialogsActivity.DialogsActivityDelegate() {
                                        @Override
                                        public void didSelectDialog(DialogsActivity fragment, long did,
                                                boolean param) {
                                            Bundle args = new Bundle();
                                            args.putBoolean("scrollToTopOnResume", true);
                                            args.putInt("chat_id", -(int) did);
                                            if (mainFragmentsStack.isEmpty() || MessagesController
                                                    .checkCanOpenChat(args, mainFragmentsStack
                                                            .get(mainFragmentsStack.size() - 1))) {
                                                NotificationCenter.getInstance()
                                                        .postNotificationName(NotificationCenter.closeChats);
                                                MessagesController.getInstance().addUserToChat(-(int) did, user,
                                                        null, 0, botChat, null);
                                                actionBarLayout.presentFragment(new ChatActivity(args), true,
                                                        false, true);
                                            }
                                        }
                                    });
                                    presentFragment(fragment);
                                } else {
                                    long dialog_id;
                                    boolean isBot = false;
                                    Bundle args = new Bundle();
                                    if (!res.chats.isEmpty()) {
                                        args.putInt("chat_id", res.chats.get(0).id);
                                        dialog_id = -res.chats.get(0).id;
                                    } else {
                                        args.putInt("user_id", res.users.get(0).id);
                                        dialog_id = res.users.get(0).id;
                                    }
                                    if (botUser != null && res.users.size() > 0 && res.users.get(0).bot) {
                                        args.putString("botUser", botUser);
                                        isBot = true;
                                    }
                                    if (messageId != null) {
                                        args.putInt("message_id", messageId);
                                    }
                                    BaseFragment lastFragment = !mainFragmentsStack.isEmpty()
                                            ? mainFragmentsStack.get(mainFragmentsStack.size() - 1)
                                            : null;
                                    if (lastFragment == null
                                            || MessagesController.checkCanOpenChat(args, lastFragment)) {
                                        if (isBot && lastFragment != null
                                                && lastFragment instanceof ChatActivity
                                                && ((ChatActivity) lastFragment).getDialogId() == dialog_id) {
                                            ((ChatActivity) lastFragment).setBotUser(botUser);
                                        } else {
                                            ChatActivity fragment = new ChatActivity(args);
                                            NotificationCenter.getInstance()
                                                    .postNotificationName(NotificationCenter.closeChats);
                                            actionBarLayout.presentFragment(fragment, false, true, true);
                                        }
                                    }
                                }
                            } else {
                                try {
                                    Toast.makeText(LaunchActivity.this, LocaleController.getString(
                                            "NoUsernameFound", R.string.NoUsernameFound), Toast.LENGTH_SHORT)
                                            .show();
                                } catch (Exception e) {
                                    FileLog.e("tmessages", e);
                                }
                            }
                        }
                    }
                });
            }
        });
    } else if (group != null) {
        if (state == 0) {
            final TLRPC.TL_messages_checkChatInvite req = new TLRPC.TL_messages_checkChatInvite();
            req.hash = group;
            requestId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
                @Override
                public void run(final TLObject response, final TLRPC.TL_error error) {
                    AndroidUtilities.runOnUIThread(new Runnable() {
                        @Override
                        public void run() {
                            if (!LaunchActivity.this.isFinishing()) {
                                try {
                                    progressDialog.dismiss();
                                } catch (Exception e) {
                                    FileLog.e("tmessages", e);
                                }
                                if (error == null && actionBarLayout != null) {
                                    TLRPC.ChatInvite invite = (TLRPC.ChatInvite) response;
                                    if (invite.chat != null && !ChatObject.isLeftFromChat(invite.chat)) {
                                        MessagesController.getInstance().putChat(invite.chat, false);
                                        ArrayList<TLRPC.Chat> chats = new ArrayList<>();
                                        chats.add(invite.chat);
                                        MessagesStorage.getInstance().putUsersAndChats(null, chats, false,
                                                true);
                                        Bundle args = new Bundle();
                                        args.putInt("chat_id", invite.chat.id);
                                        if (mainFragmentsStack.isEmpty() || MessagesController.checkCanOpenChat(
                                                args, mainFragmentsStack.get(mainFragmentsStack.size() - 1))) {
                                            ChatActivity fragment = new ChatActivity(args);
                                            NotificationCenter.getInstance()
                                                    .postNotificationName(NotificationCenter.closeChats);
                                            actionBarLayout.presentFragment(fragment, false, true, true);
                                        }
                                    } else {
                                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                                LaunchActivity.this);
                                        builder.setTitle(
                                                LocaleController.getString("AppName", R.string.AppName));
                                        if (!invite.megagroup && invite.channel
                                                || ChatObject.isChannel(invite.chat)
                                                        && !invite.chat.megagroup) {
                                            builder.setMessage(LocaleController.formatString("ChannelJoinTo",
                                                    R.string.ChannelJoinTo,
                                                    invite.chat != null ? invite.chat.title : invite.title));
                                        } else {
                                            builder.setMessage(LocaleController.formatString("JoinToGroup",
                                                    R.string.JoinToGroup,
                                                    invite.chat != null ? invite.chat.title : invite.title));
                                        }
                                        builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialogInterface,
                                                            int i) {
                                                        runLinkRequest(username, group, sticker, botUser,
                                                                botChat, message, hasUrl, messageId, 1);
                                                    }
                                                });
                                        builder.setNegativeButton(
                                                LocaleController.getString("Cancel", R.string.Cancel), null);
                                        showAlertDialog(builder);
                                    }
                                } else {
                                    AlertDialog.Builder builder = new AlertDialog.Builder(LaunchActivity.this);
                                    builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                                    if (error.text.startsWith("FLOOD_WAIT")) {
                                        builder.setMessage(
                                                LocaleController.getString("FloodWait", R.string.FloodWait));
                                    } else {
                                        builder.setMessage(LocaleController.getString(
                                                "JoinToGroupErrorNotExist", R.string.JoinToGroupErrorNotExist));
                                    }
                                    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                                            null);
                                    showAlertDialog(builder);
                                }
                            }
                        }
                    });
                }
            }, ConnectionsManager.RequestFlagFailOnServerErrors);
        } else if (state == 1) {
            TLRPC.TL_messages_importChatInvite req = new TLRPC.TL_messages_importChatInvite();
            req.hash = group;
            ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
                @Override
                public void run(final TLObject response, final TLRPC.TL_error error) {
                    if (error == null) {
                        TLRPC.Updates updates = (TLRPC.Updates) response;
                        MessagesController.getInstance().processUpdates(updates, false);
                    }
                    AndroidUtilities.runOnUIThread(new Runnable() {
                        @Override
                        public void run() {
                            if (!LaunchActivity.this.isFinishing()) {
                                try {
                                    progressDialog.dismiss();
                                } catch (Exception e) {
                                    FileLog.e("tmessages", e);
                                }
                                if (error == null) {
                                    if (actionBarLayout != null) {
                                        TLRPC.Updates updates = (TLRPC.Updates) response;
                                        if (!updates.chats.isEmpty()) {
                                            TLRPC.Chat chat = updates.chats.get(0);
                                            chat.left = false;
                                            chat.kicked = false;
                                            MessagesController.getInstance().putUsers(updates.users, false);
                                            MessagesController.getInstance().putChats(updates.chats, false);
                                            Bundle args = new Bundle();
                                            args.putInt("chat_id", chat.id);
                                            if (mainFragmentsStack.isEmpty() || MessagesController
                                                    .checkCanOpenChat(args, mainFragmentsStack
                                                            .get(mainFragmentsStack.size() - 1))) {
                                                ChatActivity fragment = new ChatActivity(args);
                                                NotificationCenter.getInstance()
                                                        .postNotificationName(NotificationCenter.closeChats);
                                                actionBarLayout.presentFragment(fragment, false, true, true);
                                            }
                                        }
                                    }
                                } else {
                                    AlertDialog.Builder builder = new AlertDialog.Builder(LaunchActivity.this);
                                    builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                                    if (error.text.startsWith("FLOOD_WAIT")) {
                                        builder.setMessage(
                                                LocaleController.getString("FloodWait", R.string.FloodWait));
                                    } else if (error.text.equals("USERS_TOO_MUCH")) {
                                        builder.setMessage(LocaleController.getString("JoinToGroupErrorFull",
                                                R.string.JoinToGroupErrorFull));
                                    } else {
                                        builder.setMessage(LocaleController.getString(
                                                "JoinToGroupErrorNotExist", R.string.JoinToGroupErrorNotExist));
                                    }
                                    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                                            null);
                                    showAlertDialog(builder);
                                }
                            }
                        }
                    });
                }
            }, ConnectionsManager.RequestFlagFailOnServerErrors);
        }
    } else if (sticker != null) {
        if (!mainFragmentsStack.isEmpty()) {
            TLRPC.TL_inputStickerSetShortName stickerset = new TLRPC.TL_inputStickerSetShortName();
            stickerset.short_name = sticker;
            mainFragmentsStack.get(mainFragmentsStack.size() - 1)
                    .showDialog(new StickersAlert(LaunchActivity.this, stickerset, null, null));
        }
        return;
    } else if (message != null) {
        Bundle args = new Bundle();
        args.putBoolean("onlySelect", true);
        DialogsActivity fragment = new DialogsActivity(args);
        fragment.setDelegate(new DialogsActivity.DialogsActivityDelegate() {
            @Override
            public void didSelectDialog(DialogsActivity fragment, long did, boolean param) {
                Bundle args = new Bundle();
                args.putBoolean("scrollToTopOnResume", true);
                args.putBoolean("hasUrl", hasUrl);
                int lower_part = (int) did;
                int high_id = (int) (did >> 32);
                if (lower_part != 0) {
                    if (high_id == 1) {
                        args.putInt("chat_id", lower_part);
                    } else {
                        if (lower_part > 0) {
                            args.putInt("user_id", lower_part);
                        } else if (lower_part < 0) {
                            args.putInt("chat_id", -lower_part);
                        }
                    }
                } else {
                    args.putInt("enc_id", high_id);
                }
                if (MessagesController.checkCanOpenChat(args, fragment)) {
                    NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats);
                    SharedPreferences preferences = ApplicationLoader.applicationContext
                            .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putString("dialog_" + did, message);
                    editor.commit();
                    actionBarLayout.presentFragment(new ChatActivity(args), true, false, true);
                }
            }
        });
        presentFragment(fragment, false, true);
    }

    if (requestId != 0) {
        final int reqId = requestId;
        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
                LocaleController.getString("Cancel", R.string.Cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ConnectionsManager.getInstance().cancelRequest(reqId, true);
                        try {
                            dialog.dismiss();
                        } catch (Exception e) {
                            FileLog.e("tmessages", e);
                        }
                    }
                });
        progressDialog.show();
    }
}

From source file:com.dmsl.anyplace.UnifiedNavigationActivity.java

/** Called when the activity is first created. */
@Override/*  w w  w . j ava 2  s  .  co  m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_unifiednav);

    detectedAPs = (TextView) findViewById(R.id.detectedAPs);
    textFloor = (TextView) findViewById(R.id.textFloor);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    textDebug = (TextView) findViewById(R.id.textDebug);
    if (AnyplaceAPI.DEBUG_MESSAGES)
        textDebug.setVisibility(View.VISIBLE);

    ActionBar actionBar = getSupportActionBar();
    actionBar.setHomeButtonEnabled(true);

    userData = new AnyUserData();

    SimpleWifiManager.getInstance().startScan();
    sensorsMain = new SensorsMain(getApplicationContext());
    movementDetector = new MovementDetector();
    sensorsMain.addListener(movementDetector);
    sensorsStepCounter = new SensorsStepCounter(getApplicationContext(), sensorsMain);
    lpTracker = new TrackerLogicPlusIMU(movementDetector, sensorsMain, sensorsStepCounter);
    // lpTracker = new TrackerLogic(sensorsMain);
    floorSelector = new Algo1Radiomap(getApplicationContext());

    mAnyplaceCache = AnyplaceCache.getInstance(this);
    visiblePois = new VisiblePois();

    setUpMapIfNeeded();

    // setup the trackme button overlaid in the map
    btnTrackme = (ImageButton) findViewById(R.id.btnTrackme);
    btnTrackme.setImageResource(R.drawable.dark_device_access_location_off);
    isTrackingErrorBackground = true;
    btnTrackme.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final GeoPoint gpsLoc = userData.getLocationGPSorIP();
            if (gpsLoc != null) {
                AnyplaceCache mAnyplaceCache = AnyplaceCache.getInstance(UnifiedNavigationActivity.this);
                mAnyplaceCache.loadWorldBuildings(new FetchBuildingsTaskListener() {

                    @Override
                    public void onSuccess(String result, List<BuildingModel> buildings) {
                        final FetchNearBuildingsTask nearest = new FetchNearBuildingsTask();
                        nearest.run(buildings, gpsLoc.lat, gpsLoc.lng, 200);

                        if (nearest.buildings.size() > 0 && (userData.getSelectedBuildingId() == null
                                || !userData.getSelectedBuildingId().equals(nearest.buildings.get(0).buid))) {
                            floorSelector.Stop();
                            final FloorSelector floorSelectorAlgo1 = new Algo1Server(getApplicationContext());
                            final ProgressDialog floorSelectorDialog = new ProgressDialog(
                                    UnifiedNavigationActivity.this);

                            floorSelectorDialog.setIndeterminate(true);
                            floorSelectorDialog.setTitle("Detecting floor");
                            floorSelectorDialog.setMessage("Please be patient...");
                            floorSelectorDialog.setCancelable(true);
                            floorSelectorDialog.setCanceledOnTouchOutside(false);
                            floorSelectorDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                                @Override
                                public void onCancel(DialogInterface dialog) {
                                    floorSelectorAlgo1.Destoy();
                                    bypassSelectBuildingActivity(nearest.buildings.get(0), "0", false);
                                }
                            });

                            class Callback implements ErrorAnyplaceFloorListener, FloorAnyplaceFloorListener {

                                @Override
                                public void onNewFloor(String floor) {
                                    floorSelectorAlgo1.Destoy();
                                    if (floorSelectorDialog.isShowing()) {
                                        floorSelectorDialog.dismiss();
                                        bypassSelectBuildingActivity(nearest.buildings.get(0), floor, false);
                                    }
                                }

                                @Override
                                public void onFloorError(Exception ex) {
                                    floorSelectorAlgo1.Destoy();
                                    if (floorSelectorDialog.isShowing()) {
                                        floorSelectorDialog.dismiss();
                                        bypassSelectBuildingActivity(nearest.buildings.get(0), "0", false);
                                    }
                                }

                            }
                            Callback callback = new Callback();
                            floorSelectorAlgo1.addListener((FloorAnyplaceFloorListener) callback);
                            floorSelectorAlgo1.addListener((ErrorAnyplaceFloorListener) callback);

                            // Show Dialog
                            floorSelectorDialog.show();
                            floorSelectorAlgo1.Start(gpsLoc.lat, gpsLoc.lng);
                        } else {
                            focusUserLocation();

                            // Clear cancel request
                            lastFloor = null;
                            floorSelector.RunNow();
                            lpTracker.reset();
                        }
                    }

                    @Override
                    public void onErrorOrCancel(String result) {

                    }

                }, UnifiedNavigationActivity.this, false);
            } else {
                focusUserLocation();

                // Clear cancel request
                lastFloor = null;
                floorSelector.RunNow();
                lpTracker.reset();
            }

        }
    });

    btnFloorUp = (ImageButton) findViewById(R.id.btnFloorUp);
    btnFloorUp.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            if (!userData.isFloorSelected()) {
                Toast.makeText(getBaseContext(), "Load a map before tracking can be used!", Toast.LENGTH_SHORT)
                        .show();
                return;
            }

            BuildingModel b = userData.getSelectedBuilding();
            if (b == null) {
                return;
            }

            if (userData.isNavBuildingSelected()) {
                // Move to start/destination poi's floor
                String floor_number;
                List<PoisNav> puids = userData.getNavPois();
                // Check start and destination floor number
                if (!puids.get(puids.size() - 1).floor_number.equals(puids.get(0).floor_number)) {
                    if (userData.getSelectedFloorNumber().equals(puids.get(puids.size() - 1).floor_number)) {
                        floor_number = puids.get(0).floor_number;
                    } else {
                        floor_number = puids.get(puids.size() - 1).floor_number;
                    }

                    FloorModel floor = b.getFloorFromNumber(floor_number);
                    if (floor != null) {
                        bypassSelectBuildingActivity(b, floor);
                        return;
                    }
                }
            }

            // Move one floor up
            int index = b.getSelectedFloorIndex();

            if (b.checkIndex(index + 1)) {
                bypassSelectBuildingActivity(b, b.getFloors().get(index + 1));
            }

        }
    });

    btnFloorDown = (ImageButton) findViewById(R.id.btnFloorDown);
    btnFloorDown.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (!userData.isFloorSelected()) {
                Toast.makeText(getBaseContext(), "Load a map before tracking can be used!", Toast.LENGTH_SHORT)
                        .show();
                return;
            }

            BuildingModel b = userData.getSelectedBuilding();
            if (b == null) {
                return;
            }

            if (userData.isNavBuildingSelected()) {
                // Move to start/destination poi's floor
                String floor_number;
                List<PoisNav> puids = userData.getNavPois();
                // Check start and destination floor number
                if (!puids.get(puids.size() - 1).floor_number.equals(puids.get(0).floor_number)) {
                    if (userData.getSelectedFloorNumber().equals(puids.get(puids.size() - 1).floor_number)) {
                        floor_number = puids.get(0).floor_number;
                    } else {
                        floor_number = puids.get(puids.size() - 1).floor_number;
                    }

                    FloorModel floor = b.getFloorFromNumber(floor_number);
                    if (floor != null) {
                        bypassSelectBuildingActivity(b, floor);
                        return;
                    }
                }
            }

            // Move one floor down
            int index = b.getSelectedFloorIndex();

            if (b.checkIndex(index - 1)) {
                bypassSelectBuildingActivity(b, b.getFloors().get(index - 1));
            }
        }

    });

    /*
     * Create a new location client, using the enclosing class to handle callbacks.
     */
    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create();
    // Use high accuracy
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    // Set the update interval to 2 seconds
    mLocationRequest.setInterval(2000);
    // Set the fastest update interval to 1 second
    mLocationRequest.setFastestInterval(1000);
    mLocationClient = new LocationClient(this, this, this);
    // declare that this is the first time this Activity launched so make
    // the automatic building selection
    mAutomaticGPSBuildingSelection = true;

    // get/set settings
    PreferenceManager.setDefaultValues(this, SHARED_PREFS_ANYPLACE, MODE_PRIVATE, R.xml.preferences_anyplace,
            true);
    SharedPreferences preferences = getSharedPreferences(SHARED_PREFS_ANYPLACE, MODE_PRIVATE);
    preferences.registerOnSharedPreferenceChangeListener(this);
    lpTracker.setAlgorithm(preferences.getString("TrackingAlgorithm", "WKNN"));

    // handle the search intent
    handleIntent(getIntent());
}

From source file:com.nttec.everychan.ui.presentation.BoardFragment.java

private void runReport(final DeletePostModel reportPostModel) {
    final EditText inputField = new EditText(activity);
    inputField.setSingleLine();/*w  w w .  j  a va  2  s  .com*/
    if (presentationModel.source.boardModel.allowReport != BoardModel.REPORT_WITH_COMMENT) {
        inputField.setEnabled(false);
        inputField.setKeyListener(null);
    } else {
        inputField.setText(reportPostModel.reportReason == null ? "" : reportPostModel.reportReason);
    }

    DialogInterface.OnClickListener dlgOnClick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(final DialogInterface dialog, final int which) {
            if (currentTask != null)
                currentTask.cancel();
            if (pullableLayout.isRefreshing())
                setPullableNoRefreshing();
            reportPostModel.reportReason = inputField.getText().toString();
            final ProgressDialog progressDlg = new ProgressDialog(activity);
            final CancellableTask reportTask = new CancellableTask.BaseCancellableTask();
            progressDlg.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    reportTask.cancel();
                }
            });
            progressDlg.setCanceledOnTouchOutside(false);
            progressDlg.setMessage(resources.getString(R.string.dialog_report_progress));
            progressDlg.show();
            Async.runAsync(new Runnable() {
                @Override
                public void run() {
                    String error = null;
                    String targetUrl = null;
                    if (reportTask.isCancelled())
                        return;
                    try {
                        targetUrl = chan.reportPost(reportPostModel, null, reportTask);
                    } catch (Exception e) {
                        if (e instanceof InteractiveException) {
                            if (reportTask.isCancelled())
                                return;
                            ((InteractiveException) e).handle(activity, reportTask,
                                    new InteractiveException.Callback() {
                                        @Override
                                        public void onSuccess() {
                                            if (!reportTask.isCancelled()) {
                                                progressDlg.dismiss();
                                                onClick(dialog, which);
                                            }
                                        }

                                        @Override
                                        public void onError(String message) {
                                            if (!reportTask.isCancelled()) {
                                                progressDlg.dismiss();
                                                Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
                                                runReport(reportPostModel);
                                            }
                                        }
                                    });
                            return;
                        }

                        Logger.e(TAG, "cannot report post", e);
                        error = e.getMessage() == null ? "" : e.getMessage();
                    }
                    if (reportTask.isCancelled())
                        return;
                    final boolean success = error == null;
                    final String result = success ? targetUrl : error;
                    Async.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (reportTask.isCancelled())
                                return;
                            progressDlg.dismiss();
                            if (success) {
                                if (result == null) {
                                    update();
                                } else {
                                    UrlHandler.open(result, activity);
                                }
                            } else {
                                Toast.makeText(activity,
                                        TextUtils.isEmpty(result) ? resources.getString(R.string.error_unknown)
                                                : result,
                                        Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                }
            });
        }
    };
    new AlertDialog.Builder(activity).setTitle(R.string.dialog_report_reason).setView(inputField)
            .setPositiveButton(R.string.dialog_report_button, dlgOnClick)
            .setNegativeButton(android.R.string.cancel, null).create().show();
}

From source file:com.nttec.everychan.ui.presentation.BoardFragment.java

@SuppressLint("InflateParams")
private void runDelete(final DeletePostModel deletePostModel, final boolean hasFiles) {
    Context dialogContext = Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB
            ? new ContextThemeWrapper(activity, R.style.Theme_Neutron)
            : activity;/*from   w  w  w. j a v  a2  s  .c  om*/
    View dlgLayout = LayoutInflater.from(dialogContext).inflate(R.layout.dialog_delete, null);
    final EditText inputField = (EditText) dlgLayout.findViewById(R.id.dialog_delete_password_field);
    final CheckBox onlyFiles = (CheckBox) dlgLayout.findViewById(R.id.dialog_delete_only_files);
    inputField.setText(chan.getDefaultPassword());

    if (!presentationModel.source.boardModel.allowDeletePosts
            && !presentationModel.source.boardModel.allowDeleteFiles) {
        Logger.e(TAG, "board model doesn't support deleting");
        return;
    } else if (!presentationModel.source.boardModel.allowDeletePosts) {
        onlyFiles.setEnabled(false);
        onlyFiles.setChecked(true);
    } else if (presentationModel.source.boardModel.allowDeleteFiles && hasFiles) {
        onlyFiles.setEnabled(true);
    } else {
        onlyFiles.setEnabled(false);
    }

    DialogInterface.OnClickListener dlgOnClick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(final DialogInterface dialog, final int which) {
            if (currentTask != null)
                currentTask.cancel();
            if (pullableLayout.isRefreshing())
                setPullableNoRefreshing();
            deletePostModel.onlyFiles = onlyFiles.isChecked();
            deletePostModel.password = inputField.getText().toString();
            final ProgressDialog progressDlg = new ProgressDialog(activity);
            final CancellableTask deleteTask = new CancellableTask.BaseCancellableTask();
            progressDlg.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    deleteTask.cancel();
                }
            });
            progressDlg.setCanceledOnTouchOutside(false);
            progressDlg.setMessage(resources.getString(R.string.dialog_delete_progress));
            progressDlg.show();
            Async.runAsync(new Runnable() {
                @Override
                public void run() {
                    String error = null;
                    String targetUrl = null;
                    if (deleteTask.isCancelled())
                        return;
                    try {
                        targetUrl = chan.deletePost(deletePostModel, null, deleteTask);
                    } catch (Exception e) {
                        if (e instanceof InteractiveException) {
                            if (deleteTask.isCancelled())
                                return;
                            ((InteractiveException) e).handle(activity, deleteTask,
                                    new InteractiveException.Callback() {
                                        @Override
                                        public void onSuccess() {
                                            if (!deleteTask.isCancelled()) {
                                                progressDlg.dismiss();
                                                onClick(dialog, which);
                                            }
                                        }

                                        @Override
                                        public void onError(String message) {
                                            if (!deleteTask.isCancelled()) {
                                                progressDlg.dismiss();
                                                Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
                                                runDelete(deletePostModel, hasFiles);
                                            }
                                        }
                                    });
                            return;
                        }

                        Logger.e(TAG, "cannot delete post", e);
                        error = e.getMessage() == null ? "" : e.getMessage();
                    }
                    if (deleteTask.isCancelled())
                        return;
                    final boolean success = error == null;
                    final String result = success ? targetUrl : error;
                    Async.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (deleteTask.isCancelled())
                                return;
                            progressDlg.dismiss();
                            if (success) {
                                if (result == null) {
                                    update();
                                } else {
                                    UrlHandler.open(result, activity);
                                }
                            } else {
                                Toast.makeText(activity,
                                        TextUtils.isEmpty(result) ? resources.getString(R.string.error_unknown)
                                                : result,
                                        Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                }
            });
        }
    };
    new AlertDialog.Builder(activity).setTitle(R.string.dialog_delete_password).setView(dlgLayout)
            .setPositiveButton(R.string.dialog_delete_button, dlgOnClick)
            .setNegativeButton(android.R.string.cancel, null).create().show();
}

From source file:org.telegram.messenger.MessagesController.java

public void startSecretChat(final Context context, final TLRPC.User user) {
    if (user == null) {
        return;//from  www.  ja  v  a  2s.  co  m
    }
    final ProgressDialog progressDialog = new ProgressDialog(context);
    progressDialog.setMessage(context.getString(R.string.Loading));
    progressDialog.setCanceledOnTouchOutside(false);
    progressDialog.setCancelable(false);
    progressDialog.show();
    TLRPC.TL_messages_getDhConfig req = new TLRPC.TL_messages_getDhConfig();
    req.random_length = 256;
    req.version = MessagesStorage.lastSecretVersion;
    ConnectionsManager.Instance.performRpc(req, new RPCRequest.RPCRequestDelegate() {
        @Override
        public void run(TLObject response, TLRPC.TL_error error) {
            if (error == null) {
                TLRPC.messages_DhConfig res = (TLRPC.messages_DhConfig) response;
                if (response instanceof TLRPC.TL_messages_dhConfig) {
                    if (!Utilities.isGoodPrime(res.p, res.g)) {
                        Utilities.RunOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    if (!((ActionBarActivity) context).isFinishing()) {
                                        progressDialog.dismiss();
                                    }
                                } catch (Exception e) {
                                    FileLog.e("tmessages", e);
                                }
                            }
                        });
                        return;
                    }
                    MessagesStorage.secretPBytes = res.p;
                    MessagesStorage.secretG = res.g;
                    MessagesStorage.lastSecretVersion = res.version;
                    MessagesStorage.Instance.saveSecretParams(MessagesStorage.lastSecretVersion,
                            MessagesStorage.secretG, MessagesStorage.secretPBytes);
                }
                final byte[] salt = new byte[256];
                for (int a = 0; a < 256; a++) {
                    salt[a] = (byte) ((byte) (random.nextDouble() * 256) ^ res.random[a]);
                }

                BigInteger i_g_a = BigInteger.valueOf(MessagesStorage.secretG);
                i_g_a = i_g_a.modPow(new BigInteger(1, salt), new BigInteger(1, MessagesStorage.secretPBytes));
                byte[] g_a = i_g_a.toByteArray();
                if (g_a.length > 256) {
                    byte[] correctedAuth = new byte[256];
                    System.arraycopy(g_a, 1, correctedAuth, 0, 256);
                    g_a = correctedAuth;
                }

                TLRPC.TL_messages_requestEncryption req2 = new TLRPC.TL_messages_requestEncryption();
                req2.g_a = g_a;
                req2.user_id = getInputUser(user);
                req2.random_id = (int) (random.nextDouble() * Integer.MAX_VALUE);
                ConnectionsManager.Instance.performRpc(req2, new RPCRequest.RPCRequestDelegate() {
                    @Override
                    public void run(final TLObject response, TLRPC.TL_error error) {
                        if (error == null) {
                            Utilities.RunOnUIThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (!((ActionBarActivity) context).isFinishing()) {
                                        try {
                                            progressDialog.dismiss();
                                        } catch (Exception e) {
                                            FileLog.e("tmessages", e);
                                        }
                                    }
                                    TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat) response;
                                    chat.user_id = chat.participant_id;
                                    encryptedChats.put(chat.id, chat);
                                    chat.a_or_b = salt;
                                    TLRPC.TL_dialog dialog = new TLRPC.TL_dialog();
                                    dialog.id = ((long) chat.id) << 32;
                                    dialog.unread_count = 0;
                                    dialog.top_message = 0;
                                    dialog.last_message_date = ConnectionsManager.Instance.getCurrentTime();
                                    dialogs_dict.put(dialog.id, dialog);
                                    dialogs.add(dialog);
                                    dialogsServerOnly.clear();
                                    Collections.sort(dialogs, new Comparator<TLRPC.TL_dialog>() {
                                        @Override
                                        public int compare(TLRPC.TL_dialog tl_dialog,
                                                TLRPC.TL_dialog tl_dialog2) {
                                            if (tl_dialog.last_message_date == tl_dialog2.last_message_date) {
                                                return 0;
                                            } else if (tl_dialog.last_message_date < tl_dialog2.last_message_date) {
                                                return 1;
                                            } else {
                                                return -1;
                                            }
                                        }
                                    });
                                    for (TLRPC.TL_dialog d : dialogs) {
                                        if ((int) d.id != 0) {
                                            dialogsServerOnly.add(d);
                                        }
                                    }
                                    NotificationCenter.Instance.postNotificationName(dialogsNeedReload);
                                    MessagesStorage.Instance.putEncryptedChat(chat, user, dialog);
                                    NotificationCenter.Instance.postNotificationName(encryptedChatCreated,
                                            chat);
                                }
                            });
                        } else {
                            Utilities.RunOnUIThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (!((ActionBarActivity) context).isFinishing()) {
                                        try {
                                            progressDialog.dismiss();
                                        } catch (Exception e) {
                                            FileLog.e("tmessages", e);
                                        }
                                        AlertDialog.Builder builder = new AlertDialog.Builder(context);
                                        builder.setTitle(context.getString(R.string.AppName));
                                        builder.setMessage(String.format(
                                                context.getString(R.string.CreateEncryptedChatOutdatedError),
                                                user.first_name, user.first_name));
                                        builder.setPositiveButton(
                                                ApplicationLoader.applicationContext.getString(R.string.OK),
                                                null);
                                        builder.show().setCanceledOnTouchOutside(true);
                                    }
                                }
                            });
                        }
                    }
                }, null, true,
                        RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors);
            } else {
                Utilities.RunOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!((ActionBarActivity) context).isFinishing()) {
                            try {
                                progressDialog.dismiss();
                            } catch (Exception e) {
                                FileLog.e("tmessages", e);
                            }
                        }
                    }
                });
            }
        }
    }, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors);
}