Android TV 开发之 TV视频播放器
不想往下看可以直接在GitHub上面克隆到自己的项目中
GitHub地址
最近公司又给了一个新任务,说要做电视机顶盒开发,这个机顶盒开发之前也没有接触过啊,没经验,这使我走了很多坑,写这个日志就是帮助和自己一样的新手开发代码顺利一些,少走弯路,如果你是有经验的,请无视我的废话和文章,因为我将从创建项目开始写这篇日志,这意味着会比较无聊,你要有心理准备,当然如果你是一个新手的话,恰好最近又要做AndroidTV的开发,那么你就来对地方了,好了,话不多说了,进入正题吧。
简介Android TV 开发,顾名思义也就是电视开发,说的高端点就是智能电视,相信你们家里都有吧,不要说你家至今用着十几年前的老电视,那我无法可说了,TV开发的资源我从网上找到的都是一些零零碎碎的,不够完整,而有一些项目还要你给积分才能去下载看,不够开源,痛定思痛,我决定自己弄一个开源的项目出来,自己来维护,学习中开发,也有可能TV这方面的文章我还会写,也有可能只写这一篇,接下来我们从创建TV项目开始。
正题开发准备:
电脑(笔记本、台式都行)、JDK环境变量配置(PS:因为是Java写的,想了解Kotlin的可以和我沟通)、Android Studio3.5(开发软件)。
创建项目:
第一步:File → New → New Project
第二步:选择TV 然后创建一个空的项目也就是点左边的 Add No Activity(PS:为什么不用谷歌的框架呢,因为这个第一次我觉得自己从头来一遍会比较好,这样更有帮助,后面你再用这个框架,而且这个空项目进去之后在,AndroidManifest.xml里面还是要添加leanback的,下面继续吧)
布局很简单,纵向线性布局,里面是一个TextView和Button,然后我们换成横屏的布局预览效果
@color/colorPrimary
@color/colorPrimaryDark
@color/colorAccent
然后你会发现少几个颜色,这时候我们在values文件夹下面创建一个colors.xml的文件
colors.xml代码如下:
#008577
#00574B
#D81B60
#1EBADE
然后就要使用我们新创建的主题了,打开AndroidManifest.xml文件
布局文件
注释已经加在布局文件里面了,下面就不过多讲述了,布局文件中的自定义VideoView代码如下:
package com.llw.androidtvdemo.view;
import android.content.Context;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.VideoView;
import com.llw.androidtvdemo.view.util.SSlUtiles;
import javax.net.ssl.HttpsURLConnection;
public class MyVideoView extends VideoView {
public MyVideoView(Context context) {
super(context);
}
public MyVideoView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyVideoView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getDefaultSize(getWidth(), widthMeasureSpec);
int height = getDefaultSize(getHeight(), heightMeasureSpec);
setMeasuredDimension(width, height);
}
@Override
public void setVideoURI(Uri uri) {
super.setVideoURI(uri);
try {
HttpsURLConnection.setDefaultSSLSocketFactory(SSlUtiles.createSSLSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new SSlUtiles.TrustAllHostnameVerifier());
} catch (Exception e) {
e.printStackTrace();
}
}
}
自定义VideoView中SSlUtils网络证书许可类代码如下:
package com.llw.androidtvdemo.view.util;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class SSlUtils {
public static SSLSocketFactory createSSLSocketFactory() {
SSLSocketFactory sSLSocketFactory = null;
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, new TrustManager[] { (TrustManager) new TrustAllManager() }, new SecureRandom());
sSLSocketFactory = sc.getSocketFactory();
} catch (Exception e) {
}
return sSLSocketFactory;
}
public static class TrustAllManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
public static class TrustAllHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
}
这个类主要是针对于 VideoView 无法播放此视频 问题,如果你没有这个问题的话,可以在MyVideoView去掉下面这一段代码:
@Override
public void setVideoURI(Uri uri) {
super.setVideoURI(uri);
try {
HttpsURLConnection.setDefaultSSLSocketFactory(SSlUtils.createSSLSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new SSlUtils.TrustAllHostnameVerifier());
} catch (Exception e) {
e.printStackTrace();
}
}
然后来看MainActivity中的代码,通过注解的方式我的控件已经不需要声明和findById了。
首先配置一下我们的VideoVIew
private void initVideo() {
//本地视频
// videoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/raw/test"));
//网络视频
final Uri uri = Uri.parse("http://gslb.miaopai.com/stream/ed5HCfnhovu3tyIQAiv60Q__.mp4");
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
int totalTime = videoView.getDuration();//获取视频的总时长
tvTotalTime.setText(stringForTime(totalTime));//设置视频总时间,stringForTime是写的一个时间装换方法,下面会提到
// 开始线程,更新进度条的刻度
handler.postDelayed(runnable, 0);
timeSeekBar.setMax(videoView.getDuration());
//视频加载完成,准备好播放视频的回调
videoView.start();
}
});
}
上面的初始化中用到了一个线程,线程代码如下:
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
public void run() {
if (videoView.isPlaying()) {
int current = videoView.getCurrentPosition();//获取播放过程中位置
timeSeekBar.setProgress(current);//设置进度条的位置
tvPlayTime.setText(time(videoView.getCurrentPosition()));//播放过程中的时间
}
handler.postDelayed(runnable, 500);//播放过程中0.5秒执行一次
}
};
然后是onCreate()方法
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);//注释然后自动添加的
timeSeekBar.setOnSeekBarChangeListener(onSeekBarChangeListener);//添加进度条的变化监听
initVideo();//初始化VideoView
//videoView播放完成监听
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
key = 1;//这是一个全局变量,用于控制遥控单击确定或者ok键时,是暂停继续还是重新播放,1则是重新播放视频
btnRestartPlay.setVisibility(View.VISIBLE);//显示黑色背景,布局文件中注释提到了
layFinishBg.setVisibility(View.VISIBLE);//显示白色重播图标,布局文件中注释提到了
}
});
//videoView播放异常监听,类似于 此视频无法播放 这样的错误提示
videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(MainActivity.this, "播放出错", Toast.LENGTH_SHORT).show();
return false;
}
});
}
代码中用到的一个方法:
protected String time(long millionSeconds) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
Calendar c = Calendar.getInstance();
c.setTimeInMillis(millionSeconds);
return simpleDateFormat.format(c.getTime());
}
控制视频是 播放还是暂停 或者是重播
private void isVideoPlay(boolean isPlay, int keys) {
switch (keys) {
case 0:
if (isPlay) {//暂停
btnPlayOrPause.setBackground(getResources().getDrawable(R.mipmap.icon_player));//更换按钮的图标并显示出来
btnPlayOrPause.setVisibility(View.VISIBLE);
videoView.pause();
} else {//继续播放
btnPlayOrPause.setBackground(getResources().getDrawable(R.mipmap.icon_pause));//更换按钮的图标并显示出来
btnPlayOrPause.setVisibility(View.VISIBLE);
// 开始线程,更新进度条的刻度
handler.postDelayed(runnable, 0);
videoView.start();//继续播放
timeSeekBar.setMax(videoView.getDuration());
timeGone();//当我们选择继续播放之后,就不能让这个图标一直显示下去,但是又不能马上消失,这样很突兀,所以用了延时1.5秒隐藏,比较合理,这个方法后面会贴出来。
}
break;
case 1://重新播放
initVideo();
btnRestartPlay.setVisibility(View.GONE);//白色重播图标隐藏
layFinishBg.setVisibility(View.GONE);//黑色背景隐藏
key = 0;//重新播放之后,我们再将key置为0,这样就不会影响到下一次视频播放过程中的暂停和继续的监听操作了
break;
}
延时1.5秒隐藏
private void timeGone() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
btnPlayOrPause.setVisibility(View.INVISIBLE);
}
}, 1500);
}
进度条监听
private SeekBar.OnSeekBarChangeListener onSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
// 当进度条停止修改的时候触发
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// 取得当前进度条的刻度
int progress = seekBar.getProgress();
if (videoView.isPlaying()) {
// 设置当前播放的位置
videoView.seekTo(progress);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
}
};
时间转换方法
//将长度转换为时间
StringBuilder mFormatBuilder = new StringBuilder();
Formatter mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
//整数类型转换为时分秒
private String stringForTime(int timeMs) {
int totalSeconds = timeMs / 1000;
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
mFormatBuilder.setLength(0);
if (hours > 0) {
return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return mFormatter.format("%02d:%02d", minutes, seconds).toString();
}
}
遥控器按键监听
private String TAG = "key";
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER: //确定键enter
case KeyEvent.KEYCODE_DPAD_CENTER:
Log.d(TAG, "enter--->");
//如果是播放中则暂停、如果是暂停则继续播放
isVideoPlay(videoView.isPlaying(), key);
break;
case KeyEvent.KEYCODE_BACK: //返回键
Log.d(TAG,"back--->");
return true; //这里由于break会退出,所以我们自己要处理掉 不返回上一层
case KeyEvent.KEYCODE_SETTINGS: //设置键
Log.d(TAG, "setting--->");
break;
case KeyEvent.KEYCODE_DPAD_DOWN: //向下键
if (event.getAction() == KeyEvent.ACTION_DOWN) {
Log.d(TAG, "down--->");
}
break;
case KeyEvent.KEYCODE_DPAD_UP: //向上键
Log.d(TAG, "up--->");
break;
case KeyEvent.KEYCODE_DPAD_LEFT: //向左键
Log.d(TAG, "left--->");
if (videoView.getCurrentPosition() > 4) {
videoView.seekTo(videoView.getCurrentPosition() - 5 * 1000);
}
break;
case KeyEvent.KEYCODE_DPAD_RIGHT: //向右键
Log.d(TAG, "right--->");
videoView.seekTo(videoView.getCurrentPosition() + 5 * 1000);
break;
case KeyEvent.KEYCODE_VOLUME_UP: //调大声音键
Log.d(TAG, "voice up--->");
break;
case KeyEvent.KEYCODE_VOLUME_DOWN: //降低声音键
Log.d(TAG, "voice down--->");
break;
case KeyEvent.KEYCODE_VOLUME_MUTE: //禁用声音
Log.d(TAG, "voice mute--->");
break;
default:
break;
}
return super.onKeyDown(keyCode, event);
}
前进后退的控制都这个遥控器监听里面。
MainActivity的完整代码如下:
package com.llw.androidtvdemo;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.llw.androidtvdemo.view.MyVideoView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Formatter;
import java.util.Locale;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity {
@BindView(R.id.video_view)
MyVideoView videoView;
@BindView(R.id.tv_play_time)
TextView tvPlayTime;
@BindView(R.id.time_seekBar)
SeekBar timeSeekBar;
@BindView(R.id.tv_total_time)
TextView tvTotalTime;
@BindView(R.id.lay_finish_bg)
RelativeLayout layFinishBg;
@BindView(R.id.btn_play_or_pause)
ImageButton btnPlayOrPause;
@BindView(R.id.btn_restart_play)
ImageButton btnRestartPlay;
private int key = 0;
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
public void run() {
if (videoView.isPlaying()) {
int current = videoView.getCurrentPosition();
timeSeekBar.setProgress(current);
tvPlayTime.setText(time(videoView.getCurrentPosition()));
}
handler.postDelayed(runnable, 500);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
timeSeekBar.setOnSeekBarChangeListener(onSeekBarChangeListener);
initVideo();
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
key = 1;
btnRestartPlay.setVisibility(View.VISIBLE);
layFinishBg.setVisibility(View.VISIBLE);
}
});
videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(MainActivity.this, "播放出错", Toast.LENGTH_SHORT).show();
return false;
}
});
}
protected String time(long millionSeconds) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
Calendar c = Calendar.getInstance();
c.setTimeInMillis(millionSeconds);
return simpleDateFormat.format(c.getTime());
}
private void initVideo() {
//本地视频
// videoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/raw/test"));
//网络视频
final Uri uri = Uri.parse("http://gslb.miaopai.com/stream/ed5HCfnhovu3tyIQAiv60Q__.mp4");
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
int totalTime = videoView.getDuration();//获取视频的总时长
tvTotalTime.setText(stringForTime(totalTime));
// 开始线程,更新进度条的刻度
handler.postDelayed(runnable, 0);
timeSeekBar.setMax(videoView.getDuration());
//视频加载完成,准备好播放视频的回调
videoView.start();
}
});
}
private void isVideoPlay(boolean isPlay, int keys) {
switch (keys) {
case 0:
if (isPlay) {//暂停
btnPlayOrPause.setBackground(getResources().getDrawable(R.mipmap.icon_player));
btnPlayOrPause.setVisibility(View.VISIBLE);
videoView.pause();
} else {//继续播放
btnPlayOrPause.setBackground(getResources().getDrawable(R.mipmap.icon_pause));
btnPlayOrPause.setVisibility(View.VISIBLE);
// 开始线程,更新进度条的刻度
handler.postDelayed(runnable, 0);
videoView.start();
timeSeekBar.setMax(videoView.getDuration());
timeGone();
}
break;
case 1://重新播放
initVideo();
btnRestartPlay.setVisibility(View.GONE);
layFinishBg.setVisibility(View.GONE);
key = 0;
break;
}
}
private void timeGone() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
btnPlayOrPause.setVisibility(View.INVISIBLE);
}
}, 1500);
}
private SeekBar.OnSeekBarChangeListener onSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
// 当进度条停止修改的时候触发
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// 取得当前进度条的刻度
int progress = seekBar.getProgress();
if (videoView.isPlaying()) {
// 设置当前播放的位置
videoView.seekTo(progress);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
}
};
//将长度转换为时间
StringBuilder mFormatBuilder = new StringBuilder();
Formatter mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
private String stringForTime(int timeMs) {
int totalSeconds = timeMs / 1000;
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
mFormatBuilder.setLength(0);
if (hours > 0) {
return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return mFormatter.format("%02d:%02d", minutes, seconds).toString();
}
}
private String TAG = "key";
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER: //确定键enter
case KeyEvent.KEYCODE_DPAD_CENTER:
Log.d(TAG, "enter--->");
//如果是播放中则暂停、如果是暂停则继续播放
isVideoPlay(videoView.isPlaying(), key);
break;
case KeyEvent.KEYCODE_BACK: //返回键
Log.d(TAG,"back--->");
return true; //这里由于break会退出,所以我们自己要处理掉 不返回上一层
case KeyEvent.KEYCODE_SETTINGS: //设置键
Log.d(TAG, "setting--->");
break;
case KeyEvent.KEYCODE_DPAD_DOWN: //向下键
if (event.getAction() == KeyEvent.ACTION_DOWN) {
Log.d(TAG, "down--->");
}
break;
case KeyEvent.KEYCODE_DPAD_UP: //向上键
Log.d(TAG, "up--->");
break;
case KeyEvent.KEYCODE_DPAD_LEFT: //向左键
Log.d(TAG, "left--->");
if (videoView.getCurrentPosition() > 4) {
videoView.seekTo(videoView.getCurrentPosition() - 5 * 1000);
}
break;
case KeyEvent.KEYCODE_DPAD_RIGHT: //向右键
Log.d(TAG, "right--->");
videoView.seekTo(videoView.getCurrentPosition() + 5 * 1000);
break;
case KeyEvent.KEYCODE_VOLUME_UP: //调大声音键
Log.d(TAG, "voice up--->");
break;
case KeyEvent.KEYCODE_VOLUME_DOWN: //降低声音键
Log.d(TAG, "voice down--->");
break;
case KeyEvent.KEYCODE_VOLUME_MUTE: //禁用声音
Log.d(TAG, "voice mute--->");
break;
default:
break;
}
return super.onKeyDown(keyCode, event);
}
}
运行效果如下:
播放结束再按确定键就可以重新播放了。
GitHub地址
如有问题请留言,定当第一时间回复您,感谢你的阅读,后会有期~
作者:初学者—Study
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341