Example usage for android.app ProgressDialog dismiss

List of usage examples for android.app ProgressDialog dismiss

Introduction

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

Prototype

@Override
public void dismiss() 

Source Link

Document

Dismiss this dialog, removing it from the screen.

Usage

From source file:com.koushikdutta.superuser.MainActivity.java

void doSystemInstall() {
    final ProgressDialog dlg = new ProgressDialog(this);
    dlg.setTitle(R.string.installing);//w w w.  j a  v a 2 s. c  o m
    dlg.setMessage(getString(R.string.installing_superuser));
    dlg.setIndeterminate(true);
    dlg.show();
    new Thread() {
        public void run() {
            boolean _error = false;
            try {
                final File su = extractSu();
                final String command = "mount -orw,remount /system\n" + "rm /system/xbin/su\n"
                        + "rm /system/bin/su\n" + "rm /system/app/Supersu.*\n" + "rm /system/app/superuser.*\n"
                        + "rm /system/app/supersu.*\n" + "rm /system/app/SuperUser.*\n"
                        + "rm /system/app/SuperSU.*\n"
                        + String.format("cat %s > /system/xbin/su\n", su.getAbsolutePath())
                        + "chmod 6755 /system/xbin/su\n" + "ln -s /system/xbin/su /system/bin/su\n"
                        + "mount -oro,remount /system\n" + "sync\n";
                Process p = Runtime.getRuntime().exec("su");
                p.getOutputStream().write(command.getBytes());
                p.getOutputStream().close();
                if (p.waitFor() != 0)
                    throw new Exception("non zero result");
                SuHelper.checkSu(MainActivity.this);
            } catch (Exception ex) {
                _error = true;
                Log.e("Superuser", "error upgrading", ex);
            }
            dlg.dismiss();
            final boolean error = _error;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.setTitle(R.string.install);

                    if (error) {
                        builder.setMessage(R.string.install_error);
                    } else {
                        builder.setMessage(R.string.install_success);
                    }
                    builder.create().show();
                }
            });
        };
    }.start();
}

From source file:net.vexelon.myglob.fragments.HomeFragment.java

/**
 * Get selected spinner option and update view
 *//*  ww w .  j  a  v a 2  s  . com*/
public void updateStatus(Operations operation) {
    if (Defs.LOG_ENABLED)
        Log.v(Defs.LOG_TAG, "updateStatus with opId= " + operation.getId());

    View v = this.getView();

    final FragmentActivity activity = getActivity();

    if (UsersManager.getInstance().size() > 0) {

        final Operations finalOperation = operation;
        final TextView tvContent = (TextView) v.findViewById(R.id.tv_status_content);
        final TextView tvPhoneNumber = (TextView) v.findViewById(R.id.tv_profile_number);
        final String phoneNumber = (String) tvPhoneNumber.getText();

        // show progress
        final ProgressDialog myProgress = ProgressDialog.show(activity,
                getResString(R.string.dlg_progress_title), getResString(R.string.dlg_progress_message), true);

        new Thread() {
            public void run() {
                try {
                    User user = UsersManager.getInstance().getUserByPhoneNumber(phoneNumber);

                    final ActionResult actionResult = new AccountStatusAction(activity, finalOperation, user)
                            .execute();

                    // remember last account and operation
                    GlobalSettings.getInstance().setLastSelectedPhoneNumber(phoneNumber);
                    GlobalSettings.getInstance().setLastSelectedOperation(finalOperation);

                    // update text field
                    activity.runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            tvContent.setText(Html.fromHtml(actionResult.getString()));
                            updateProfileView(phoneNumber);
                        }
                    });

                    // close progress bar dialog
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            myProgress.dismiss();
                        }
                    });

                } catch (ActionExecuteException e) {
                    Log.e(Defs.LOG_TAG, "Error updating status!", e);

                    // close progress bar dialog
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            myProgress.dismiss();
                        }
                    });

                    // Show error dialog
                    if (e.isErrorResIdAvailable()) {
                        Utils.showAlertDialog(activity, e.getErrorResId(), e.getErrorTitleResId());
                    } else {
                        Utils.showAlertDialog(activity, e.getMessage(), getResString(e.getErrorTitleResId()));
                    }
                }
            };
        }.start();
    } else {
        // show add user screen
        Toast.makeText(this.getActivity().getApplicationContext(), R.string.text_account_add_new,
                Toast.LENGTH_SHORT).show();

    }
}

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

@Override
public View createView(Context context) {
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    actionBar.setTitle(LocaleController.getString("PrivacySettings", R.string.PrivacySettings));
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override//from  w  ww. j  av a  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(AdapterView<?> adapterView, View view, final int i, long l) {
            if (i == blockedRow) {
                presentFragment(new BlockedUsersActivity());
            } else if (i == sessionsRow) {
                presentFragment(new SessionsActivity());
            } else if (i == deleteAccountRow) {
                if (getParentActivity() == null) {
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setTitle(LocaleController.getString("DeleteAccountTitle", R.string.DeleteAccountTitle));
                builder.setItems(
                        new CharSequence[] { LocaleController.formatPluralString("Months", 1),
                                LocaleController.formatPluralString("Months", 3),
                                LocaleController.formatPluralString("Months", 6),
                                LocaleController.formatPluralString("Years", 1) },
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                int value = 0;
                                if (which == 0) {
                                    value = 30;
                                } else if (which == 1) {
                                    value = 90;
                                } else if (which == 2) {
                                    value = 182;
                                } else if (which == 3) {
                                    value = 365;
                                }
                                final ProgressDialog progressDialog = new ProgressDialog(getParentActivity());
                                progressDialog
                                        .setMessage(LocaleController.getString("Loading", R.string.Loading));
                                progressDialog.setCanceledOnTouchOutside(false);
                                progressDialog.setCancelable(false);
                                progressDialog.show();

                                final TLRPC.TL_account_setAccountTTL req = new TLRPC.TL_account_setAccountTTL();
                                req.ttl = new TLRPC.TL_accountDaysTTL();
                                req.ttl.days = value;
                                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() {
                                                try {
                                                    progressDialog.dismiss();
                                                } catch (Exception e) {
                                                    FileLog.e("tmessages", e);
                                                }
                                                if (response instanceof TLRPC.TL_boolTrue) {
                                                    ContactsController.getInstance()
                                                            .setDeleteAccountTTL(req.ttl.days);
                                                    listAdapter.notifyDataSetChanged();
                                                }
                                            }
                                        });
                                    }
                                });
                            }
                        });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showDialog(builder.create());
            } else if (i == lastSeenRow) {
                presentFragment(new PrivacyControlActivity(false));
            } else if (i == groupsRow) {
                presentFragment(new PrivacyControlActivity(true));
            } else if (i == passwordRow) {
                presentFragment(new TwoStepVerificationActivity(0));
            } else if (i == passcodeRow) {
                if (UserConfig.passcodeHash.length() > 0) {
                    presentFragment(new PasscodeActivity(2));
                } else {
                    presentFragment(new PasscodeActivity(0));
                }
            } else if (i == secretWebpageRow) {
                if (MessagesController.getInstance().secretWebpagePreview == 1) {
                    MessagesController.getInstance().secretWebpagePreview = 0;
                } else {
                    MessagesController.getInstance().secretWebpagePreview = 1;
                }
                ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE)
                        .edit().putInt("secretWebpage2", MessagesController.getInstance().secretWebpagePreview)
                        .commit();
                if (view instanceof TextCheckCell) {
                    ((TextCheckCell) view)
                            .setChecked(MessagesController.getInstance().secretWebpagePreview == 1);
                }
            }
        }
    });

    return fragmentView;
}

From source file:com.esri.android.ecologicalmarineunitexplorer.map.MapFragment.java

private final void setUpMap(View root) {

    // Show a dialog while the map loads
    final ProgressDialog progressDialog = ProgressDialog.show(this.getActivity(), null, "Loading map data...",
            true);/*from w  w  w.j  a  v  a2s .  c o  m*/

    mMapView = (MapView) root.findViewById(R.id.map);

    // Create a map using Ocean basemap and
    // zoom to Galapagos Islands
    mMap = new ArcGISMap(Basemap.Type.OCEANS, -0.3838312, -91.5727346, 4);

    mMapView.setMap(mMap);

    // Create and add layers that need to be visible in the map
    mGraphicOverlay = new GraphicsOverlay();
    mMapView.getGraphicsOverlays().add(mGraphicOverlay);

    // EMU Ocean Surface
    ArcGISTiledLayer tiledLayerBaseMap = new ArcGISTiledLayer(getString(R.string.emu_ocean_surface_layer));
    mMap.getOperationalLayers().add(tiledLayerBaseMap);

    final MapTouchListener mapTouchListener = new MapTouchListener(getActivity().getApplicationContext(),
            mMapView);

    // Once map has loaded, remove the progress dialog
    // and enable touch listener
    mMapView.addDrawStatusChangedListener(new DrawStatusChangedListener() {
        @Override
        public void drawStatusChanged(DrawStatusChangedEvent drawStatusChangedEvent) {
            if (drawStatusChangedEvent.getDrawStatus() == DrawStatus.COMPLETED) {
                // Stop listening to any more draw status changes
                mMapView.removeDrawStatusChangedListener(this);
                // Start listening to touch interactions on the map
                mMapView.setOnTouchListener(mapTouchListener);
                progressDialog.dismiss();
            }
        }
    });

    // When map's layout is changed, re-center map on selected point
    mMapView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
        @Override
        public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop,
                int oldRight, int oldBottom) {
            if (mSelectedPoint != null) {
                mMapView.setViewpointCenterAsync(mSelectedPoint, 5000000);
            }
        }
    });

}

From source file:nf.frex.android.FrexActivity.java

private void setWallpaper() {
    final WallpaperManager wallpaperManager = WallpaperManager.getInstance(FrexActivity.this);
    final int desiredWidth = wallpaperManager.getDesiredMinimumWidth();
    final int desiredHeight = wallpaperManager.getDesiredMinimumHeight();

    final Image image = view.getImage();
    final int imageWidth = image.getWidth();
    final int imageHeight = image.getHeight();

    final boolean useDesiredSize = desiredWidth > imageWidth || desiredHeight > imageHeight;

    DialogInterface.OnClickListener noListener = new DialogInterface.OnClickListener() {
        @Override/*from  w  w  w  .  ja va  2  s . c  o  m*/
        public void onClick(DialogInterface dialog, int which) {
            // ok
        }
    };

    if (useDesiredSize) {
        showYesNoDialog(this, R.string.set_wallpaper,
                getString(R.string.wallpaper_compute_msg, desiredWidth, desiredHeight),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        final Image wallpaperImage;
                        try {
                            wallpaperImage = new Image(desiredWidth, desiredHeight);
                        } catch (OutOfMemoryError e) {
                            alert(getString(R.string.out_of_memory));
                            return;
                        }

                        final ProgressDialog progressDialog = new ProgressDialog(FrexActivity.this);

                        Generator.ProgressListener progressListener = new Generator.ProgressListener() {
                            int numLines;

                            @Override
                            public void onStarted(int numTasks) {
                            }

                            @Override
                            public void onSomeLinesComputed(int taskId, int line1, int line2) {
                                numLines += 1 + line2 - line1;
                                progressDialog.setProgress(numLines);
                            }

                            @Override
                            public void onStopped(boolean cancelled) {
                                progressDialog.dismiss();
                                if (!cancelled) {
                                    setWallpaper(wallpaperManager, wallpaperImage);
                                }
                            }
                        };
                        final Generator wallpaperGenerator = new Generator(view.getGeneratorConfig(),
                                SettingsActivity.NUM_CORES, progressListener);

                        DialogInterface.OnCancelListener cancelListener = new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                if (progressDialog.isShowing()) {
                                    progressDialog.dismiss();
                                }
                                wallpaperGenerator.cancel();
                            }
                        };
                        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                        progressDialog.setCancelable(true);
                        progressDialog.setMax(desiredHeight);
                        progressDialog.setOnCancelListener(cancelListener);
                        progressDialog.show();

                        Arrays.fill(wallpaperImage.getValues(), FractalView.MISSING_VALUE);
                        wallpaperGenerator.start(wallpaperImage, false);
                    }
                }, noListener, null);
    } else {
        showYesNoDialog(this, R.string.set_wallpaper, getString(R.string.wallpaper_replace_msg),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setWallpaper(wallpaperManager, image);
                    }
                }, noListener, null);
    }
}

From source file:org.csploit.android.WifiScannerActivity.java

private void performCracking(final Keygen keygen, final ScanResult ap) {

    final ProgressDialog dialog = ProgressDialog.show(this, "", getString(R.string.generating_keys), true,
            false);/*from  w  w w . ja  va 2 s .co  m*/

    new Thread(new Runnable() {
        @Override
        public void run() {
            dialog.show();

            try {
                List<String> keys = keygen.getKeys();

                if (keys == null || keys.size() == 0) {
                    WifiScannerActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            new ErrorDialog(getString(R.string.error),
                                    keygen.getErrorMessage().isEmpty() ? getString(R.string.wifi_error_keys)
                                            : keygen.getErrorMessage(),
                                    WifiScannerActivity.this).show();
                        }
                    });
                } else {
                    mCurrentAp = ap;
                    mKeyList = keys;

                    nextConnectionAttempt();
                }
            } catch (Exception e) {
                System.errorLogging(e);
            } finally {
                dialog.dismiss();
            }
        }
    }).start();
}

From source file:com.example.android.foodrecipes.app.RecipeDetailsFragment.java

private void saveCurrentRecipeInFavorites() {
    String title = getActivity().getString(R.string.text_please_wait);
    String text = getActivity().getString(R.string.text_saving_in_favorites);

    final ProgressDialog dialog = ProgressDialog.show(getActivity(), title, text);
    final BitmapDrawable bitmapDrawable = (BitmapDrawable) mRecipeImage.getDrawable();

    dialog.show();//from  w  w  w.  ja v  a 2s .c  o  m

    final AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            ContentValues cv = new ContentValues();
            cv.put(COLUMN_EXTERNAL_ID, mRecipe.getExternalId());
            cv.put(COLUMN_TITLE, mRecipe.getTitle());
            cv.put(COLUMN_IMAGE_URL, mRecipe.getImageUrl());
            cv.put(COLUMN_SOCIAL_RANK, mRecipe.getSocialRank());
            cv.put(COLUMN_SOURCE_URL, mRecipe.getSourceUrl());
            cv.put(COLUMN_INGREDIENTS, buildIngredientsString(mRecipe.getIngredients()));

            if (PrefsUtil.shouldSaveRecipeImages(getActivity())) {
                Bitmap bitmap = bitmapDrawable.getBitmap();
                if (bitmap != null) {
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                    cv.put(COLUMN_IMAGE_CONTENT, stream.toByteArray());
                }
            }

            getActivity().getContentResolver().insert(CONTENT_URI, cv);

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            dialog.dismiss();
            Toast.makeText(getActivity(), getActivity().getString(R.string.recipe_saved_in_favorites),
                    Toast.LENGTH_SHORT).show();

            mFavoritesActionButton.setEnabled(false);
        }
    };

    dialog.setOnKeyListener(new Dialog.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                task.cancel(true);
                dialog.dismiss();
            }
            return true;
        }
    });

    task.execute();
}

From source file:com.wpi.assistments.HomeTabbedActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_webview);

    final ProgressDialog pd = ProgressDialog.show(this, "", "Loading...", true);

    isTeacher = false;/* ww w. ja  v  a 2 s .c om*/
    toggle = true;
    logoutFlag = false;

    homeWebView = (WebView) findViewById(R.id.homeWebView);
    homeWebView.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String url) {
            Log.i("test", view.getUrl());
            if (view.getUrl().equals("https://www.assistments.org/account/login") && !logoutFlag) {

                Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
                intent.putExtra("showPopup", "true");
                startActivity(intent);
                finish();
            } else if (view.getUrl().equals("https://www.assistments.org/teacher")) {
                isTeacher = true;
            } else if (view.getUrl().equals("https://www.assistments.org/account/login") && logoutFlag) {
                Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
                startActivity(intent);
            }

            if (!homeWebView.canGoBack()) {
                btnBack.setEnabled(false);
            } else {
                btnBack.setEnabled(true);
            }

            if (!homeWebView.canGoForward()) {
                btnForward.setEnabled(false);
            } else {
                btnForward.setEnabled(true);
            }

            if (pd.isShowing() && pd != null) {
                pd.dismiss();
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            pd.show();
            view.loadUrl(url);
            return true;
        }
    });
    homeWebView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
            new AlertDialog.Builder(webviewContext).setTitle("ASSISTments").setMessage(message)
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            logoutFlag = true;
                            result.confirm();
                        }
                    }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            result.cancel();
                        }
                    }).create().show();

            return true;
        }
    });

    if (savedInstanceState != null) {
        homeWebView.restoreState(savedInstanceState);
    } else {
        /** Scaling, replaced by overview mode and wide view port
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        if (size.x <= 780) {
           int scaleRate = (int) ((size.x) / 7.8);
           Log.i("test", Integer.toString(size.x));
           homeWebView.setInitialScale(scaleRate);
        }
        */

        Intent intent = getIntent();

        if (intent.getStringExtra("username").equals("") && intent.getStringExtra("password").equals("")) {
            homeWebView.loadUrl("https://www.assistments.org/signup");

        } else {
            String username = intent.getStringExtra("username");
            String password = intent.getStringExtra("password");

            String postData = "login=" + username + "&password=" + password + "&commit=Log in";
            homeWebView.postUrl("https://www.assistments.org/account/login",
                    EncodingUtils.getBytes(postData, "BASE64"));
        }

    }

    WebSettings settings = homeWebView.getSettings();
    settings.setSaveFormData(false);
    settings.setSavePassword(false);
    settings.setJavaScriptEnabled(true);
    settings.setBuiltInZoomControls(true);
    settings.setDisplayZoomControls(false);
    settings.setJavaScriptCanOpenWindowsAutomatically(true);
    settings.setSupportMultipleWindows(true);
    settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    settings.setAppCacheEnabled(false);
    settings.setDomStorageEnabled(true);
    settings.setDatabaseEnabled(true);
    settings.setUseWideViewPort(false);
    settings.setLoadWithOverviewMode(true);
    homeWebView.clearCache(true);
    homeWebView.setPadding(0, 0, 0, 0);
    homeWebView.setInitialScale(getScale());

    btnBack = (Button) findViewById(R.id.btnBack);
    btnBack.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            homeWebView.goBack();
        }
    });

    btnRefresh = (Button) findViewById(R.id.btnRefresh);
    btnRefresh.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            //homeWebView.zoomOut();
            homeWebView.scrollTo(1000, 0);
            Log.i("test", "111");
            //homeWebView.reload();
        }
    });

    btnForward = (Button) findViewById(R.id.btnForward);
    btnForward.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            homeWebView.goForward();
        }
    });

    btnOffline = (Button) findViewById(R.id.btnOffline);
    btnOffline.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (toggle) {
                homeWebView.loadUrl(
                        "https://www.assistments.org/assistments/student/index.html#offlineUserAssignmentList/");
                btnOffline.setText("Home");
                toggle = false;
            } else {
                if (isTeacher) {
                    homeWebView.loadUrl("https://www.assistments.org/teacher");
                } else {
                    homeWebView.loadUrl("https://www.assistments.org/tutor");
                }
                btnOffline.setText("Offline");
                toggle = true;
            }

        }
    });
}

From source file:com.mobicage.rogerthat.registration.RegistrationActivity2.java

private void tryConnect(final ProgressDialog pd, final int attempt, final String statusMessage,
        final RegistrationInfo info) {
    T.UI();/*from   w w w.  j  a va2 s  . c o  m*/
    final Pausable pausable = this;

    if (attempt > XMPP_MAX_NUM_ATTEMPTS) {
        pd.dismiss();

        new AlertDialog.Builder(RegistrationActivity2.this).setMessage(getString(R.string.registration_error))
                .setCancelable(true).setPositiveButton(R.string.try_again, null).create().show();
        mWiz.reInit();
        mWiz.goBackToPrevious();
        return;
    }
    pd.setMessage(statusMessage + attempt);
    if (!pd.isShowing())
        pd.show();
    L.d("Registration attempt #" + attempt);

    final String xmppServiceName = info.mCredentials.getXmppServiceName();
    final String xmppAccount = info.mCredentials.getXmppAccount();
    final String xmppPassword = info.mCredentials.getPassword();

    final ConfigurationProvider cp = mService.getConfigurationProvider();
    Configuration cfg = cp.getConfiguration(RegistrationWizard2.CONFIGKEY);
    final String invitorCode = (cfg == null) ? null : cfg.get(INVITOR_CODE_CONFIGKEY, null);
    final String invitorSecret = (cfg == null) ? null : cfg.get(INVITOR_SECRET_CONFIGKEY, null);

    Runnable runnable = new SafeRunnable() {

        @Override
        public void safeRun() {
            T.REGISTRATION();
            try {

                if (CloudConstants.USE_XMPP_KICK_CHANNEL) {

                    final ConnectionConfiguration xmppConfig = new XMPPConfigurationFactory(cp,
                            mService.getNetworkConnectivityManager(), null)
                                    .getSafeXmppConnectionConfiguration(xmppServiceName);
                    final XMPPConnection xmppCon = new XMPPConnection(xmppConfig);

                    xmppCon.setLogger(new Logger() {
                        @Override
                        public void log(String message) {
                            L.d(message);
                        }
                    });
                    xmppCon.connect();
                    xmppCon.login(xmppAccount, xmppPassword);

                    final Thread t2 = new Thread(new SafeRunnable() {
                        @Override
                        protected void safeRun() throws Exception {
                            L.d("REG Before disconnect (on separate thread) - xmpp-" + xmppCon.hashCode());
                            xmppCon.disconnect();
                            L.d("REG After disconnect (on separate thread) - xmpp-" + xmppCon.hashCode());
                        }
                    });
                    t2.setDaemon(true);
                    t2.start();

                }

                postFinishRegistration(info.mCredentials.getUsername(), info.mCredentials.getPassword(),
                        invitorCode, invitorSecret);

                mUIHandler.post(new SafeRunnable(pausable) {

                    @Override
                    protected void safeRun() throws Exception {
                        T.UI();
                        mWiz.setCredentials(info.mCredentials);

                        if (CloudConstants.USE_GCM_KICK_CHANNEL && !"".equals(mGCMRegistrationId)) {
                            GoogleServicesUtils.saveGCMRegistrationId(mService, mGCMRegistrationId);
                        }

                        mService.setCredentials(mWiz.getCredentials());
                        mService.setRegisteredInConfig(true);

                        final Intent launchServiceIntent = new Intent(RegistrationActivity2.this,
                                MainService.class);
                        launchServiceIntent.putExtra(MainService.START_INTENT_JUST_REGISTERED, true);
                        launchServiceIntent.putExtra(MainService.START_INTENT_MY_EMAIL, mWiz.getEmail());
                        RegistrationActivity2.this.startService(launchServiceIntent);
                        stopRegistrationService();
                        pd.dismiss();

                        mWiz.finish(); // finish
                    }
                });

            } catch (Exception e) {
                L.d("Exception while trying to end the registration process", e);
                mUIHandler.post(new SafeRunnable(pausable) {

                    @Override
                    protected void safeRun() throws Exception {
                        T.UI();
                        tryConnect(pd, attempt + 1, statusMessage, info);
                    }
                });
            }
        }
    };
    if (attempt == 1) {
        mWorkerHandler.post(runnable);
    } else {
        mWorkerHandler.postDelayed(runnable, XMPP_CHECK_DELAY_MILLIS);
    }
}

From source file:com.microsoft.live.sample.skydrive.SkyDriveActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == FilePicker.PICK_FILE_REQUEST) {
        if (resultCode == RESULT_OK) {
            String filePath = data.getStringExtra(FilePicker.EXTRA_FILE_PATH);

            if (TextUtils.isEmpty(filePath)) {
                showToast("No file was choosen.");
                return;
            }//w  w w . j  av a2 s.  c  om

            File file = new File(filePath);

            final ProgressDialog uploadProgressDialog = new ProgressDialog(SkyDriveActivity.this);
            uploadProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            uploadProgressDialog.setMessage("Uploading...");
            uploadProgressDialog.setCancelable(true);
            uploadProgressDialog.show();

            final LiveOperation operation = mClient.uploadAsync(mCurrentFolderId, file.getName(), file,
                    new LiveUploadOperationListener() {
                        @Override
                        public void onUploadProgress(int totalBytes, int bytesRemaining,
                                LiveOperation operation) {
                            int percentCompleted = computePrecentCompleted(totalBytes, bytesRemaining);

                            uploadProgressDialog.setProgress(percentCompleted);
                        }

                        @Override
                        public void onUploadFailed(LiveOperationException exception, LiveOperation operation) {
                            uploadProgressDialog.dismiss();
                            showToast(exception.getMessage());
                        }

                        @Override
                        public void onUploadCompleted(LiveOperation operation) {
                            uploadProgressDialog.dismiss();

                            JSONObject result = operation.getResult();
                            if (result.has(JsonKeys.ERROR)) {
                                JSONObject error = result.optJSONObject(JsonKeys.ERROR);
                                String message = error.optString(JsonKeys.MESSAGE);
                                String code = error.optString(JsonKeys.CODE);
                                showToast(code + ": " + message);
                                return;
                            }

                            loadFolder(mCurrentFolderId);
                        }
                    });

            uploadProgressDialog.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    operation.cancel();
                }
            });
        }
    }
}