我有MediaPlayer
播放文件,我想在后台连续写入日志数据。这应该由Thread
(或类似的概念,但我不知道AsyncTask
是否是这里的方式)来完成。线程不应该总是写,而是在两者之间暂停半秒。
我的MediaPlayer
工作正常,但是一旦我尝试运行我的线程,就不会显示任何视频。线程似乎正在运行。
以下是相关代码:
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();
}
}
}
这是我为视频准备播放器并创建Thread实例的地方。
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();
}
这是从onPreparedListener
。
public void startVideo() {
mIsVideoPlaying = true;
mLoggingThread.run();
mPlayer.start();
}
从输出中看,线程运行正常,但为什么播放器没有显示任何视频?
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.
...
答案 0 :(得分:1)
您应该启动Thread
对象并将Runnable
添加到其中:
public void startVideo() {
mIsVideoPlaying = true;
new Thread(mLoggingThread).start();
mPlayer.start();
}
调用Runnable#run()
将在当前线程上运行代码,而不是创建新代码。