Android的,的AsyncTask,检查状态?状态、Android、AsyncTask

2023-09-14 00:06:26 作者:我去你马勒戈壁·

这是我的code:

在的onCreate:

In onCreate:

 new LoadMusicInBackground().execute();

然后对我的主要课程结束后我有这个code

Then towards the end of my main class I have this code

/** Helper class to load all the music in the background. */
class LoadMusicInBackground extends AsyncTask<Void, String, Void> {
    @Override
    protected Void doInBackground(Void... unused) {

        soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 100);
        soundPoolMap = new HashMap<Integer, Integer>();

        soundPoolMap.put(A1,
                soundPool.load(GameScreen_bugfix.this, R.raw.a, 1));
        soundPoolMap.put(A3,
                soundPool.load(GameScreen_bugfix.this, R.raw.b, 1));
        soundPoolMap.put(A5,
                soundPool.load(GameScreen_bugfix.this, R.raw.c_s, 1));
        soundPoolMap.put(A6,
                soundPool.load(GameScreen_bugfix.this, R.raw.d, 1));
        soundPoolMap.put(A8,
                soundPool.load(GameScreen_bugfix.this, R.raw.e, 1));
        soundPoolMap.put(A10,
                soundPool.load(GameScreen_bugfix.this, R.raw.f_s, 1));
        soundPoolMap.put(A12,
                soundPool.load(GameScreen_bugfix.this, R.raw.g_s, 1));
        soundPoolMap.put(wrong,
                soundPool.load(GameScreen_bugfix.this, R.raw.wrong2, 1));

        publishProgress("");
        Log.v("SOUNDPOOL", "" + soundPoolMap);
        return (null);
    }

    @Override
    protected void onProgressUpdate(String... item) {
        // text1.setText(item[0]);
    }

    @Override
    protected void onPostExecute(Void unused) {
        //Toast.makeText(GameScreen_bugfix.this, "music loaded!", Toast.LENGTH_SHORT).show();
    }
}

如果音乐没有加载我得到一个空指针异常,看着我看到有一个的getStatus(该文档),但我已经试过这样的事情:

If the music has not loaded I am getting a nullpointer exception, looking at the docs I see there is a getStatus() but I have tried something like this:

music_load_status=LoadMusicInBackground.getStatus()

和不工作:( 我如何检查,如果后台任务完成和音乐加载?

and that is not working :( How do I check if the background task is complete and the music has loaded?

谢谢! 瑞安

推荐答案

的getStatus()检查是否在的AsyncTask 挂起,运行,或成品。

getStatus() checks whether the the AsyncTask is pending, running, or finished.

LoadMusicInBackground lmib = new LoadMusicInBackground();

if(lmib.getStatus() == AsyncTask.Status.PENDING){
    // My AsyncTask has not started yet
}

if(lmib.getStatus() == AsyncTask.Status.RUNNING){
    // My AsyncTask is currently doing work in doInBackground()
}

if(lmib.getStatus() == AsyncTask.Status.FINISHED){
    // My AsyncTask is done and onPostExecute was called
}

如果您要检查你的动作居然成功(即成功加载音乐),那么你需要拿出你自己的方法来确定。该的getStatus()只能确定在的AsyncTask 实际线程的状态。

If you want to check if your action actually succeeded (i.e. the music was successfully loaded), then you need to come up with your own method that determines that. The getStatus() can only determine the state of the actual thread in AsyncTask.