简体   繁体   中英

Android: Progress Dialog with AsyncTask

Since the game requires TTS, and need quite a long time to load, I would like to implement Progress Dialog (PD), as either in the following ways:

Implement AsyncTask in Game Index Page:

This will show the PD, but the PD is freezed, ie the looping circle inside the PD is not looping.

    buttonC.setOnClickListener(new OnClickListener() 
    {  
        @Override
        public void onClick(View v) 
        {
            new initialize_game().execute();
        }
    }); 


private class initialize_game extends AsyncTask<String,Integer,String> 
{
    @Override
    protected void onPreExecute()
    {           
        dialog= new ProgressDialog(Index_game.this);
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        dialog.setMessage("Loading!\nPlease wait...");
        dialog.show();
    }

    @Override
    protected String doInBackground(String... params) 
    {            
        buttonC.setBackgroundColor(getResources().getColor(R.color.tran_black));
        Intent intent = new Intent(Index_game.this, Game_star_intro.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        startActivityForResult(intent, 0);
        overridePendingTransition(0, 0); // 0 for no animation
        Index_game.this.finish();   
        return "Done!";
    }

    protected void onPostExecute(String result) 
    {

        super.onPostExecute(result);
        Log.i("result","" +result);
        if(result!=null)
        {
            dialog.dismiss();
        }      
    }
}

AsyncTask for TTS:

Once clicked from the Game Index Page, no PD is shown until the Game is loaded fully, and at that time then the PD pops up and off for a millisecond, ie even worse than that above.

private class MainFrameTask extends AsyncTask<String,Integer,String> implements OnInitListener, OnUtteranceCompletedListener
{
    private Index_game_card_intro mainFrame = null;  

    public MainFrameTask(Index_game_card_intro mainFrame)
    {  
        this.mainFrame = mainFrame;  
    }  

    @Override  
    protected void onCancelled() 
    {  
        stopProgressDialog();  
        super.onCancelled();  
    }  

    @Override
    protected void onPreExecute()
    {           
        startProgressDialog(); 
    }

    @Override
    protected String doInBackground(String... params) 
    {            
        // setup TTS part 1.1
          mTts = new TextToSpeech(Index_game_card_intro.this, this);  // TextToSpeech.OnInitListener



        return "Done!";
    }

    protected void onPostExecute(String result) 
    {
        stopProgressDialog();      
    }

 // setup TTS part 2    
    @Override
    public void onUtteranceCompleted(String utteranceId) 
    {  
        Log.v(TAG, "Get completed message for the utteranceId " + utteranceId);  
        lastUtterance = Integer.parseInt(utteranceId);  
    }  

// setup TTS part 3 
    @Override
    public void onInit(int status) 
    {  
        if(status == TextToSpeech.SUCCESS)  
        {  
            int result = mTts.setLanguage(Locale.US);  // <====== set speech location
            mTts.setSpeechRate((float) 0.8);
            mTts.setPitch(1.0f);
            if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED)  
            {  
                // button_header.setEnabled(false);  
            }  
            else  
            {  
                // button_header.setEnabled(true);  
                mTts.setOnUtteranceCompletedListener(this);  
            }  
        }     
    }    
}

// setup TTS part 4 
private void speakText()  
{  
    lastUtterance++;  
    if(lastUtterance >= loveArray.length)  
    {  
        lastUtterance = 0;  
    }  
    Log.v(TAG, "the begin utterance is " + lastUtterance);  
    for(int i = lastUtterance; i < loveArray.length; i++)  
    {  
        params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, String.valueOf(i));  
        mTts.speak(loveArray[i], TextToSpeech.QUEUE_ADD, params);  
        mTts.playSilence(ttsilience, TextToSpeech.QUEUE_ADD, null);
    }  
} 

Question:

I found that the Progress Dialog does not show out when Button C in the game index is pressed. However, when the Game_star_intro is finally loaded, the progress dialog pops up for a very very short time and then gone.

I would like to show the ProgressDialog when it is loading up the game, not after the game is loaded then the dialog pops for a millisecond.

In this way, I have also tried to put the load TTS in AsyncTask inside Game_star_intro , yet the result is the same: the dialog just pops up for a millisecond.

Actually how should the AsyncTask be coded?? I have followed some website like this http://karanbalkar.com/2012/10/tutorial-5-custom-progressdialog-with-asynctask/

Thanks for your time!

You shouldn't start your activity in background thread. Start it, for example, in your onClick() method. You should put only your expensive code in doInBackground() , separating it from the framework lifecycle stuff. I guess you should implement AsyncTask inside Game_star_intro class for this.

ProgressDialog is not showing probably because UI thread is freezed until the work is done.

Also, naming conventions in Java suggest name classes without underscores, ie GameStarIntro :)

If I understood correctly from your question, loading of the Game_star_intro activity takes a lot of time because you use TTS in creation of this activity. The code you use is wrong. ProgressDialog from Index_game won't be shown when another activity is running (or is being created). You should use AsyncTask in Game_star_intro activity and use TTS there. In Index_game just start Game_star_intro :

buttonC.setOnClickListener(new OnClickListener() 
{  
    @Override
    public void onClick(View v) 
    {
        Intent intent = new Intent(Index_game.this, Game_star_intro.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        startActivityForResult(intent, 0);
    }
});

And in Game_star_intro something like this

public void onCreate() {
    ...
    new TTLTask().execute();
}

private class TTLTask extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute()
    {           
        dialog= new ProgressDialog(Index_game.this);
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        dialog.setMessage("Loading!\nPlease wait...");
        dialog.show();
    }

    @Override
    protected String doInBackground(String... params) 
    {            
        //... TTS code
        return null;
    }

    protected void onPostExecute(String result) 
    {

        super.onPostExecute(result);
        Log.i("result","" +result);
        if(dialog.isShown())
        {
            dialog.dismiss();
        }      
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM