Reputation: 1201
I have a VideoView and a TextView on the same activity. Here s the xml for the layout.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rellayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<VideoView
android:id="@+id/videoview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:padding="5dp" />
<TextView
android:id="@+id/numberTicker"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/purple"
android:textStyle="bold"
android:gravity="top|right"
android:textSize="35dp"
android:maxEms="3"/>
</RelativeLayout>
As soon as the video start playing I wish to display a number on the numberTicker text view. Mind you the numbers are likely to change 4 times per second. Anyway, the primary issue I have is to identify that the video has started playing and to keep updating the TextView.
My attempt :
vid = (VideoView) findViewById(R.id.videoview);
ratings = (TextView) findViewById(R.id.ratingTicker);
vid.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
vid.start();
vid.postDelayed(onEveryQuarterSecond,250);
}
});
...
...
private Runnable onEveryQuarterSecond = new Runnable() {
Random r = new Random();
int uVal, aVal;
@Override
public void run() {
ratings.setText(Integer.toString(r.nextInt()));
}
};
The code Runnable would only run once, and never get updated. Am I missing something?
Thanks for the help!
Upvotes: 0
Views: 464
Reputation: 3479
Consider to use a new Thread to not block the main UI Thread:
public void updateEverySecond() {
new Thread(new Runnable() {
@Override
public void run() {
while (mediaPlayer.isPlaying()) {
try {
ratings.setText(Integer.toString(r.nextInt()));
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
}
Upvotes: 0
Reputation: 9778
You get a MediaPlayer
object in onPrepared()
. You could use that like this:
vid.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
this.mediaPlayer = mp; //have mediaPlayer be a class variable
vid.start();
vid.postDelayed(onEveryQuarterSecond,250);
}
});
private Runnable onEveryQuarterSecond = new Runnable() {
Random r = new Random();
int uVal, aVal;
@Override
public void run() {
while(mediaPlayer.isPlaying()) {
ratings.setText(Integer.toString(r.nextInt()));
Thread.sleep(250);
}
}
};
Upvotes: 1