java - 安卓把new thread写在onCreate()里面不会运行?
ringa_lee
ringa_lee 2017-04-17 17:11:52
0
4
859

今天写了一个线程在onCreate里面,结果它不运行。我犯错了??

这个子线程在哪里开start(),有关系吗?我以为无论在哪里开了,它就是特立独行的了??

新手,理解不是很全....

你觉得呢?

public void onCreate() {
        super.onCreate();
        player = new MediaPlayer();
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {

                mListener.onNextPlay(true);

            }
        });

        new Thread() {


            @Override
            public void run() {

                final int millis = 100;

                try {
                    sleep(millis);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if (player.isPlaying() && player != null) {
                    mListener.onPlaying(player.getCurrentPosition(), player.getDuration());

                    Log.i("ddd", Integer.toString(player.getCurrentPosition()));

                }

            }
        }.start();

    }

Log.i("ddd", Integer.toString(player.getCurrentPosition()));

这句没有信息弹出,如果歌曲播放了,它会不断输出播放进度的数字才是....

====================================
经过添加log,得知这个线程是一开始就运行的,但是sleep一次后,就好像没有醒过来一样....没信息输出

====================================
解决疑惑:能运行,就是要加一个while循环......

ringa_lee
ringa_lee

ringa_lee

reply all(4)
阿神

onCreate is only run once when creating the activity, and this thread has ended when it runs the last line of the run.
I am also a newbie, please correct me if there are any mistakes.

大家讲道理

It will definitely be implemented. But if you call the same object in different threads, you need to carefully check whether there is a competition relationship. Whether synchronization protection is required.

大家讲道理

Log at the beginning of the run function to determine whether it is running

巴扎黑

Ah, I should write a while loop...

new Thread() {


            @Override
            public void run() {

                Log.i("ddd", "running");

                final int millis = 100;
                
                while (true) {

                    try {

                        sleep(millis);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if (player.isPlaying() && player != null) {
                        mListener.onPlaying(player.getCurrentPosition(), player.getDuration());

                        Log.i("ddd", Integer.toString(player.getCurrentPosition()));

                    }

                }



            }

        }.start();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template