Android -- 双屏异显之方法一:MediaRouter
PS:
1. 部分主板可能不支持,得验证;
2. 副屏输出可以不用连接显示屏也能正常后台运行;
3. 主屏Activity内控制副屏;
4. 副屏截图命令:
screencap -p -d 1 <path_name>;(-d 1 副屏截屏)
使用方法:
java
//主屏activity内
private MediaRouter mMediaRouter;
private SecondDisplay secondDisplay;
//控制副屏显隐
public void onSecondChange(View view) {
if (secondDisplay == null) {
showSecondScreen();
} else {
closeSecondScreen();
}
}
//====================================
private void showSecondScreen() {
if (secondDisplay != null) {
return;
}
mMediaRouter = (MediaRouter) getSystemService(Context.MEDIA_ROUTER_SERVICE);
updatePresentation();
}
private void closeSecondScreen() {
if (secondDisplay != null) {
secondDisplay.release();
secondDisplay.dismiss();
secondDisplay = null;
}
}
private void updatePresentation() {
// Get the current route and its presentation display.
MediaRouter.RouteInfo route = mMediaRouter.getSelectedRoute(MediaRouter.ROUTE_TYPE_LIVE_VIDEO);
Display presentationDisplay = route != null ? route.getPresentationDisplay() : null;
// Dismiss the current presentation if the display has changed.
if (secondDisplay != null && secondDisplay.getDisplay() != presentationDisplay) {
secondDisplay.dismiss();
secondDisplay = null;
}
// Show a new presentation if needed.
if (secondDisplay == null && presentationDisplay != null) {
secondDisplay = new SecondDisplay(this, presentationDisplay);
secondDisplay.setOnDismissListener(mOnDismissListener);
try {
secondDisplay.show();
} catch (WindowManager.InvalidDisplayException ex) {
secondDisplay = null;
ex.printStackTrace();
}
}
}
//副屏关闭监听
private final DialogInterface.OnDismissListener mOnDismissListener = new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
if (dialog == secondDisplay) {
secondDisplay = null;
}
}
};
SecondDisplay.java (副屏类)
java
//主要继承Presentation类
public class SecondDisplay extends Presentation {
private static final String TAG = "SecondDisplay";
private Context mContext;
//构造函数
public SecondDisplay(Context outerContext, Display display) {
super(outerContext, display);
this.mContext = outerContext;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//副屏布局,与activity内一样
setContentView(R.layout.layout_second);
initUI();
}
private void initUI() {
//绑定控件
}
public void release() {
//关闭页面前注销资源
}
}