最近公司要求在Android触摸设备上通过hdmi接口连接外置显示器,实现双屏异现功能,打开软件后外置显示器播放动画,触摸设备则可以进行其他的用户交互。捣鼓了好几天这东西,现在和大家分享一下
首先你的安卓设备需要支持双屏异现功能,然后就可以进行代码的编写了(这里主要通过DisplayManager和Presentation来实现)
1. 新建一个 MyPresentation类继承Presentation,
public class MyPresentation extends Presentation {
Context context;
@BindView(R.id.video)
VideoView myVideoView;
public MyPresentation(Context outerContext, Display display) {
super(outerContext, display);
this.context = outerContext;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.presentation_my);
ButterKnife.bind(this);
final String file = "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4";
myVideoView.setVideoPath(file);
myVideoView.start();
}
}
注释:Presentation就是Dialog类的扩展,它提供了一块区域可以显示不同于主屏幕的内容。这里我放了一个VideoView播放网络上的一个视频
2.新建一个MyApplication类继承Application
public class MposApplication extends Application {
private MyPresentation mPresentation;
private Display[] displays; //定义一个屏幕数组
private static MposApplication sMPosApplication;
public static MposApplication getInstance() {
return sMPosApplication;
}
@Override
public void onCreate() {
sMPosApplication = this;
DisplayManager mDisplayManager;// 屏幕管理类
mDisplayManager = (DisplayManager) this
.getSystemService(Context.DISPLAY_SERVICE);
displays = mDisplayManager.getDisplays();
super.onCreate();
}
public MyPresentation showExternalAd(Context context) {
if (mPresentation == null) {
mPresentation = new MyPresentation(context, displays[displays.length - 1]);// displays[1]是副屏 displays[0]是主屏
mPresentation.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
mPresentation.show();
return mPresentation;
} else {
return null;
}
}
}
3. 在 MainActivity的oncreate中添加一句代码
MposApplication.getInstance().showExternalAd(this);
4. 在AndroidManifest.xml中添加自定义的Application
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.loadingtest.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
荆轲刺秦王,大功已告成