Situation: I'm trying to write a Google Tango application in Java that allows the user to see the tango's camera feed with virtual objects on top (i.e. a video see-through augmented reality view) AND uses Tango depth/point cloud information.
Problem: Whenever I try to enable the depth sensor on the Tango, the camera image get's very dark. When I disable the depth sensing, everything is OK. Here are some screen shots:
Google Tango with Depth information enabled:
mConfig.putBoolean(TangoConfig.KEY_BOOLEAN_DEPTH, true);
Same application with Depth information disabled:
mConfig.putBoolean(TangoConfig.KEY_BOOLEAN_DEPTH, false);
Question: How do I get a clean camera image AND enable the Tango's depth information? If pure color is not possible, can a get high contrast B/W? I suspect this is a synchronization issue, and perhaps the surface is drawn after the depth/point cloud algorithm perturbing the image. Or, the camera format is changed to support the depth sensing and is unsuitable for preview.
I'm using the Tango.setSurface technique suggested in this helpful and related post
I'm purposefully NOT using the Android's native camera APIs.
(EDIT: This post is based on Fermat update. Have not confirmed after Gauss update)
My main activity code is posted below. Full project is at this github repo
Thanks in advance!
/*
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.digitalblacksmith.tango_ar_pointcloud;
import com.google.atap.tangoservice.Tango;
import com.google.atap.tangoservice.Tango.OnTangoUpdateListener;
import com.google.atap.tangoservice.TangoConfig;
import com.google.atap.tangoservice.TangoCoordinateFramePair;
import com.google.atap.tangoservice.TangoErrorException;
import com.google.atap.tangoservice.TangoEvent;
import com.google.atap.tangoservice.TangoInvalidException;
import com.google.atap.tangoservice.TangoOutOfDateException;
import com.google.atap.tangoservice.TangoPoseData;
import com.google.atap.tangoservice.TangoXyzIjData;
import android.app.Activity;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
/**
*
* Modified Main Activity class from the Original Google Tango SDK Motion Tracking API Sample.
*
* Creates a GLSurfaceView for the OpenGL scene, which displays a cube
* Then adds a SurfaceView for the camera image. The surface is connected
* to the Tango camera. This is necessary if one wants to get point cloud
* data from the Tango AND use the camera for video-see through Augmented Reality.
*
* Lessons learned: Ensure your onPause and onResume actions are handled correctly
* in terms of disconnecting and reconnecting the Tango!! If the Tango is not
* disconnected and reconnected properly, you will get a black background and
* may think the issue is something else.
*
* #author Steve Henderson #stevehenderson
*
*/
public class PointCloudActivity extends Activity implements View.OnClickListener, SurfaceHolder.Callback {
private static final String TAG = PointCloudActivity.class.getSimpleName();
private static final int SECS_TO_MILLISECS = 1000;
private Tango mTango;
private TangoConfig mConfig;
private TextView mDeltaTextView;
private TextView mPoseCountTextView;
private TextView mPoseTextView;
private TextView mQuatTextView;
private TextView mPoseStatusTextView;
private TextView mTangoServiceVersionTextView;
private TextView mApplicationVersionTextView;
private TextView mTangoEventTextView;
private TextView mPointCountTextView;
private TextView mAverageZTextView;
private TextView mFrequencyTextView;
private float mPreviousTimeStamp;
private int mPreviousPoseStatus;
private int count;
private float mDeltaTime;
private Button mMotionResetButton;
private Button mDropBoxButton;
//private boolean mIsAutoRecovery;
//private PCRenderer mOpenGL2Renderer;
private OpenGL2PointCloudRenderer mOpenGL2Renderer;
private DemoRenderer mDemoRenderer;
private GLSurfaceView mGLView;
private SurfaceView surfaceView;
private float mXyIjPreviousTimeStamp;
private float mCurrentTimeStamp;
boolean first_initialized = false;
Surface tangoSurface;
Vector3f lastPosition;
Vector3f dropBoxPosition;
/**
* Set up the activity using OpenGL 20
*/
#SuppressWarnings("deprecation")
private void setUpOpenGL20() {
///////////////////////
//Create GLSurface
///////////////////////
// OpenGL view where all of the graphics are drawn
mGLView = new GLSurfaceView(this);
mGLView.setEGLContextClientVersion(2);
mGLView.setEGLConfigChooser(8,8,8,8,16,0);
SurfaceHolder glSurfaceHolder = mGLView.getHolder();
glSurfaceHolder.setFormat(PixelFormat.TRANSLUCENT);
////////////////////////////////////
// Instantiate the Tango service
///////////////////////////////////
mTango = new Tango(this);
// Create a new Tango Configuration and enable the MotionTrackingActivity API
mConfig = new TangoConfig();
mConfig = mTango.getConfig(TangoConfig.CONFIG_TYPE_CURRENT);
mConfig.putBoolean(TangoConfig.KEY_BOOLEAN_MOTIONTRACKING, true);
/// --->If the next property is false (disabled depth) then image ok <-------
mConfig.putBoolean(TangoConfig.KEY_BOOLEAN_DEPTH, true);
// Configure OpenGL renderer
//mRenderer = new GLClearRenderer();
int maxDepthPoints = mConfig.getInt("max_point_cloud_elements");
mOpenGL2Renderer = new OpenGL2PointCloudRenderer(maxDepthPoints);
mDemoRenderer = mOpenGL2Renderer;
mOpenGL2Renderer.setFirstPersonView();
mGLView.setRenderer(mOpenGL2Renderer);
mGLView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
//setContentView(mGLView);
try {
setTangoListeners();
} catch (TangoErrorException e) {
Toast.makeText(getApplicationContext(), R.string.TangoError, Toast.LENGTH_SHORT).show();
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), R.string.motiontrackingpermission,
Toast.LENGTH_SHORT).show();
}
//////////////////////////
// Create Camera Surface
//////////////////////////
surfaceView = new SurfaceView(this);
SurfaceHolder activitySurfaceHolder = surfaceView.getHolder();
activitySurfaceHolder.addCallback(this);
//mGLView.setZOrderOnTop(true);
setContentView(mGLView);
addContentView( surfaceView, new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT ) );
/////////////////////////
//Create UI Objects
////////////////////////
LayoutInflater inflater = getLayoutInflater();
View tmpView;
tmpView = inflater.inflate(R.layout.activity_motion_tracking, null);
getWindow().addContentView(tmpView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT));
mApplicationVersionTextView = (TextView) findViewById(R.id.appversion);
mApplicationVersionTextView.setText("OpenGL 2.0");
// Button to reset motion tracking
mMotionResetButton = (Button) findViewById(R.id.resetmotion);
// Set up button click listeners
mMotionResetButton.setOnClickListener(this);
// Button to drop position box (breadcrumb cube)
mDropBoxButton = (Button) findViewById(R.id.dropbox);
// Set up button click listeners
mDropBoxButton.setOnClickListener(this);
//mOpenGL2Renderer.setFirstPersonView();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setUpOpenGL20();
// Text views for displaying translation and rotation data
mPoseTextView = (TextView) findViewById(R.id.pose);
mQuatTextView = (TextView) findViewById(R.id.quat);
mPoseCountTextView = (TextView) findViewById(R.id.posecount);
mDeltaTextView = (TextView) findViewById(R.id.deltatime);
mTangoEventTextView = (TextView) findViewById(R.id.tangoevent);
mPointCountTextView = (TextView) findViewById(R.id.pointCount);
mAverageZTextView = (TextView) findViewById(R.id.averageZ);
mFrequencyTextView = (TextView) findViewById(R.id.frameDelta);
// Text views for the status of the pose data and Tango library versions
mPoseStatusTextView = (TextView) findViewById(R.id.status);
mTangoServiceVersionTextView = (TextView) findViewById(R.id.version);
// Display the library version for debug purposes
mTangoServiceVersionTextView.setText(mConfig.getString("tango_service_library_version"));
dropBoxPosition = new Vector3f();
lastPosition = new Vector3f();
}
private void motionReset() {
mTango.resetMotionTracking();
}
private void dropBox() {
dropBoxPosition.setTo(lastPosition);
}
#Override
protected void onPause() {
super.onPause();
Log.i(TAG, "OnPause");
try {
mTango.disconnect();
Log.i(TAG,"Pausing..TANGO disconnected");
} catch (TangoErrorException e) {
Toast.makeText(getApplicationContext(), R.string.TangoError, Toast.LENGTH_SHORT).show();
}
}
protected void onResume() {
super.onResume();
Log.i(TAG, "OnResume");
try {
//setTangoListeners();
} catch (TangoErrorException e) {
Log.e(TAG,e.toString());
} catch (SecurityException e) {
Log.e(TAG,e.toString());
}
try {
if(first_initialized)mTango.connect(mConfig);
} catch (TangoOutOfDateException e) {
Log.e(TAG,e.toString());
} catch (TangoErrorException e) {
Log.e(TAG,e.toString());
}
try {
//setUpExtrinsics();
} catch (TangoErrorException e) {
Log.e(TAG,e.toString());
} catch (SecurityException e) {
Log.e(TAG,e.toString());
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.resetmotion:
motionReset();
break;
case R.id.dropbox:
dropBox();
break;
default:
Log.w(TAG, "Unknown button click");
return;
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return false;
}
/**
* Set up the TangoConfig and the listeners for the Tango service, then begin using the Motion
* Tracking API. This is called in response to the user clicking the 'Start' Button.
*/
private void setTangoListeners() {
// Lock configuration and connect to Tango
// Select coordinate frame pair
final ArrayList<TangoCoordinateFramePair> framePairs =
new ArrayList<TangoCoordinateFramePair>();
framePairs.add(new TangoCoordinateFramePair(
TangoPoseData.COORDINATE_FRAME_START_OF_SERVICE,
TangoPoseData.COORDINATE_FRAME_DEVICE));
// Listen for new Tango data
mTango.connectListener(framePairs, new OnTangoUpdateListener() {
#Override
public void onPoseAvailable(final TangoPoseData pose) {
// Log whenever Motion Tracking enters a n invalid state
if (pose.statusCode == TangoPoseData.POSE_INVALID) {
Log.w(TAG, "Invalid State");
}
if (mPreviousPoseStatus != pose.statusCode) {
count = 0;
}
count++;
mPreviousPoseStatus = pose.statusCode;
mDeltaTime = (float) (pose.timestamp - mPreviousTimeStamp) * SECS_TO_MILLISECS;
mPreviousTimeStamp = (float) pose.timestamp;
// Update the OpenGL renderable objects with the new Tango Pose
// data
float[] translation = pose.getTranslationAsFloats();
mGLView.requestRender();
// Update the UI with TangoPose information
runOnUiThread(new Runnable() {
#Override
public void run() {
DecimalFormat threeDec = new DecimalFormat("0.000");
String translationString = "[" + threeDec.format(pose.translation[0])
+ ", " + threeDec.format(pose.translation[1]) + ", "
+ threeDec.format(pose.translation[2]) + "] ";
String quaternionString = "[" + threeDec.format(pose.rotation[0]) + ", "
+ threeDec.format(pose.rotation[1]) + ", "
+ threeDec.format(pose.rotation[2]) + ", "
+ threeDec.format(pose.rotation[3]) + "] ";
float x = (float) pose.translation[0];
float y = (float) pose.translation[1];
float z = (float) pose.translation[2];
mDemoRenderer.setCameraPosition(x-dropBoxPosition.x, y-dropBoxPosition.y, z-dropBoxPosition.z);
lastPosition.setTo(x, y, z);
float qx = (float) pose.rotation[0];
float qy = (float) pose.rotation[1];
float qz = (float) pose.rotation[2];
float qw = (float) pose.rotation[3];
mDemoRenderer.setCameraAngles(qx, qy, qz, qw);
// Display pose data on screen in TextViews
//Log.i(TAG,translationString);
mPoseTextView.setText(translationString);
mQuatTextView.setText(quaternionString);
mPoseCountTextView.setText(Integer.toString(count));
mDeltaTextView.setText(threeDec.format(mDeltaTime));
if (pose.statusCode == TangoPoseData.POSE_VALID) {
mPoseStatusTextView.setText(R.string.pose_valid);
} else if (pose.statusCode == TangoPoseData.POSE_INVALID) {
mPoseStatusTextView.setText(R.string.pose_invalid);
} else if (pose.statusCode == TangoPoseData.POSE_INITIALIZING) {
mPoseStatusTextView.setText(R.string.pose_initializing);
} else if (pose.statusCode == TangoPoseData.POSE_UNKNOWN) {
mPoseStatusTextView.setText(R.string.pose_unknown);
}
}
});
}
#Override
public void onXyzIjAvailable(final TangoXyzIjData xyzIj) {
//Log.i(TAG,"xyzijAvailable!!!!!!!!");
mCurrentTimeStamp = (float) xyzIj.timestamp;
final float frameDelta = (mCurrentTimeStamp - mXyIjPreviousTimeStamp)
* SECS_TO_MILLISECS;
mXyIjPreviousTimeStamp = mCurrentTimeStamp;
byte[] buffer = new byte[xyzIj.xyzCount * 3 * 4];
//////mGLView.requestRender();
FileInputStream fileStream = new FileInputStream(
xyzIj.xyzParcelFileDescriptor.getFileDescriptor());
try {
fileStream.read(buffer,
xyzIj.xyzParcelFileDescriptorOffset, buffer.length);
fileStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
TangoPoseData pointCloudPose = mTango.getPoseAtTime(
mCurrentTimeStamp, framePairs.get(0));
mOpenGL2Renderer.getPointCloud().UpdatePoints(buffer,
xyzIj.xyzCount);
mOpenGL2Renderer.getModelMatCalculator()
.updatePointCloudModelMatrix(
pointCloudPose.getTranslationAsFloats(),
pointCloudPose.getRotationAsFloats());
mOpenGL2Renderer.getPointCloud().setModelMatrix(
mOpenGL2Renderer.getModelMatCalculator()
.getPointCloudModelMatrixCopy());
} catch (TangoErrorException e) {
Toast.makeText(getApplicationContext(),
R.string.TangoError, Toast.LENGTH_SHORT).show();
} catch (TangoInvalidException e) {
Toast.makeText(getApplicationContext(),
R.string.TangoError, Toast.LENGTH_SHORT).show();
}
// Must run UI changes on the UI thread. Running in the Tango
// service thread
// will result in an error.
runOnUiThread(new Runnable() {
DecimalFormat threeDec = new DecimalFormat("0.000");
#Override
public void run() {
// Display number of points in the point cloud
mPointCountTextView.setText(Integer
.toString(xyzIj.xyzCount));
mFrequencyTextView.setText(""
+ threeDec.format(frameDelta));
mAverageZTextView.setText(""
+ threeDec.format(mOpenGL2Renderer.getPointCloud()
.getAverageZ()));
}
});
}
#Override
public void onTangoEvent(final TangoEvent event) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mTangoEventTextView.setText(event.eventKey + ": " + event.eventValue);
}
});
}
});
}
private void setUpExtrinsics() {
// Get device to imu matrix.
TangoPoseData device2IMUPose = new TangoPoseData();
TangoCoordinateFramePair framePair = new TangoCoordinateFramePair();
framePair.baseFrame = TangoPoseData.COORDINATE_FRAME_IMU;
framePair.targetFrame = TangoPoseData.COORDINATE_FRAME_DEVICE;
device2IMUPose = mTango.getPoseAtTime(0.0, framePair);
// mRenderer.getModelMatCalculator().SetDevice2IMUMatrix(
// device2IMUPose.getTranslationAsFloats(), device2IMUPose.getRotationAsFloats());
// Get color camera to imu matrix.
TangoPoseData color2IMUPose = new TangoPoseData();
framePair.baseFrame = TangoPoseData.COORDINATE_FRAME_IMU;
framePair.targetFrame = TangoPoseData.COORDINATE_FRAME_CAMERA_COLOR;
color2IMUPose = mTango.getPoseAtTime(0.0, framePair);
// mRenderer.getModelMatCalculator().SetColorCamera2IMUMatrix(
// color2IMUPose.getTranslationAsFloats(), color2IMUPose.getRotationAsFloats());
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Surface surface = holder.getSurface();
if (surface.isValid()) {
mTango.connectSurface(0, surface);
first_initialized=true;
mTango.connect(mConfig);
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
mTango.disconnectSurface(0);
}
}
I discovered a solution of sorts, with the help of my friends at CGUI.
In my post above, you will note that the depth camera enabled image has an underexposure error. It seems that the Tango is doing some auto-exposure on the camera image.
When I tried it during the day time, with good natural light and some added flood lights, I received better results:
Depth enabled:
Depth disabled:
So, one possible workaround/consideration when using color and depth is to carefully manage the light in the environment..This makes sense given some of the calibration routines I've seen in the Tango demo apps that call for "daylight"
UPDATE You can also select the B/W fisheye camera which might be better for low-light situations if you don't mind the lack of color and distortion:
mTango.connectSurface(2, surface); //0-->color cam; 2--> B/W fisheye
Related
recently I started learning Java, I watched a YT video where a programmer used static methods and variables to create a simple guess game using JFrame.
Afterwards I tried to implement a close/restart button, after reading some Threads I relized static methods aren´t made that for. So my question is now how do I solve my problem now. :)
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.ThreadLocalRandom;
public class main extends JFrame {
JLabel text = new JLabel("Please choose a number between 1 & 10 ");
JLabel textVersuch = new JLabel();
JButton button = new JButton("Try");
int myNumber = ThreadLocalRandom.current().nextInt(1,10+1);
JTextField textField = new JTextField();
int count = 0;
//is there a better way to hide all this information, but still keep them useable for my methods?
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.openUI(); //error occurs
}
//How do I manage to start my method openUI() to start my game?
public void openUI(){
JFrame frame = new JFrame("Program");
frame.setSize(400,400);
frame.setLocation(800,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setDefaultLookAndFeelDecorated(true);
text.setBounds(0,50,400,25);
textVersuch.setBounds(300,0,100,25);
textField.setBounds(0,150,50,25);
button.setBounds(50,150,100,25);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
String textFromTextfield = textField.getText();
int number = Integer.parseInt(textFromTextfield);
if(number<1 || number>10){
text.setText("Your number has to be between 1 & 10 ");
textField.setText("");
}else{
guess(number);
}
}catch (Exception error){
text.setText("Please enter a digit! ");
textField.setText("");
}
}});
frame.add(button);
frame.add(textField);
frame.add(text);
frame.add(textVersuch);
frame.setLayout(null);
frame.setVisible(true);
}
public void close(JFrame frame){
frame.dispose(); //here I want to close the game
}
public void guess(int number ) throws InterruptedException {
count++;
textVersuch.setText(count + " tries!");
if(number == myNumber){
text.setText("You was right! " + " You tried " + count + " time(s) :)" );
button.setText("Restart");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//How can I restart my JFrame?
}
});
} else if (count < 3) {
text.setText("Wrong guess! Retry");
if (number < myNumber){
text.setText("Your searched number is bigger than" + number );
}else {
text.setText("Your searched number is lower than" + number );
}
} else {
text.setText("Sorry, you lost the number was " + myNumber);
}
textField.setText("");
}
}
How would I move an image across an AnchorPane in JavaFX? The image should move itself over a period of time. So far I have: (view is the ImageView already in the AnchorPane)
position = 35.0;
for(int x = 0; x<11; x++){
TimeUnit.SECONDS.sleep(1);
myAnchorPane.getChildren().remove(view);
AnchorPane.setRightAnchor(view, position);
AnchorPane.setTopAnchor(view, 103.0);
myAnchorPane.getChildren().add(view);
position += 20;
}
within the initialize() method of my controller. However, this does not work since the stage appears with the image already moved.
Here is a class I create from an idea I got from tutoring a student.
You should use Javafx animation. This moves with button press, but if you
want to see the diver move right, just remove the code from inside the isRightPressed if-statement and place it outside the if-statement. Also, remove this part: * (Math.cos(Math.toRadians(rotation))).
import java.io.File;
import javafx.animation.AnimationTimer;
import javafx.event.EventHandler;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyEvent;
/**
*
* #author blj0011
*/
public class Diver {
File diverFile;
ImageView ivDiver = new ImageView();
double rotation = 0.0;
boolean isUpPressed, isDownPressed, isLeftPressed, isRightPressed;
Diver()
{
diverFile = new File("src/img/diver.png");
if(diverFile.exists())
{
Image diverImage = new Image(diverFile.toURI().toString());
ivDiver.setImage(diverImage);
}
ivDiver.setFocusTraversable(true);
ivDiver.setOnKeyPressed(new EventHandler<KeyEvent>()
{
#Override
public void handle(KeyEvent event) {
switch(event.getCode()) {
case UP: isUpPressed = true; break;
case DOWN: isDownPressed = true; break;
case LEFT: isLeftPressed = true; break;
case RIGHT: isRightPressed = true; break;
}
}
});
ivDiver.setOnKeyReleased(new EventHandler<KeyEvent>()
{
#Override
public void handle(KeyEvent event) {
switch(event.getCode()) {
case UP: isUpPressed = false; break;
case DOWN: isDownPressed = false; break;
case LEFT: isLeftPressed = false; break;
case RIGHT: isRightPressed = false; break;
}
}
});
AnimationTimer timer = new AnimationTimer(){
#Override
public void handle(long now) {
if(isUpPressed){if(rotation == -360){rotation = 0;} ivDiver.setRotate(rotation+=5);}
if(isDownPressed){if(rotation == 360){rotation = 0;} ivDiver.setRotate(rotation-=5);}
if(isLeftPressed)
{
ivDiver.setX(ivDiver.getX() - 2.0 * (Math.cos(Math.toRadians(rotation))));
ivDiver.setY(ivDiver.getY() - 2.0 * (Math.sin(Math.toRadians(rotation))));
}
if(isRightPressed)
{
System.out.println("moving diver right!");
ivDiver.setX(ivDiver.getX() + 2.0 * (Math.cos(Math.toRadians(rotation))));
ivDiver.setY(ivDiver.getY() + 2.0 * (Math.sin(Math.toRadians(rotation))));
}
}
};
timer.start();
}
ImageView getDiver()
{
return ivDiver;
}
}
You code may look something like this.
AnimationTimer timer = new AnimationTimer(){
#Override
public void handle(long now) {
System.out.println("moving diver right!");
yourImageView.setX(yourImageView.getX() + 20.0 );
//yourImageView.setY(yourImageView.getY() + 20.0 );
}
};
timer.start();
Question: Does anyone know how to get the Tango's color camera image buffer using the Tango Java (Jacobi) API onFrameAvailable() callback?
Background:
I have an augmented reality application that displays video in the background of the Tango. I've successfully created the video overlay example using the the Java API (Jacobi) following this example. My application works fine, and the video is rendered in the background properly.
As part of the application, I'd like to store a copy of the video backbuffer when the user presses a button. Therefore, I need access to the camera's RGB data.
According to the Jacobi release notes, any class desiring access to the camera RGB data should implement the new onFrameAvailable() method in the OnTangoUpdateListener. I did this, but I don't see any handle or arguments to actually get the pixels:
Java API
#Override
public void onFrameAvailable(int cameraId) {
//Log.w(TAG, "Frame available!");
if (cameraId == TangoCameraIntrinsics.TANGO_CAMERA_COLOR) {
tangoCameraPreview.onFrameAvailable();
}
}
as shown, onFrameAvailable only has one argument, and integer designating the id of the camera generating the view. Contrast this with the C-library call back, which provides access to the image buffer:
C API
TangoErrorType TangoService_connectOnFrameAvailable(
TangoCameraId id, void* context,
void (*onFrameAvailable)(void* context, TangoCameraId id,
const TangoImageBuffer* buffer));
I was expecting the Java method to have something similar to the buffer object in the C API call.
What I've Tried
I tried extending the TangoCameraPreview class and saving the image there, but I only get a black background.
public class CameraSurfaceView extends TangoCameraPreview {
private boolean takeSnapShot = false;
public void takeSnapShot() {
takeSnapShot = true;
}
/**
* Grabs a copy of the surface (which is rendering the Tango color camera)
* https://stackoverflow.com/questions/14620055/how-to-take-a-screenshot-of-androids-surface-view
*/
public void screenGrab2(){
int width = this.getWidth();
int height = this.getHeight();
long fileprefix = System.currentTimeMillis();
View v= getRootView();
v.setDrawingCacheEnabled(true);
// this is the important code :)
// Without it the view will have a dimension of 0,0 and the bitmap will be null
v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
v.layout(0, 0, width, height);
v.buildDrawingCache(true);
Bitmap image = v.getDrawingCache();
//TODO: make seperate subdirctories for each exploitation sessions
String targetPath =Environment.getExternalStorageDirectory() + "/RavenEye/Photos/";
String imageFileName = fileprefix + ".jpg";
if(!(new File(targetPath)).exists()) {
new File(targetPath).mkdirs();
}
try {
File targetDirectory = new File(targetPath);
File photo=new File(targetDirectory, imageFileName);
FileOutputStream fos=new FileOutputStream(photo.getPath());
image.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
Log.i(this.getClass().getCanonicalName(), "Grabbed an image in target path:" + targetPath);
} catch (FileNotFoundException e) {
Log.e(CameraPreview.class.getName(),"Exception " + e);
e.printStackTrace();
} catch (IOException e) {
Log.e(CameraPreview.class.getName(),"Exception " + e);
e.printStackTrace();
}
}
/**
* Grabs a copy of the surface (which is rendering the Tango color camera)
*/
public void screenGrab(){
int width = this.getWidth();
int height = this.getHeight();
long fileprefix = System.currentTimeMillis();
Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(image);
canvas.drawBitmap(image, 0, 0, null);
//TODO: make seperate subdirctories for each exploitation sessions
String targetPath =Environment.getExternalStorageDirectory() + "/RavenEye/Photos/";
String imageFileName = fileprefix + ".jpg";
if(!(new File(targetPath)).exists()) {
new File(targetPath).mkdirs();
}
try {
File targetDirectory = new File(targetPath);
File photo=new File(targetDirectory, imageFileName);
FileOutputStream fos=new FileOutputStream(photo.getPath());
image.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
Log.i(this.getClass().getCanonicalName(), "Grabbed an image in target path:" + targetPath);
} catch (FileNotFoundException e) {
Log.e(CameraPreview.class.getName(),"Exception " + e);
e.printStackTrace();
} catch (IOException e) {
Log.e(CameraPreview.class.getName(),"Exception " + e);
e.printStackTrace();
}
}
#Override
public void onFrameAvailable() {
super.onFrameAvailable();
if(takeSnapShot) {
screenGrab();
takeSnapShot = false;
}
}
public CameraSurfaceView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
}
Where I'm Heading
I'm preparing to root the device, and then using the onFrameAvailable method to cue an external root process such as one of these:
post 23610900
post 10965409
post 4998527
I'm hoping I can find a way to avoid the root hack.
Thank you in advance!
OK, I figured out a way to make it work.
Update: My working solution is here:
https://github.com/stevehenderson/GoogleTango_AR_VideoCapture
I essentially set up a "man (renderer) in the middle" attack on the rendering pipeline.
This approach intercepts the SetRenderer call from the TangoCameraPreview base class, and allows one to get access
to the base renderer's OnDraw() method and the GL context. I then add additional methods to this extended renderer that allow reading of the GL buffer.
General approach
1) Extend the TangoCameraPreview class (e.g. in my example ReadableTangoCameraPreview). Override the setRenderer(GLSurfaceView.Renderer renderer), keeping a reference to the base renderer, and replacing the renderer with your own "wrapped" GLSUrface.Renderer renderer that will add methods to render the backbuffer to an image on the device.
2) Create your own GLSurfaceView.Renderer Interface (e.g. my ScreenGrabRenderer class ) that implements all the GLSurfaceView.Renderer methods, passing them on to the base renderer captured in Step 1. Also, add a few new methods to "cue" when you want to grab the image.
3) Implement the ScreenGrabRenderer described in step 2 above.
4) Use a callback interface (my TangoCameraScreengrabCallback) to communicate when an image has been copied
It works pretty well, and allows one to grab the camera bits in an image without rooting the device.
Note: I haven't had the need to closely synchronize my captured images with the point cloud. So I haven't checked the latency. For best results, you may need to invoke the C methods proposed by Mark.
Here's what each of my classes looks like..
///Main Activity Class where bulk of Tango code is
.
.
.
// Create our Preview view and set it as the content of our activity.
mTangoCameraPreview = new ReadableTangoCameraPreview(getActivity());
RelativeLayout preview = (RelativeLayout) view.findViewById(R.id.camera_preview);
preview.addView(mTangoCameraPreview);
.
.
.
//When you want to take a snapshot, call the takeSnapShotMethod()
//(you can make this respond to a button)
mTangoCameraPreview.takeSnapShot();
.
.
.
.
.
//Main Tango Listeners
#Override
public void onFrameAvailable(final int cameraId) {
// Update the UI with TangoPose information
runOnUiThread(new Runnable() {
#Override
public void run() {
if (cameraId == TangoCameraIntrinsics.TANGO_CAMERA_COLOR) {
tangoCameraPreview.onFrameAvailable();
}
}
});
}
ReadableTangoCameraPreview Class
public class ReadableTangoCameraPreview extends TangoCameraPreview implements TangoCameraScreengrabCallback {
Activity mainActivity;
private static final String TAG = ReadableTangoCameraPreview.class.getSimpleName();
//An intercept renderer
ScreenGrabRenderer screenGrabRenderer;
private boolean takeSnapShot = false;
#Override
public void setRenderer(GLSurfaceView.Renderer renderer) {
//Create our "man in the middle"
screenGrabRenderer= new ScreenGrabRenderer(renderer);
//Set it's call back
screenGrabRenderer.setTangoCameraScreengrabCallback(this);
//Tell the TangoCameraPreview class to use this intermediate renderer
super.setRenderer(screenGrabRenderer);
Log.i(TAG,"Intercepted the renderer!!!");
}
/**
* Set a trigger for snapshot. Call this from main activity
* in response to a use input
*/
public void takeSnapShot() {
takeSnapShot = true;
}
#Override
public void onFrameAvailable() {
super.onFrameAvailable();
if(takeSnapShot) {
//screenGrabWithRoot();
screenGrabRenderer.grabNextScreen(0,0,this.getWidth(),this.getHeight());
takeSnapShot = false;
}
}
public ReadableTangoCameraPreview(Activity context) {
super(context);
mainActivity = context;
}
public void newPhoto(String aNewPhotoPath) {
//This gets called when a new photo was grabbed created in the renderer
Log.i(TAG,"New image available at" + aNewPhotoPath);
}
}
ScreenGrabRenderer Interface
(Overloads the TangoCameraPreview default Renderer)
/**
* This is an intermediate class that intercepts all calls to the TangoCameraPreview's
* default renderer.
*
* It simply passes all render calls through to the default renderer.
*
* When required, it can also use the renderer methods to dump a copy of the frame to a bitmap
*
* #author henderso
*
*/
public class ScreenGrabRenderer implements GLSurfaceView.Renderer {
TangoCameraScreengrabCallback mTangoCameraScreengrabCallback;
GLSurfaceView.Renderer tangoCameraRenderer;
private static final String TAG = ScreenGrabRenderer.class.getSimpleName();
private String lastFileName = "unset";
boolean grabNextScreen = false;
int grabX = 0;
int grabY = 0;
int grabWidth = 640;
int grabHeight = 320;
public void setTangoCameraScreengrabCallback(TangoCameraScreengrabCallback aTangoCameraScreengrabCallback) {
mTangoCameraScreengrabCallback = aTangoCameraScreengrabCallback;
}
/**
* Cue the renderer to grab the next screen. This is a signal that will
* be detected inside the onDrawFrame() method
*
* #param b
*/
public void grabNextScreen(int x, int y, int w, int h) {
grabNextScreen = true;
grabX=x;
grabY=y;
grabWidth=w;
grabHeight=h;
}
#Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
tangoCameraRenderer.onSurfaceCreated(gl, config);
}
#Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
tangoCameraRenderer.onSurfaceChanged(gl, width, height);
}
#Override
public void onDrawFrame(GL10 gl) {
tangoCameraRenderer.onDrawFrame(gl);
if(grabNextScreen) {
screenGrab(gl);
grabNextScreen=false;
}
}
/**
*
* Creates a bitmap given a certain dimension and an OpenGL context
*
* This code was lifted from here:
*
* http://stackoverflow.com/questions/5514149/capture-screen-of-glsurfaceview-to-bitmap
*/
private Bitmap createBitmapFromGLSurface(int x, int y, int w, int h, GL10 gl)
throws OutOfMemoryError {
int bitmapBuffer[] = new int[w * h];
int bitmapSource[] = new int[w * h];
IntBuffer intBuffer = IntBuffer.wrap(bitmapBuffer);
intBuffer.position(0);
try {
gl.glReadPixels(x, y, w, h, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, intBuffer);
int offset1, offset2;
for (int i = 0; i < h; i++) {
offset1 = i * w;
offset2 = (h - i - 1) * w;
for (int j = 0; j < w; j++) {
int texturePixel = bitmapBuffer[offset1 + j];
int blue = (texturePixel >> 16) & 0xff;
int red = (texturePixel << 16) & 0x00ff0000;
int pixel = (texturePixel & 0xff00ff00) | red | blue;
bitmapSource[offset2 + j] = pixel;
}
}
} catch (GLException e) {
Log.e(TAG,e.toString());
return null;
}
return Bitmap.createBitmap(bitmapSource, w, h, Bitmap.Config.ARGB_8888);
}
/**
* Writes a copy of the GLSurface backbuffer to storage
*/
private void screenGrab(GL10 gl) {
long fileprefix = System.currentTimeMillis();
String targetPath =Environment.getExternalStorageDirectory() + "/RavenEye/Photos/";
String imageFileName = fileprefix + ".png";
String fullPath = "error";
Bitmap image = createBitmapFromGLSurface(grabX,grabY,grabWidth,grabHeight,gl);
if(!(new File(targetPath)).exists()) {
new File(targetPath).mkdirs();
}
try {
File targetDirectory = new File(targetPath);
File photo=new File(targetDirectory, imageFileName);
FileOutputStream fos=new FileOutputStream(photo.getPath());
image.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
fullPath =targetPath + imageFileName;
Log.i(TAG, "Grabbed an image in target path:" + fullPath);
///Notify the outer class(es)
if(mTangoCameraScreengrabCallback != null) {
mTangoCameraScreengrabCallback.newPhoto(fullPath);
} else {
Log.i(TAG, "Callback not set properly..");
}
} catch (FileNotFoundException e) {
Log.e(TAG,"Exception " + e);
e.printStackTrace();
} catch (IOException e) {
Log.e(TAG,"Exception " + e);
e.printStackTrace();
}
lastFileName = fullPath;
}
/**
* Constructor
* #param baseRenderer
*/
public ScreenGrabRenderer(GLSurfaceView.Renderer baseRenderer) {
tangoCameraRenderer = baseRenderer;
}
}
TangoCameraScreengrabCallback Interface
(not required unless you want to pass info back from the screen grab renderer)
/*
* The TangoCameraScreengrabCallback is a generic interface that provides callback mechanism
* to an implementing activity.
*
*/
interface TangoCameraScreengrabCallback {
public void newPhoto(String aNewPhotoPath);
}
I haven't tried on the latest release, but it was the absence of this functionality that drove me to the C API where I could get image data - a recent post, I think on the G+ page, seemed to indicate that the Unity API now returns image data as well - for a company that wants to keep scolding us when we don't use Java, it certainly is an odd lag :-)
i referred this code for viewpagerindicator from http://www.zylinc.com/blog-reader/items/viewpager-page-indicator.html .I want to display different views on different pages.Right now i m able to display list items on every page(3 pages) but i want to display lets say textview on second and third pages.i made some changes and created title using array here is the snippet for that
#Override
public String getTitle(int pos){
Log.i("FragmentList", "current page position is : " +mViewPager.getCurrentItem());
switch (pos) {
case 0:return titles[0];
case 1:return titles[1];
case 2:return titles[2];
default:return titles[0];
}
// pageListener = new DetailOnPageChange();
// mViewPager.setOnPageChangeListener(pageListener);
}
so when i change the page i also want to change the layouts i was thinking if i could get current position of the page i could put them in switch case and implement layout... but invain as mViewpager.getcurrentitem behaves properly in this function can some1 help me who should i implement that here is my code viewpagerindicator activty
package com.zylinc.view;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.zip.Inflater;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.ListFragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ViewPagerIndicatorActivity extends FragmentActivity
{
DetailOnPageChange pageListener;
PagerAdapter mPagerAdapter;
static ViewPager mViewPager;
ViewPagerIndicator mIndicator;
static TextView stv;
static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
static SimpleDateFormat readableDateFormat = new SimpleDateFormat("yyyy - MM/dd");
public int numberofPages = 3;
Inflater inflater;
public static final String[] titles = new String[]{"First Page","Second Page","Third Page"};
public static int pos;
public int currentPageIs;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create our custom adapter to supply pages to the viewpager.
mPagerAdapter = new PagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager)findViewById(R.id.pager);
mViewPager.setAdapter(mPagerAdapter);
// Start at a custom position
mViewPager.setCurrentItem(0);
// Find the indicator from the layout
mIndicator = (ViewPagerIndicator)findViewById(R.id.indicator);
// Set the indicator as the pageChangeListener
mViewPager.setOnPageChangeListener(mIndicator);
// Initialize the indicator. We need some information here:
// * What page do we start on.
// * How many pages are there in total
// * A callback to get page titles
Log.i("number of counts are ", "pages are"+mPagerAdapter.getCount());
mIndicator.init(0, mPagerAdapter.getCount(), mPagerAdapter);
Resources res = getResources();
Drawable prev = res.getDrawable(R.drawable.indicator_prev_arrow);
Drawable next = res.getDrawable(R.drawable.indicator_next_arrow);
mIndicator.setFocusedTextColor(new int[]{255, 0, 0});
// Set images for previous and next arrows.
mIndicator.setArrows(prev, next);
mIndicator.setOnClickListener(new OnIndicatorClickListener());
}
class OnIndicatorClickListener implements ViewPagerIndicator.OnClickListener{
#Override
public void onCurrentClicked(View v) {
Toast.makeText(ViewPagerIndicatorActivity.this, "Hello", Toast.LENGTH_SHORT).show();
}
#Override
public void onNextClicked(View v) {
mViewPager.setCurrentItem(Math.min(mPagerAdapter.getCount() - 1, mIndicator.getCurrentPosition() + 1));
}
#Override
public void onPreviousClicked(View v) {
mViewPager.setCurrentItem(Math.max(0, mIndicator.getCurrentPosition() - 1));
}
}
class PagerAdapter extends FragmentPagerAdapter implements ViewPagerIndicator.PageInfoProvider
{
ArrayList<Fragment> fragments = new ArrayList<Fragment>();
//ArrayList<String> showTitles = new ArrayList<String>();
//String myPos = titles[pos];
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, pos - getCount() / 2);
return ItemFragment.newInstance(cal.getTime());
//return ItemFragment.newInstance(titles[pos]);
}
#Override
public String getTitle(int pos){
Log.i("FragmentList", "current page position is : " +mViewPager.getCurrentItem());
switch (pos) {
case 0:return titles[0];
case 1:return titles[1];
case 2:return titles[2];
default:return titles[0];
}
// pageListener = new DetailOnPageChange();
// mViewPager.setOnPageChangeListener(pageListener);
}
#Override
public int getCount() {
return numberofPages;
}
}
public class DetailOnPageChange extends ViewPager.SimpleOnPageChangeListener{
#Override
public void onPageSelected(int position) {
Log.i("FragmentList", "************* position is : " +currentPageIs);
currentPageIs = position;
}
public int getCurrentPage(){
return currentPageIs;
}
}
public static class ItemFragment extends ListFragment
{
static Date date;
TextView tv;
static ItemFragment newInstance(Date date) {
ItemFragment f = new ItemFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putString("date", sdf.format(date));
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
this.date = sdf.parse(getArguments().getString("date"));
} catch (ParseException e) {
e.printStackTrace();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Log.i("FragmentList", "current page checker position is : " +titles[pos]);
View v = inflater.inflate(R.layout.date_fragment, container, false);
View tv = v.findViewById(R.id.text);
((TextView)tv).setText(readableDateFormat.format(date));
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, list));
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("FragmentList", "Item clicked: " + id);
}
}
public static final String[] list = new String[]{"France", "London", "Sweden", "Denmark", "Germany", "Finland", "Thailand", "Taiwan", "USA", "Norway", "Lithuania", "Bosnia", "Russia", "Vietnam", "Australia"};
}
and here is adapter
package com.zylinc.view;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* An small bar indicating the title of the previous,
* current and next page to be shown in a ViewPager.
* Made to resemble the indicator in the Google+ application
* in function.
*
* #author Mark Gjøl # Zylinc
*/
public class ViewPagerIndicator extends RelativeLayout implements OnPageChangeListener {
private static final int PADDING = 5;
TextView mPrevious;
TextView mCurrent;
TextView mNext;
int mCurItem;
int mRestoreCurItem = -1;
LinearLayout mPreviousGroup;
LinearLayout mNextGroup;
int mArrowPadding;
int mSize;
ImageView mCurrentIndicator;
ImageView mPrevArrow;
ImageView mNextArrow;
int[] mFocusedTextColor;
int[] mUnfocusedTextColor;
OnClickListener mOnClickHandler;
public interface PageInfoProvider{
String getTitle(int pos);
}
public interface OnClickListener{
void onNextClicked(View v);
void onPreviousClicked(View v);
void onCurrentClicked(View v);
}
public void setOnClickListener(OnClickListener handler){
this.mOnClickHandler = handler;
mPreviousGroup.setOnClickListener(new OnPreviousClickedListener());
mCurrent.setOnClickListener(new OnCurrentClickedListener());
mNextGroup.setOnClickListener(new OnNextClickedListener());
}
public int getCurrentPosition(){
return mCurItem;
}
PageInfoProvider mPageInfoProvider;
public void setPageInfoProvider(PageInfoProvider pageInfoProvider){
this.mPageInfoProvider = pageInfoProvider;
}
public void setFocusedTextColor(int[] col){
System.arraycopy(col, 0, mFocusedTextColor, 0, 3);
updateColor(0);
}
public void setUnfocusedTextColor(int[] col){
System.arraycopy(col, 0, mUnfocusedTextColor, 0, 3);
mNext.setTextColor(Color.argb(255, col[0], col[1], col[2]));
mPrevious.setTextColor(Color.argb(255, col[0], col[1], col[2]));
updateColor(0);
}
#Override
protected Parcelable onSaveInstanceState() {
Parcelable state = super.onSaveInstanceState();
Bundle b = new Bundle();
b.putInt("current", this.mCurItem);
b.putParcelable("viewstate", state);
return b;
}
#Override
protected void onRestoreInstanceState(Parcelable state) {
super.onRestoreInstanceState(((Bundle)state).getParcelable("viewstate"));
mCurItem = ((Bundle)state).getInt("current", mCurItem);
this.setText(mCurItem - 1);
this.updateArrows(mCurItem);
this.invalidate();
}
/**
* Initialization
*
* #param startPos The initially selected element in the ViewPager
* #param size Total amount of elements in the ViewPager
* #param pageInfoProvider Interface that returns page titles
*/
public void init(int startPos, int size, PageInfoProvider pageInfoProvider){
setPageInfoProvider(pageInfoProvider);
this.mSize = size;
setText(startPos - 1);
mCurItem = startPos;
}
public ViewPagerIndicator(Context context, AttributeSet attrs) {
super(context, attrs);
addContent();
}
public ViewPagerIndicator(Context context, AttributeSet attrs, int defStyle){
super(context, attrs, defStyle);
addContent();
}
public ViewPagerIndicator(Context context) {
super(context);
addContent();
}
/**
* Add drawables for arrows
*
* #param prev Left pointing arrow
* #param next Right pointing arrow
*/
public void setArrows(Drawable prev, Drawable next){
this.mPrevArrow = new ImageView(getContext());
this.mPrevArrow.setImageDrawable(prev);
this.mNextArrow = new ImageView(getContext());
this.mNextArrow.setImageDrawable(next);
LinearLayout.LayoutParams arrowLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
arrowLayoutParams.gravity = Gravity.CENTER;
mPreviousGroup.removeAllViews();
mPreviousGroup.addView(mPrevArrow, arrowLayoutParams);
mPreviousGroup.addView(mPrevious, arrowLayoutParams);
mPrevious.setPadding(PADDING, 0, 0, 0);
mNext.setPadding(0, 0, PADDING, 0);
mArrowPadding = PADDING + prev.getIntrinsicWidth();
mNextGroup.addView(mNextArrow, arrowLayoutParams);
updateArrows(mCurItem);
}
/**
* Create all views, build the layout
*/
private void addContent(){
mFocusedTextColor = new int[]{0, 0, 0};
mUnfocusedTextColor = new int[]{190, 190, 190};
// Text views
mPrevious = new TextView(getContext());
mCurrent = new TextView(getContext());
mNext = new TextView(getContext());
RelativeLayout.LayoutParams previousParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
previousParams.addRule(RelativeLayout.ALIGN_LEFT);
RelativeLayout.LayoutParams currentParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
currentParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
RelativeLayout.LayoutParams nextParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
nextParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
// Groups holding text and arrows
mPreviousGroup = new LinearLayout(getContext());
mPreviousGroup.setOrientation(LinearLayout.HORIZONTAL);
mNextGroup = new LinearLayout(getContext());
mNextGroup.setOrientation(LinearLayout.HORIZONTAL);
mPreviousGroup.addView(mPrevious, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mNextGroup.addView(mNext, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
addView(mPreviousGroup, previousParams);
addView(mCurrent, currentParams);
addView(mNextGroup, nextParams);
mPrevious.setSingleLine();
mCurrent.setSingleLine();
mNext.setSingleLine();
mPrevious.setText("previous");
mCurrent.setText("current");
mNext.setText("next");
mPrevious.setClickable(false);
mNext.setClickable(false);
mCurrent.setClickable(true);
mPreviousGroup.setClickable(true);
mNextGroup.setClickable(true);
// Set colors
mNext.setTextColor(Color.argb(255, mUnfocusedTextColor[0], mUnfocusedTextColor[1], mUnfocusedTextColor[2]));
mPrevious.setTextColor(Color.argb(255, mUnfocusedTextColor[0], mUnfocusedTextColor[1], mUnfocusedTextColor[2]));
updateColor(0);
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
positionOffsetPixels = adjustOffset(positionOffsetPixels);
position = updatePosition(position, positionOffsetPixels);
setText(position - 1);
updateColor(positionOffsetPixels);
updateArrows(position);
updatePositions(positionOffsetPixels);
mCurItem = position;
}
void updatePositions(int positionOffsetPixels){
int textWidth = mCurrent.getWidth() - mCurrent.getPaddingLeft() - mCurrent.getPaddingRight();
int maxOffset = this.getWidth() / 2 - textWidth / 2 - mArrowPadding;
if(positionOffsetPixels > 0){
maxOffset -= this.getPaddingLeft();
int offset = Math.min(positionOffsetPixels, maxOffset - 1);
mCurrent.setPadding(0, 0, 2 * offset, 0);
// Move previous text out of the way. Slightly buggy.
/*
int overlapLeft = mPreviousGroup.getRight() - mCurrent.getLeft() + mArrowPadding;
mPreviousGroup.setPadding(0, 0, Math.max(0, overlapLeft), 0);
mNextGroup.setPadding(0, 0, 0, 0);
*/
}else{
maxOffset -= this.getPaddingRight();
int offset = Math.max(positionOffsetPixels, -maxOffset);
mCurrent.setPadding(-2 * offset, 0, 0, 0);
// Move next text out of the way. Slightly buggy.
/*
int overlapRight = mCurrent.getRight() - mNextGroup.getLeft() + mArrowPadding;
mNextGroup.setPadding(Math.max(0, overlapRight), 0, 0, 0);
mPreviousGroup.setPadding(0, 0, 0, 0);
*/
}
}
/**
* Hide arrows if we can't scroll further
*
* #param position
*/
void updateArrows(int position){
if(mPrevArrow != null){
mPrevArrow.setVisibility(position == 0 ? View.INVISIBLE : View.VISIBLE);
mNextArrow.setVisibility(position == mSize - 1 ? View.INVISIBLE : View.VISIBLE);
}
}
/**
* Adjust position to be the view that is showing the most.
*
* #param givenPosition
* #param offset
* #return
*/
int updatePosition(int givenPosition, int offset){
int pos;
if(offset < 0){
pos = givenPosition + 1;
}else{
pos = givenPosition;
}
return pos;
}
/**
* Fade "currently showing" color depending on it's position
*
* #param offset
*/
void updateColor(int offset){
offset = Math.abs(offset);
// Initial condition: offset is always 0, this.getWidth is also 0! 0/0 = NaN
int width = this.getWidth();
float fraction = width == 0 ? 0 : offset / ((float)width / 4.0f);
fraction = Math.min(1, fraction);
int r = (int)(mUnfocusedTextColor[0] * fraction + mFocusedTextColor[0] * (1 - fraction));
int g = (int)(mUnfocusedTextColor[1] * fraction + mFocusedTextColor[1] * (1 - fraction));
int b = (int)(mUnfocusedTextColor[2] * fraction + mFocusedTextColor[2] * (1 - fraction));
mCurrent.setTextColor(Color.argb(255, r, g, b));
}
/**
* Update text depending on it's position
*
* #param prevPos
*/
void setText(int prevPos){
if(prevPos < 0){
mPrevious.setText("");
}else{
mPrevious.setText(mPageInfoProvider.getTitle(prevPos));
}
mCurrent.setText(mPageInfoProvider.getTitle(prevPos + 1));
if(prevPos + 2 == this.mSize){
mNext.setText("");
}else{
mNext.setText(mPageInfoProvider.getTitle(prevPos + 2));
}
}
// Original:
// 244, 245, 0, 1, 2
// New:
// -2, -1, 0, 1, 2
int adjustOffset(int positionOffsetPixels){
// Move offset half width
positionOffsetPixels += this.getWidth() / 2;
// Clamp to width
positionOffsetPixels %= this.getWidth();
// Center around zero
positionOffsetPixels -= this.getWidth() / 2;
return positionOffsetPixels;
}
#Override
public void onPageSelected(int position) {
// Reset padding when the page is finally selected (May not be necessary)
mCurrent.setPadding(0, 0, 0, 0);
}
class OnPreviousClickedListener implements android.view.View.OnClickListener{
#Override
public void onClick(View v) {
if(mOnClickHandler != null){
mOnClickHandler.onPreviousClicked(ViewPagerIndicator.this);
}
}
}
class OnCurrentClickedListener implements android.view.View.OnClickListener{
#Override
public void onClick(View v) {
if(mOnClickHandler != null){
mOnClickHandler.onCurrentClicked(ViewPagerIndicator.this);
}
}
}
class OnNextClickedListener implements android.view.View.OnClickListener{
#Override
public void onClick(View v) {
if(mOnClickHandler != null){
mOnClickHandler.onNextClicked(ViewPagerIndicator.this);
}
}
}
}
You may find this blog useful; Making ActionBarSherlock and ViewPagerIndicator play nice
You may also come across a bug mentioned here; Android - SupportMapFragment with GoogleMaps API 2.0 giving IllegalArgumentException
Good Luck..!!
Is there a way to show "Loading" screen with animation in blackberry?
Options:
PME animation content
multithreading + set of images + timer/counter
standard rim api
some other way
Any of this?
Thanks!
Fermin, Anthony +1. Thanks to all, you gave me the part of answer.
My final solution:
1.Create or generate (free Ajax loading gif generator) animation and add it to project.
2.Create ResponseCallback interface (see Coderholic - Blackberry WebBitmapField) to receive thread execution result:
public interface ResponseCallback {
public void callback(String data);
}
3.Create a class to handle your background thread job. In my case it was http request:
public class HttpConnector
{
static public void HttpGetStream(final String fileToGet,
final ResponseCallback msgs) {
Thread t = new Thread(new Runnable() {
public void run() {
HttpConnection hc = null;
DataInputStream din = null;
try {
hc = (HttpConnection) Connector.open("http://" + fileToGet);
hc.setRequestMethod(HttpsConnection.GET);
din = hc.openDataInputStream();
ByteVector bv = new ByteVector();
int i = din.read();
while (-1 != i) {
bv.addElement((byte) i);
i = din.read();
}
final String response = new String(bv.toArray(), "UTF-8");
UiApplication.getUiApplication().invokeLater(
new Runnable() {
public void run() {
msgs.callback(response);
}
});
}
catch (final Exception e) {
UiApplication.getUiApplication().invokeLater(
new Runnable() {
public void run() {
msgs.callback("Exception (" + e.getClass() + "): "
+ e.getMessage());
}
});
}
finally {
try {
din.close();
din = null;
hc.close();
hc = null;
}
catch (Exception e) {
}
}
}
});
t.start();
}
}
4.Create WaitScreen (a hybrid of FullScreen and AnimatedGIFField with ResponseCallback interface):
public class WaitScreen extends FullScreen implements ResponseCallback
{
StartScreen startScreen;
private GIFEncodedImage _image;
private int _currentFrame;
private int _width, _height, _xPos, _yPos;
private AnimatorThread _animatorThread;
public WaitScreen(StartScreen startScreen) {
super(new VerticalFieldManager(), Field.NON_FOCUSABLE);
setBackground(
BackgroundFactory.createSolidTransparentBackground(
Color.WHITE, 100));
this.startScreen = startScreen;
EncodedImage encImg =
GIFEncodedImage.getEncodedImageResource("ajax-loader.gif");
GIFEncodedImage img = (GIFEncodedImage) encImg;
// Store the image and it's dimensions.
_image = img;
_width = img.getWidth();
_height = img.getHeight();
_xPos = (Display.getWidth() - _width) >> 1;
_yPos = (Display.getHeight() - _height) >> 1;
// Start the animation thread.
_animatorThread = new AnimatorThread(this);
_animatorThread.start();
UiApplication.getUiApplication().pushScreen(this);
}
protected void paint(Graphics graphics) {
super.paint(graphics);
// Draw the animation frame.
graphics
.drawImage(_xPos, _yPos, _image
.getFrameWidth(_currentFrame), _image
.getFrameHeight(_currentFrame), _image,
_currentFrame, 0, 0);
}
protected void onUndisplay() {
_animatorThread.stop();
}
private class AnimatorThread extends Thread {
private WaitScreen _theField;
private boolean _keepGoing = true;
private int _totalFrames, _loopCount, _totalLoops;
public AnimatorThread(WaitScreen _theScreen) {
_theField = _theScreen;
_totalFrames = _image.getFrameCount();
_totalLoops = _image.getIterations();
}
public synchronized void stop() {
_keepGoing = false;
}
public void run() {
while (_keepGoing) {
// Invalidate the field so that it is redrawn.
UiApplication.getUiApplication().invokeAndWait(
new Runnable() {
public void run() {
_theField.invalidate();
}
});
try {
// Sleep for the current frame delay before
// the next frame is drawn.
sleep(_image.getFrameDelay(_currentFrame) * 10);
} catch (InterruptedException iex) {
} // Couldn't sleep.
// Increment the frame.
++_currentFrame;
if (_currentFrame == _totalFrames) {
// Reset back to frame 0
// if we have reached the end.
_currentFrame = 0;
++_loopCount;
// Check if the animation should continue.
if (_loopCount == _totalLoops) {
_keepGoing = false;
}
}
}
}
}
public void callback(String data) {
startScreen.updateScreen(data);
UiApplication.getUiApplication().popScreen(this);
}
}
5.In the end, create Start screen to call HttpConnector.HttpGetStream and to show WaitScreen:
public class StartScreen extends MainScreen
{
public RichTextField text;
WaitScreen msgs;
public StartScreen() {
text = new RichTextField();
this.add(text);
}
protected void makeMenu(Menu menu, int instance) {
menu.add(runWait);
super.makeMenu(menu, instance);
}
MenuItem runWait = new MenuItem("wait", 1, 1) {
public void run() {
UiApplication.getUiApplication().invokeLater(
new Runnable() {
public void run() {
getFile();
}
});
}
};
public void getFile() {
msgs = new WaitScreen(this);
HttpConnector.HttpGetStream(
"stackoverflow.com/faq", msgs);
}
//you should implement this method to use callback data on the screen.
public void updateScreen(String data)
{
text.setText(data);
}
}
UPDATE: another solution naviina.eu: A Web2.0/Ajax-style loading popup in a native BlackBerry application
The basic pattern for this kind of thing is:
Have a thread running a loop that updates a variable (such as the frame index of the animated image) and then calls invalidate on a Field which draws the image (and then sleeps for a period of time). The invalidate will queue a repaint of the field.
In the field's paint method, read the variable and draw the appropriate frame of the image.
Pseudo code (not totally complete, but to give you the idea):
public class AnimatedImageField extends Field implements Runnable {
private int currentFrame;
private Bitmap[] animationFrames;
public void run() {
while(true) {
currentFrame = (currentFrame + 1) % animationFrames.length;
invalidate();
Thread.sleep(100);
}
}
protected void paint(Graphics g) {
g.drawBitmap(0, 0, imageWidth, imageHeight, animationFrames[currentFrame], 0, 0);
}
}
Note also here I used an array of Bitmaps, but EncodedImage lets you treat an animated gif as one object, and includes methods to get specific frames.
EDIT: For completeness: Add this to a PopupScreen (as in Fermin's answer) or create your own dialog by overriding Screen directly. The separate thread is necessary because the RIM API is not thread-safe: you need to do everything UI related on the event thread (or while holding the event lock, see BlackBerry UI Threading - The Very Basics
This is simple code for loading screen ....
HorizontalFieldManager popHF = new HorizontalFieldManager();
popHF.add(new CustomLabelField("Pls wait..."));
final PopupScreen waitScreen = new PopupScreen(popHF);
new Thread()
{
public void run()
{
synchronized (UiApplication.getEventLock())
{
UiApplication.getUiApplication().pushScreen(waitScreen);
}
//Here Some Network Call
synchronized (UiApplication.getEventLock())
{
UiApplication.getUiApplication().popScreen(waitScreen);
}
}
}.start();
If it's just an animation could you show an animated gif on a popup and close it when loading operation is complete?
Easiest way is probably to use the standard GaugeField, setting style GaugeField.PERCENT. This will give you a progress bar. Add this to a PopupScreen and it will sit on top of your content. Something like..
private GaugeField _gaugeField;
private PopupScreen _popup;
public ProgressBar() {
DialogFieldManager manager = new DialogFieldManager();
_popup = new PopupScreen(manager);
_gaugeField = new GaugeField(null, 0, 100, 0, GaugeField.PERCENT);
manager.addCustomField(_gaugeField);
}
Then have an update method which will use _gaugeField.setValue(newValue); to update the progress bar.
I normally have this called from whichever thread is doing the work (loading in your case, everytime an operation is complete the progress bar is updated.
I would suggest to take a look at this simple implementation. I liked this but never used it. May be helpful to you.
link text
ActivityIndicator is a good option if you are working with at least BB OS 6.0.
http://www.brighthub.com/mobile/blackberry-platform/articles/94258.aspx
http://docs.blackberry.com/en/developers/deliverables/17966/Screen_APIs_1245069_11.jsp