это правильная асинхронная задача? - PullRequest
2 голосов
/ 06 января 2012

У меня есть первый класс, экран загрузки.

 public class Loading extends Activity {

public int switchscreensvalue = 0;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.loadinglayout);

    new Loadsounds().execute(switchscreensvalue);


            if (switchscreensvalue == 1)
            {
                Intent myIntent = new Intent(Loading.this, main.class);
                startActivityForResult(myIntent, 0);
            }



        }
}

Тогда у меня есть класс по асинктаске.

    public class Loadsounds extends AsyncTask<Integer, Void, Void> {

@Override
protected Void doInBackground(Integer... params) {

        SoundManager.addSound(0, R.raw.rubber);
    SoundManager.addSound(1, R.raw.metal);
    SoundManager.addSound(2, R.raw.ice);
    SoundManager.addSound(3, R.raw.wind);
    SoundManager.addSound(4, R.raw.fire);

    return null;
}


protected void onPostExecute(Integer...params){
    int switchscreensvalue = 1;
}

 }

Я хочу, чтобы он запустил asynctask, который загружает 5 звуков в деку, и когда это будет сделано, измените int "switchscreensvalue" на 1. Затем экран загрузки должен измениться на главный экран, когда "switchscreensvalue" = 1. Это не работает, хотя. Пожалуйста, кто-нибудь может мне помочь, просто изучая асинктические задачи в первый раз. На самом деле все еще довольно плохо знаком с Java. Мне нужна асинхронная задача, чтобы загрузить 5 звуков, а затем изменить действие с загрузки на основное действие.

Ответы [ 4 ]

3 голосов
/ 06 января 2012

Это потому, что вы звоните

 if (switchscreensvalue == 1)
        {
            Intent myIntent = new Intent(Loading.this, main.class);
            startActivityForResult(myIntent, 0);
        }

в свой onCreate (), который вы не можете гарантировать, будет вызван снова.

Почему вы не звоните

 if (switchscreensvalue == 1)
        {
            Intent myIntent = new Intent(Loading.this, main.class);
            startActivityForResult(myIntent, 0);
        }

В вашем onPostExecute () после того, как вы установите переменную в порядке.

2 голосов
/ 06 января 2012

Это должно работать ...

public class Loading extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loadinglayout);

        new Loadsounds().execute();
    }

    public void startMainActivity() {
        Intent myIntent = new Intent(this, Main.class);
        startActivityForResult(myIntent, 0);
    }

    private class Loadsounds extends AsyncTask<Void, Void, Boolean> {
        boolean success = false;

        @Override
        protected Void doInBackground(Void... params) {
            // Load sounds here and set success = true if successful
        }
        return success;

        @Override
        protected void onPostExecute(Boolean...result) {
            if (result)
                startMainActivity();
        }
    }
)
1 голос
/ 06 января 2012

Ваш почти там ... Потерять переменную ...

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.loadinglayout);
    new Loadsounds().execute(switchscreensvalue);
}


//                                       <Params, Progress, Result>
public class Loadsounds extends AsyncTask<Integer, Integer, Integer> {

@Override
protected Void doInBackground(Integer... params) {

    int result = 0;
    try {
        SoundManager.addSound(0, R.raw.rubber);
        SoundManager.addSound(1, R.raw.metal);
        SoundManager.addSound(2, R.raw.ice);
        SoundManager.addSound(3, R.raw.wind);
        SoundManager.addSound(4, R.raw.fire);
        result = 1;
    } catch(Exception e){
        // some error handling if SoundManager.addSound throws exceptions?
    }

    return result; // positive integer on success
}


protected void onPostExecute(Integer result){
    if (!isCancelled() && (result != null) && (result > 0)
    {
        // int someResult = 0;
        Intent myIntent = new Intent(Loading.this, main.class);
        // should the following line be startActivity? 
        // difference between startActivity and startActivityForResult 
        // is that the latter returns an integer value where your zero is
        //startActivityForResult(myIntent, 0);
        startActivityForResult(myIntent, someResult);

        // Alternatively, just...
        // startActivity(myIntent);
    } else {
        // Log error, inform user, then close application?
    }

}

}
0 голосов
/ 06 января 2012

Я думаю, что вы пытаетесь сказать, что это не переключение активности?Я слышал, что вы говорите о области, вы уверены, что оба класса находятся в одном файле?т. е. один класс (LoadingTask) внутри другого (класс загрузки)?

попробуйте переключить «Loading.this» на «getApplication ()»

У меня есть

public class Loading extends Activity {
protected void onCreate(...){
    ... (As in above answer)
}

// LoadTask exists inside the Loading activity class
private class LoadTask extends AsyncTask<Integer, Integer, Integer>     {
    protected Integer doInBackground(Integer... params) {
        ... (As in above answer)
    }

    protected void onPostExecute(Integer result) {
        super.onPostExecute(result);
        try {
            Intent intent = new Intent(Loading.this, Main.class);
            // Alternatively
            // Intent intent = new Intent(getApplication(), Main.class);
            startActivity(intent);
        } catch (ActivityNotFoundException e){
            // Exception handling code
        }
    } 
}
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...