Want to add 360 VR functionality in your android app? It’s very simple, just follow along and your app will have the required functionality in no time!
We will use the VrPanoramaView provided by Google in its VR SDK.
Steps to add 360 VR functionality in Android App
- Add the following dependency in your app.gradle file:
1 |
compile 'com.google.vr:sdk-panowidget:1.80.0' |
- In your XML file add VrPanoramaView.
1 2 3 4 5 6 |
<com.google.vr.sdk.widgets.pano.VrPanoramaView android:id="@+id/vrPanoramaView" android:layout_width="match_parent" android:layout_height="wrap_content"> </com.google.vr.sdk.widgets.pano.VrPanoramaView> |
- In your activity file, reference to the VrPanoramaView.
1 2 3 4 5 |
private VrPanoramaView mVRPanoramaView; ... mVRPanoramaView = (VrPanoramaView) findViewById(R.id.vrPanoramaView); |
- We need to implement all the lifecycle methods for VrPanoramaView, particularly onPause, onResume and onDestroy.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
@Override void onPause() { super.onPause() mVRPanoramaView.pauseRendering() } @Override void onResume() { super.onResume() mVRPanoramaView.resumeRendering() } @Override void onDestroy() { mVRPanoramaView.shutdown() super.onDestroy() } |
- Now, comes the main part, Loading photo! In this tutorial we will download a 360 degree photo and place it inside the assets folder. Your can fetch the required photo from where ever required, be it from an API, file or whatever, doesn’t matter, the code will remain the same. Go download any 360 degree photo, you can get a lot of them by doing a simple google search. Place the photo in the assets folder.
- Below is the code for loading the image from asset. VrPanoramaView takes input as Bitmap so we need to first convert it into right format. Here, the loadPhotoSphere functions in called in onCreate().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
private void loadPhotoSphere() { VrPanoramaView.Options options = new VrPanoramaView.Options(); InputStream inputStream = null; AssetManager assetManager = getAssets(); try { inputStream = assetManager.open("image.jpg"); options.inputType = VrPanoramaView.Options.TYPE_MONO; mVRPanoramaView.loadImageFromBitmap(BitmapFactory.decodeStream(inputStream), options); inputStream.close(); } catch (Exception e) { e.printStackTrace(); } } |