Reputation: 38682
I have a MediaPlayer
playing a file, and I want to continuously write logging data in the background. This should be done by a Thread
(or a similar concept, but I don't know if an AsyncTask
is the way to go here). The Thread shouldn't always write, but pause for half a second in between.
My MediaPlayer
works fine, but once I try to run my Thread, no video is displayed. The Thread appears to be running though.
Here's the relevant code:
public class LoggingThread implements Runnable {
String videoName;
public LoggingThread(String videoName) {
Logger.startContinuousLogCSV(videoName);
Log.d(TAG, "Created logging thread");
}
public void run() {
Log.d(TAG, "Trying to run the thread");
try {
while (mIsVideoPlaying) {
Log.d(TAG, "Video is playing. Writing rating to file.");
// write to file and Thread.sleep(500)
// problem occurs regardless of this
}
Log.d(TAG, "Video not playing anymore, stopping thread.");
} catch (Exception e) {
Logger.closeContinuousLogCSV();
}
}
}
Here's where I prepare the player for a video and create the Thread instance.
public void preparePlayerForVideo(int videoIndex) {
Log.d(TAG, "Creating new logging thread");
mLoggingThread = new LoggingThread(Session.sTracks.get(videoIndex));
mPlayer = new MediaPlayer();
// various calls to set up player, this works fine
mPlayer.setOnPreparedListener(this);
mPlayer.prepare();
}
This is called from the onPreparedListener
.
public void startVideo() {
mIsVideoPlaying = true;
mLoggingThread.run();
mPlayer.start();
}
From the output, it appears that the Thread is running fine, but why is the player not showing any video?
02-15 12:00:18.904: D/SubjectivePlayerSession(17918): Creating new logging thread
02-15 12:00:18.944: D/SubjectivePlayerSession(17918): Created logging thread
02-15 12:00:18.944: D/SubjectivePlayerSession(17918): Set data source to: /mnt/sdcard/SubjectiveMovies/pair_01-video_a-GUT_DEUTSCH.mp4
02-15 12:00:19.095: V/SubjectivePlayerSession(17918): onVideoSizeChanged called
02-15 12:00:19.095: D/SubjectivePlayerSession(17918): Running thread
02-15 12:00:19.095: D/SubjectivePlayerSession(17918): Trying to run the thread
02-15 12:00:19.095: D/SubjectivePlayerSession(17918): Video is playing. Writing rating to file.
02-15 12:00:19.605: D/SubjectivePlayerSession(17918): Video is playing. Writing rating to file.
...
Upvotes: 0
Views: 766
Reputation: 4608
You should start a Thread
object and add your Runnable
to it:
public void startVideo() {
mIsVideoPlaying = true;
new Thread(mLoggingThread).start();
mPlayer.start();
}
Calling Runnable#run()
will run the code on the current thread, instead of creating a new one.
Upvotes: 1