如果ProgressDialog未显示(安卓)

3

我有一个ProgressDialog,当对话框消失时,我想要执行一些操作(但我不想在progressdialog.dismiss之后执行我的操作)。

是否有可能:

                               ----> if No ---> Do something     
    Check if dialog is showing
                               ----> if Yes 
             /|\                       |
              |                       \|/
               ---------------------  Wait

不要想得太复杂,我只想执行一个操作,但前提是没有对话框存在,如果有对话框,则会在对话框完成后执行该操作。

编辑:我的活动:

import verymuchimportshere..
public class ScroidWallpaperGallery extends Activity {

private WallpaperGalleryAdapter wallpaperGalleryAdapter;
private final WallpaperManager wallpaperManager;
private final ICommunicationDAO communicationDAO;
private final IFavouriteDAO favouriteDAO;
private final List<Integer> preloadedList;
private Wallpaper selectedWallpaper;

private static final int PICK_CONTACT = 0;
private static final int DIALOG_ABOUT = 0;

public ScroidWallpaperGallery() {
    super();

    if (!DependencyInjector.isInitialized()) {
        DependencyInjector.init(this);  
    }

    this.wallpaperManager = DependencyInjector.getInstance(WallpaperManager.class);
    this.communicationDAO = DependencyInjector.getInstance(ICommunicationDAO.class);
    this.favouriteDAO = DependencyInjector.getInstance(IFavouriteDAO.class);

    this.preloadedList = new ArrayList<Integer>();
}


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.setContentView(R.layout.main);
    this.initGallery();
    ProgressDialog progressDialog = new ProgressDialog(this);     
    progressDialog.setMessage(this.getString(R.string.loadingText));
    if (progressDialog.isShowing()) {
          progressDialog.dismiss();
        }
    else {
    SharedPreferences settings = getSharedPreferences("firstrun", MODE_PRIVATE);
    if (settings.getBoolean("isFirstRun", true)) {
        new AlertDialog.Builder(this).setTitle("How to").setMessage("Long press item to add/remove from favorites.").setNeutralButton("Ok", null).show();
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean("isFirstRun", false);
        editor.commit();
    }
    }
    if (this.wallpaperGalleryAdapter != null) {
        this.updateGalleryAdapter();

        return;
    }

    AdView adView = (AdView)this.findViewById(R.id.adView);
    adView.loadAd(new AdRequest());

    new FillGalleryTask(progressDialog, this).start();
}

private void updateGalleryAdapter() {
    this.updateGalleryAdapter(this.wallpaperManager.getWallpapers());
}

private synchronized void updateGalleryAdapter(Wallpaper[] wallpapers) {
    this.wallpaperGalleryAdapter = new WallpaperGalleryAdapter(this, wallpapers, this.wallpaperManager);

    Gallery gallery = (Gallery)this.findViewById(R.id.gallery);
    gallery.setAdapter(this.wallpaperGalleryAdapter);
}

private void initGallery() {
    Gallery gallery = (Gallery)this.findViewById(R.id.gallery);

    gallery.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {                  
            Wallpaper wallpaper = (Wallpaper)parent.getItemAtPosition(position);

            showPreviewActivity(wallpaper);
        }
    });
    gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, final int position, long id) {
            selectedWallpaper = (Wallpaper)wallpaperGalleryAdapter.getItem(position);

            new Thread(new Runnable() {

                @Override
                public void run() {
                    preloadThumbs(wallpaperGalleryAdapter.getWallpapers(), (position + 1), 3);
                }
            }).start();
        }
        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            selectedWallpaper = null;
        } 
    });

    this.registerForContextMenu(gallery);
}

private void showPreviewActivity(Wallpaper wallpaper) {
    WallpaperPreviewActivity.showPreviewActivity(this, wallpaper);
}

private void preloadThumbs(Wallpaper[] wallpapers, int index, int maxCount) {
    for (int i = index; (i < (index + maxCount)) && (i < wallpapers.length); i++) {
        if (this.preloadedList.contains(i)) {
            continue;
        }

        try {
            this.wallpaperManager.getThumbImage(wallpapers[i]);

            this.preloadedList.add(i);
        }
        catch (ClientProtocolException ex) {
            // nothing to do - image will be loaded on select
        }
        catch (IOException ex) {
            // nothing to do - image will be loaded on select
        }
    }
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    if (this.selectedWallpaper == null
            || !(v instanceof Gallery)) {
        return;
    }

    MenuInflater menuInflater = new MenuInflater(this);
    menuInflater.inflate(R.menu.gallery_context_menu, menu);

    if (this.favouriteDAO.isFavourite(this.selectedWallpaper.getId())) {
        menu.findItem(R.id.galleryRemoveFavouriteMenuItem).setVisible(true);
    }
    else {
        menu.findItem(R.id.galleryAddFavouriteMenuItem).setVisible(true);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater menuInflater = getMenuInflater();
    menuInflater.inflate(R.menu.main_menu, menu);

    return true;
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    if (this.selectedWallpaper == null) {
        return false;
    }

    switch (item.getItemId()) {
        case R.id.galleryAddFavouriteMenuItem:
            this.favouriteDAO.add(this.selectedWallpaper.getId());
            return true;

        case R.id.galleryRemoveFavouriteMenuItem:
            this.favouriteDAO.remove(this.selectedWallpaper.getId());
            return true;
    }

    return false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.aboutMenuItem:
            this.showDialog(DIALOG_ABOUT);
            return true;

        case R.id.settingsMenuItem:
            this.startActivity(new Intent(this, SettingsActivity.class));
            return true;

        case R.id.recommendMenuItem:
            this.recommendWallpaper();
            return true;

        case R.id.favouritesMenuItem:
            FavouriteListActivity.showFavouriteListActivity(this);
            return true;

        case R.id.closeMenuItem:
            this.finish();
            return true;
    }

    return false;
}
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
        case DIALOG_ABOUT:
            return new AboutDialog(this);

        default:
            return null;
    }
}

private void recommendWallpaper() {
    if (this.selectedWallpaper == null) {
        return;
    }

    Intent intent = new Intent(Intent.ACTION_PICK, People.CONTENT_URI);
    this.startActivityForResult(intent, PICK_CONTACT);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case PICK_CONTACT:
            this.onPickContactActivityResult(resultCode, data);
            break;
    }
}

private void onPickContactActivityResult(int resultCode, Intent data) {
    if (resultCode == 0) {
        return;
    }

    Communication[] communications = this.communicationDAO.getCommunications(data.getData());

    if (communications.length < 1) {
        AlertDialogFactory.showInfoMessage(this, R.string.infoText, R.string.noCommunicationFoundInfoText);

        return;
    }

    CommunicationChooseDialog dialog = new CommunicationChooseDialog(this, communications, new CommunicationChosenListener() {
        @Override
        public void onCommunicationChosen(Communication communication) {
            handleOnCommunicationChosen(communication);
        }
    });

    dialog.show();
}

private void handleOnCommunicationChosen(Communication communication) {
    Wallpaper wallpaper = this.selectedWallpaper;

    if (communication.getType().equals(Communication.Type.Email)) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.putExtra(Intent.EXTRA_EMAIL, new String[] { communication.getValue() });
        intent.putExtra(Intent.EXTRA_SUBJECT, getBaseContext().getString(R.string.applicationName));
        intent.putExtra(Intent.EXTRA_TEXT, String.format(getBaseContext().getString(R.string.recommendEmailPattern), 
                                                         wallpaper.getWallpaperUrl()));
        intent.setType("message/rfc822");

        this.startActivity(intent);                 
    }
    else if (communication.getType().equals(Communication.Type.Mobile)) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.putExtra("address", communication.getValue());
        intent.putExtra("sms_body", String.format(getBaseContext().getString(R.string.recommendSmsPattern), 
                                                  wallpaper.getWallpaperUrl()));
        intent.setType("vnd.android-dir/mms-sms");

        this.startActivity(intent);
    }
}


private class FillGalleryTask extends LongTimeRunningOperation<Wallpaper[]> {

    private final Context context;
    public FillGalleryTask(Dialog progressDialog, Context context) {
        super(progressDialog);

        this.context = context;
    }

    @Override
    public void afterOperationSuccessfullyCompleted(Wallpaper[] result) {
        updateGalleryAdapter(result);
    }
    @Override
    public void handleUncaughtException(Throwable ex) {
        if (ex instanceof WallpaperListReceivingException) {
            AlertDialogFactory.showErrorMessage(this.context, 
                                                R.string.errorText, 
                                                ex.getMessage(), 
                                                new ShutDownAlertDialogOnClickListener());
        } 
        else if (ex instanceof IOException) {
            AlertDialogFactory.showErrorMessage(this.context,
                                                R.string.errorText, 
                                                R.string.downloadException, 
                                                new ShutDownAlertDialogOnClickListener());
        }
        else {
            throw new RuntimeException(ex);
        }
    }

    @Override
    public Wallpaper[] onRun() throws Exception {
        // retrieving available wallpapers from server
        wallpaperManager.loadAvailableWallpapers(getBaseContext());

        Wallpaper[] wallpapers = wallpaperManager.getWallpapers();

        // preloading first 3 thumbs
        preloadThumbs(wallpapers, 0, 3);

        return wallpapers;
    }
}

private class ShutDownAlertDialogOnClickListener implements DialogInterface.OnClickListener {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();

        finish();
    }
}
}

你在哪里展示这个进度对话框?请展示你现有的代码。 - Aleks G
2个回答

5

试一下这个:

private void doSomethingWhenProgressNotShown() {
    if (mProgressDialog != null && mProgressDialog.isShowing()) {
        //is running
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                doSomethingWhenProgressNotShown();
            }
        }, 500);
    }
    //isnt running- do something here
}

欢迎。请尝试给一个赞,这样可以帮助其他人哦。 :) - Sagar Waghmare

4
我认为您可以使用这段代码:

    if (mProgressDialog != null && mProgressDialog.isShowing()) {
        //is running
    }
        //isnt running

或者您可以设置监听器:

mProgressDialog.setOnCancelListener(listener);
mProgressDialog.setOnDismissListener(listener);

谢谢您的回答,但是如果我使用您的第一个答案,我的代码将根本无法运行,因为我希望在对话框消失时执行操作。不过我会尝试您的第二个答案。 - Mdlc
或者您可以使用 mProgressDialog.setCancelable(false);,这样用户就无法在不停止活动的情况下取消对话框。 - Bullman
第二种方法是正确的做法。 - TronicZomB

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接