从内部线程开始活动

时间:2014-05-12 11:14:27

标签: android multithreading text-to-speech voice-recognition

引言

我有一个处理某些功能的活动。在这个活动中,主进程是一个处理这些函数的线程。当处理完成后,它应该调用另一个活动来启动另一个不同的进程。

这是主要活动中的主题:

CODE

private static void DetectionThread (byte[] data, int width, int height, final Context context) {

        mData = data;
        mWidth = width;
        mHeight = height;

        mThread = new Thread() {

            @Override
            public void run() {

                try {
                    //MAKES THE PROCESSING
                    //If it's right, continues to next code...

                        MotionDetectionActivity.gameStarted = true;
                        gameLaunched = true;
                        return;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    processing.set(false);

                    /*HERE MUST INIT THE ACTIVITY WITH INTENT*/
                    if (MotionDetectionActivity.gameStarted == true && gameLaunched == true) {
                        gameLaunched = false;

                        Intent gameIntent = new Intent(context, GameActivity.class);
                        context.startActivity(gameIntent);
                    }
                    processing.set(false);
                }
            }
        };
        if (MotionDetectionActivity.gameStarted == false) {
            mThread.start();
        }
}

问题

嗯,问题是我没有得到理想的结果。初始化GameActivity时,它没有显示此活动的布局,并且有一些功能未初始化,例如。我这样做是为了初始化TTS:

private static TextToSpeech tts;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.game);

    tts = new TextToSpeech(this, this);

//Iniside main method
tts.speak("Initializing...", TextToSpeech.QUEUE_ADD, null);

事情是它不会说话。

1 个答案:

答案 0 :(得分:2)

使用AsyncTask而不是Thread,并在onPostExecute方法中调用另一个活动

    public class MyAsync extends AsyncTask<Void, Void, Void>
        {
            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
//start the next activity here
            }

            @Override
            protected Void doInBackground(Void... params) {
//your task goes here
                return null;
            }

    }