简体   繁体   中英

How to make Thread in android run infinitely

   Runnable updateSeekbar=new Runnable() {
    @Override
    public void run() {
        try{
            while (true) {
                if (!isPlayerDead) {
                    Log.d("Threads", "Thread is running successfully.");
                    int progress=mediaPlayer.getCurrentPosition();
                    seekBar.setProgress(progress);
                    Log.d("Seekbar",seekBar.getProgress()+"");
                    Log.d("MediaProgress",mediaPlayer.getCurrentPosition()+"");
                    String s=modifyTime(mediaPlayer.getCurrentPosition() / 1000 / 60) + ":" + modifyTime((mediaPlayer.getCurrentPosition() / 1000) % 60);
                    progressTime.setText(s);

                }
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
};
Executor executor=new Executor() {
    @Override
    public void execute(Runnable command) {
        Thread thread=new Thread(command);
        thread.start();
    }
};

executor.execute(updateSeekbar);

Actually the problem is that the thread dies before the mediaplayer can send updated position. I have made the thread in an endless while loop but still it dies. How can I make it run infinitely till the activity gets destroyed. The thread only runs for a couple of seconds and then dies. I want it to run infinitely till the activity gets destroyed. All suggestions are welcome.

when mediaPlayer isn't in proper state and you try to call some improper method then some Exception may be thrown, and you are catching it OUTside while(true) loop. try to move try{}catch inside while(true) , then your Thread will run infinitely

@Override
public void run() {
    while (true) {
        try{
            if (!isPlayerDead) {
            
            // current code
            
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        SystemClock.sleep(20); // some bonus line
    } // end of while
}

btw. give some rest for UI between iterations, eg by putting SystemClock.sleep(20); after every calculation (last line before closing bracket). you don't need so often progress refreshing, in current code it may happen even few times more often than system is capable to draw (in most often 60Hz case)

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