Android accelerometer stability - android

I am trying to use the accelerometer to simply detect flipping the phone in 4 different angles from face down (left, right, right side up, upside down) and whether it is done fast or slow. I also want to stop checking after about 30 degrees of flipping the phone.
My problem is getting some stability. It will work once in a while and then not work.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
#Override
protected void onResume() {
super.onResume();
...
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
}
#Override
public void onSensorChanged(SensorEvent event) {
preTS = TS;
preX = X;
preY = Y;
preZ = Z;
realX = event.values[0];
realY = event.values[1];
realZ = event.values[2];
X = Math.abs(event.values[0]);
Y = Math.abs(event.values[1]);
Z = Math.abs(event.values[2]);
TS = event.timestamp;
if (X < 2 && Y < 1) {
npsX = ((TS - preTS) * Math.abs(X - preX)) / 100000;
npsY = ((TS - preTS) * Math.abs(Y - preY)) / 100000;
npsZ = ((TS - preTS) * Math.abs(Z - preZ)) / 100000;
}
maxX = (maxX > npsX) ? maxX : npsX;
maxY = (maxY > npsY) ? maxY : npsY;
maxZ = (maxZ > npsZ) ? maxZ : npsZ;
if(X < 1 && Y < 1 && Z > 9) {
maxX = 0;
maxY = 0;
maxZ = 0;
dir = "";
speed = "";
}
if (Objects.equals(dir, "") || Objects.equals(speed, "")) {
if (realX >= 2) {
dir = "left";
} else if (realX <= -2) {
dir = "right";
} else if (realY >= 2) {
dir = "up";
} else if (realY <= -2) {
dir = "down";
}
if (maxX > 250 || maxY > 250 || maxZ > 250)
speed = "fast";
else
speed = "slow";
}
Log.i("MA", (int) maxX + " " + (int) maxY + " " + (int) maxZ + " " + X + " " + Y + " " +
Z + " " + speed + " " + dir + " " + realX + " " + realY + " " + realZ);
}

Related

How do I keep from leaving the screen?

I do not speak English well.
We apologize if you do not understand the question.
LinearLayout _Main_Contact_Layout;
FrameLayout _Main_Frame;
ImageView _Main_Background;
private List<string> _DrawerList_Item;
private ListView _DrawerList;
float _X, _Y;
float _XX, _YY;
int offset = 0, duration = 100;
float scaleX = 1.0f, scaleY = 1.0f;
float maxZoomLimit = 2.6f, minZoomLimit = 1.0f;
public bool OnTouch(View v, MotionEvent e)
{
switch (e.Action)
{
case MotionEventActions.Down:
_X = e.GetX();
_Y = e.GetY();
float _Start_X = 760, _Start_Y = 160;
float _End_X = 1150, _End_Y = 490;
WindowManagerLayoutParams _Params = new WindowManagerLayoutParams();
_Params.X = (int)e.RawX;
_Params.Y = (int)e.RawY;
LayoutInflater inflater = (LayoutInflater)this.GetSystemService(Context.LayoutInflaterService);
View _Popup = inflater.Inflate(Resource.Layout.Custom_Popup, null);
PopupWindow _Window = new PopupWindow(_Popup, WindowManagerLayoutParams.WrapContent, WindowManagerLayoutParams.WrapContent);
_Window.SetBackgroundDrawable(new BitmapDrawable());
_Window.OutsideTouchable = true;
TextView _SetupX = (TextView)_Popup.FindViewById(Resource.Id.x_text);
TextView _SetupY = (TextView)_Popup.FindViewById(Resource.Id.y_text);
_SetupX.Text = "X 좌표 : " + _X.ToString("#.##");
_SetupY.Text = "Y 좌표 : " + _Y.ToString("#.##");
DrawerLayout _lstDrawer = (DrawerLayout)v.FindViewById(Resource.Id._DrawerLayout);
if(_Start_X > _X | _Start_Y > _Y | _End_X < _X | _End_Y < _Y )
{
_Window.Focusable = true;
_Window.ShowAsDropDown(_Popup, _Params.X, _Params.Y);
_Window.ShowAtLocation(_Popup, GravityFlags.Left | GravityFlags.Top, 0, 0);
_lstDrawer.CloseDrawer((int)GravityFlags.Left);
}
else if (_Start_X < _X & _Start_Y < _Y & _End_X > _X & _End_Y > _Y & !_lstDrawer.IsDrawerOpen((int)GravityFlags.Left))
{
_lstDrawer.OpenDrawer((int)GravityFlags.Left);
_Window.ShowAsDropDown(_Popup, _Params.X, _Params.Y);
_Window.ShowAtLocation(_Popup, GravityFlags.Left | GravityFlags.Top, 0, 0);
}
else if (_lstDrawer.IsDrawerOpen((int)GravityFlags.Left))
{
_lstDrawer.CloseDrawer((int)GravityFlags.Left);
}
break;
case MotionEventActions.Move:
_XX = e.GetX() - _X;
_YY = e.GetY() - _Y;
//_Main_Background.SetX(_Main_Background.GetX() + _XX);
//_Main_Background.SetY(_Main_Background.GetY() + _YY);
_X = e.GetX();
_Y = e.GetY();
if (scaleX > 1.0f && scaleY > 1.0f)
{
_MoveToX(_XX);
_MoveToY(_YY);
Console.WriteLine("_XX : " + _XX.ToString());
Console.WriteLine("_YY : " + _YY.ToString());
}
break;
}
return true;
}
private void _MoveToX(float xX)
{
float futureX = _Main_Background.GetX() + _XX;
if (futureX > 0 | futureX < 500)
{
_Main_Background.SetX(futureX);
}
}
private void _MoveToY(float yY)
{
float futureY = _Main_Background.GetY() + _YY;
if (futureY > 0 | futureY < 500)
{
_Main_Background.SetY(futureY);
}
}
private void _Zoom_In(View v)
{
if (scaleX < maxZoomLimit && scaleY < maxZoomLimit)
{
Animation animation = new ScaleAnimation(scaleX, (scaleX + 0.2f), scaleY, (scaleY + 0.2f), _X, _Y);
scaleX += 0.2f;
scaleY += 0.2f;
animation.Interpolator = new DecelerateInterpolator();
animation.Duration = duration;
animation.StartOffset = offset;
animation.FillAfter = true;
v.StartAnimation(animation);
}
}
private void _Zoom_Out(View v)
{
if (scaleX > minZoomLimit && scaleY > minZoomLimit)
{
Animation animation = new ScaleAnimation(scaleX, (scaleX - 0.2f), scaleY, (scaleY - 0.2f), _X, _Y);
scaleY -= 0.2f;
scaleX -= 0.2f;
animation.Interpolator = new DecelerateInterpolator();
animation.Duration = duration;
animation.StartOffset = offset;
animation.FillAfter = true;
v.StartAnimation(animation);
}
}
I am worried about this for about a week.
How do I keep from leaving the screen?
Adjusting the scale? How do I touch the scale?
Zoom in and Zoom out using the Button
-> resolution
Moving images with Zoom in using Button
-> resolution
If you move it after Zoom in, start with moving the image to a strange place.
-> resolution
Layout out of range
-> resolution
Move only within layout range (Unresolved)
Modify the if condition in your _MoveTo method. The x, y is the coordinate of the top left corner of your view. Calculate the width and height of the imageview, make sure the x and y value is smaller than 0 and not smaller than the value of screenwidth minus the imageview width.
For example:
private void _MoveToX(float xX)
{
float futureX = _Main_Background.GetX() + xX;
if (futureX <=0 && futureX >=YourScreenWidth -(_Main_Background.Width * scaleX))
{
_Main_Background.SetX(futureX);
Console.WriteLine("futureY : " + (_Main_Background.Height * scaleX).ToString());
Console.WriteLine("futureX : " + futureX.ToString());
}
}
private void _MoveToY(float yY)
{
float futureY = _Main_Background.GetY() + yY;
if (futureY <= 0 && futureY >=YourScreenHeight- (_Main_Background.Height * scaleY))
{
_Main_Background.SetY(futureY);
Console.WriteLine("futureY : " + (_Main_Background.Height * scaleY).ToString());
Console.WriteLine("futureY : " + futureY.ToString());
}
}

Android SurfaceView onTouchEvent not getting called

I'm developing a game using SurfaceView which listens to touch events. The onTouchEvent method in SurfaceView works fine for many of the devices, but in some devices, sometimes it doesn't get called (Moto X Style is the one) and my app also stops responding.
I guess that this might be due to the overloading of main thread due to which onTouchEvent is starving.
Could some Android experts over here give me some tips to reduce the load on main thread if it's getting overloaded, or there might be some other reason which may cause this
The code is quite complex but still I'm posting some if you want to go through it
GameLoopThread
public class GameLoopThread extends Thread{
private GameView view;
// desired fps
private final static int MAX_FPS = 120;
// maximum number of frames to be skipped
private final static int MAX_FRAME_SKIPS = 5;
// the frame period
private final static int FRAME_PERIOD = 1000 / MAX_FPS;
private boolean running = false;
public GameLoopThread(GameView view){
this.view = view;
}
public void setRunning(boolean running){
this.running = running;
}
public boolean isRunning() {
return running;
}
#Override
public void run() {
Canvas canvas;
long beginTime; // the time when the cycle begun
long timeDiff; // the time it took for the cycle to execute
int sleepTime; // ms to sleep (<0 if we're behind)
int framesSkipped; // number of frames being skipped
while (running) {
canvas = null;
// try locking the canvas for exclusive pixel editing
// in the surface
try {
canvas = view.getHolder().lockCanvas();
synchronized (view.getHolder()) {
beginTime = System.nanoTime();
framesSkipped = 0; // resetting the frames skipped
// update game state
// render state to the screen
// draws the canvas on the panel
this.view.draw(canvas);
// calculate how long did the cycle take
timeDiff = System.nanoTime() - beginTime;
// calculate sleep time
sleepTime = (int)(FRAME_PERIOD - timeDiff/1000000);
if (sleepTime > 0) {
// if sleepTime > 0 we're OK
try {
// send the thread to sleep for a short period
// very useful for battery saving
Thread.sleep(sleepTime);
} catch (InterruptedException e) {}
}
while (sleepTime < 0 && framesSkipped < MAX_FRAME_SKIPS) {
// update without rendering
// add frame period to check if in next frame
sleepTime += FRAME_PERIOD;
framesSkipped++;
}
}
}
finally {
// in case of an exception the surface is not left in
// an inconsistent state
view.getHolder().unlockCanvasAndPost(canvas);
} // end finally
}
}
}
GameView
public class GameView extends SurfaceView {
ArrayList<Bitmap> circles = new ArrayList<>();
int color;
public static boolean isGameOver;
public GameLoopThread gameLoopThread;
Circle circle; // Code for Circle class is provided below
public static int score = 0;
public static int stars = 0;
final Handler handler = new Handler();
int remainingTime;
boolean oneTimeFlag;
Bitmap replay;
Bitmap home;
Bitmap star;
int highScore;
boolean isLeaving;
public GameView(Context context, ArrayList<Bitmap> circles, int color) {
super(context);
this.circles = circles;
this.color = color;
oneTimeFlag = true;
gameLoopThread = new GameLoopThread(GameView.this);
getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (!gameLoopThread.isRunning()) {
gameLoopThread.setRunning(true);
gameLoopThread.start();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
gameLoopThread.setRunning(false);
gameLoopThread = new GameLoopThread(GameView.this);
}
});
initializeCircles();
if(!gameLoopThread.isRunning()) {
gameLoopThread.setRunning(true);
gameLoopThread.start();
}
}
public void initializeCircles() {
ArrayList<String> numbers = new ArrayList<>();
for(int i=0;i<10;i++)
numbers.add(i+"");
Random random = new Random();
int position = random.nextInt(4);
numbers.remove(color + "");
int p1 = position;
int r1 = Integer.valueOf(numbers.get(random.nextInt(9)));
numbers.remove(r1+"");
int r2 = Integer.valueOf(numbers.get(random.nextInt(8)));
numbers.remove(r2 + "");
int r3 = Integer.valueOf(numbers.get(random.nextInt(7)));
ArrayList<Bitmap> bitmaps = new ArrayList<>();
if(position == 0) {
bitmaps.add(circles.get(color));
bitmaps.add(circles.get(r1));
bitmaps.add(circles.get(r2));
bitmaps.add(circles.get(r3));
}
else if(position == 1) {
bitmaps.add(circles.get(r1));
bitmaps.add(circles.get(color));
bitmaps.add(circles.get(r2));
bitmaps.add(circles.get(r3));
}
else if(position == 2) {
bitmaps.add(circles.get(r1));
bitmaps.add(circles.get(r2));
bitmaps.add(circles.get(color));
bitmaps.add(circles.get(r3));
}
else {
bitmaps.add(circles.get(r1));
bitmaps.add(circles.get(r2));
bitmaps.add(circles.get(r3));
bitmaps.add(circles.get(color));
}
numbers = new ArrayList<>();
for(int i=0;i<10;i++)
numbers.add(i+"");
position = random.nextInt(4);
numbers.remove(color + "");
r1 = Integer.valueOf(numbers.get(random.nextInt(9)));
numbers.remove(r1 + "");
r2 = Integer.valueOf(numbers.get(random.nextInt(8)));
numbers.remove(r2 + "");
r3 = Integer.valueOf(numbers.get(random.nextInt(7)));
if(position == 0) {
bitmaps.add(circles.get(color));
bitmaps.add(circles.get(r1));
bitmaps.add(circles.get(r2));
bitmaps.add(circles.get(r3));
}
else if(position == 1) {
bitmaps.add(circles.get(r1));
bitmaps.add(circles.get(color));
bitmaps.add(circles.get(r2));
bitmaps.add(circles.get(r3));
}
else if(position == 2) {
bitmaps.add(circles.get(r1));
bitmaps.add(circles.get(r2));
bitmaps.add(circles.get(color));
bitmaps.add(circles.get(r3));
}
else {
bitmaps.add(circles.get(r1));
bitmaps.add(circles.get(r2));
bitmaps.add(circles.get(r3));
bitmaps.add(circles.get(color));
}
circle = new Circle(this, bitmaps, circles, p1, position, color, getContext());
}
#Override
public void draw(Canvas canvas) {
if(canvas != null) {
super.draw(canvas);
canvas.drawColor(Color.WHITE);
if(!isGameOver && timer != null)
stopTimerTask();
try {
circle.draw(canvas);
} catch (GameOverException e) {
isGameOver = true;
if(isLeaving)
gameOver(canvas);
else if(GameActivity.counter > 0) {
gameOver(canvas);
GameActivity.counter++;
} else {
if (oneTimeFlag) {
int size1 = 200 * GameActivity.SCREEN_HEIGHT / 1280;
int size2 = 125 * GameActivity.SCREEN_HEIGHT / 1280;
float ratio = (float) GameActivity.SCREEN_HEIGHT / 1280;
replay = GameActivity.decodeSampledBitmapFromResource(getResources(), R.drawable.replay, size1, size1);
home = GameActivity.decodeSampledBitmapFromResource(getResources(), R.drawable.home, size2, size2);
continueButton = GameActivity.decodeSampledBitmapFromResource(getContext().getResources(), R.drawable.button, (int) (540 * ratio), (int) (100 * ratio));
star = GameActivity.decodeSampledBitmapFromResource(getContext().getResources(), R.drawable.star1, (int) (220 * ratio), (int) (220 * ratio));
int w = (int) ((float) GameActivity.SCREEN_WIDTH * 0.9);
oneTimeFlag = false;
}
if (askPurchaseScreen == 2) {
gameOver(canvas);
} else {
canvas.drawColor(Circle.endColor);
}
}
}
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
circle.onTouch(x, y);
return true;
}
}
Circle
public class Circle {
int x;
int y1;
int y2;
public static float speedY1 = 12.5f*(float)GameActivity.SCREEN_HEIGHT/1280;
public static float speedY2 = 12.5f*(float)GameActivity.SCREEN_HEIGHT/1280;
ArrayList<Bitmap> bitmaps;
GameView gameView;
int p1; // Position of required circle in slot 1
int p2; // Position of required circle in slot 2
int color;
int tempColor;
int width;
Context context;
// Centers of required circle
float centerX1;
float centerX2;
float centerY1;
float centerY2;
ArrayList<Bitmap> circles = new ArrayList<>();
boolean touchedFirst;
boolean touchedSecond;
int count1 = 1; // Slot 1 circle radius animation
int count2 = 1; // Slot 2 circle radius animation
float tempSpeedY1;
float tempSpeedY2;
boolean stopY1;
boolean stopY2;
int barCounter = 1;
int loopCount = 0;
int endGameCount = 0; // Count to move circle upwards
double limit;
float endRadiusSpeed;
int endSlot; // Where you died
int endRadiusCount = 0; // Count to increase circle radius
int barEndCounter = 1;
final Handler handler = new Handler();
boolean exception;
public static int endColor;
public Circle(GameView gameView, ArrayList<Bitmap> bitmaps, ArrayList<Bitmap> circles, int p1, int p2, int color, Context context) {
this.gameView = gameView;
this.bitmaps = bitmaps;
this.circles = circles;
this.p1 = p1;
this.p2 = p2;
this.color = color;
this.context = context;
width = GameActivity.SCREEN_WIDTH / 4 - 10;
x = 10;
y1 = 0;
y2 = -(GameActivity.SCREEN_HEIGHT + width) / 2;
centerX1 = x + p1 * (10 + width) + width / 2;
centerY1 = y1 + width / 2;
centerX2 = x + p2 * (10 + width) + width / 2;
centerY2 = y2 + width / 2;
}
public void update() throws GameOverException {
y1+= speedY1;
y2+= speedY2;
centerY1+= speedY1;
centerY2+= speedY2;
float ratio = (float)GameActivity.SCREEN_HEIGHT/1280;
limit = width/(20*ratio);
if(y1 >= gameView.getHeight()) {
loopCount++;
if(touchedFirst)
touchedFirst = false;
else {
speedY1 = speedY2 = -(12.5f * ratio);
endColor = bitmaps.get(p1).getPixel(width/2, width/2);
endGameCount += 1;
endSlot = 1;
}
if(endGameCount == 0) {
if (stopY1) {
tempSpeedY1 = speedY1;
speedY1 = 0;
ArrayList<Integer> numbers = new ArrayList<>();
for (int i = 0; i < 10; i++) {
if (i != color)
numbers.add(i);
}
tempColor = numbers.get(new Random().nextInt(9));
}
y1 = -(gameView.getWidth() / 4 - 10);
count1 = 1;
setBitmaps(1);
}
}
else if(y2 >= gameView.getHeight()) {
loopCount++;
if(touchedSecond)
touchedSecond = false;
else {
speedY1 = speedY2 = -(12.5f * ratio);
endColor = bitmaps.get(p2 + 4
).getPixel(width/2, width/2);
endGameCount += 1;
endSlot = 2;
}
if(endGameCount == 0) {
if (stopY2) {
tempSpeedY2 = speedY2;
speedY2 = 0;
}
y2 = -(gameView.getWidth() / 4 - 10);
count2 = 1;
setBitmaps(2);
}
}
}
public void setBitmaps(int slot) {
ArrayList<String> numbers = new ArrayList<>();
for(int i=0;i<10;i++)
numbers.add(i+"");
Random random = new Random();
int position = random.nextInt(4);
numbers.remove(color + "");
int r1 = Integer.valueOf(numbers.get(random.nextInt(9)));
numbers.remove(r1+"");
int r2 = Integer.valueOf(numbers.get(random.nextInt(8)));
numbers.remove(r2 + "");
int r3 = Integer.valueOf(numbers.get(random.nextInt(7)));
if(position == 0) {
bitmaps.set((slot - 1)*4, circles.get(color));
bitmaps.set((slot - 1)*4 + 1, circles.get(r1));
bitmaps.set((slot - 1)*4 + 2, circles.get(r2));
bitmaps.set((slot - 1)*4 + 3, circles.get(r3));
}
else if(position == 1) {
bitmaps.set((slot - 1)*4, circles.get(r1));
bitmaps.set((slot - 1)*4 + 1, circles.get(color));
bitmaps.set((slot - 1)*4 + 2, circles.get(r2));
bitmaps.set((slot - 1)*4 + 3, circles.get(r3));
}
else if(position == 2) {
bitmaps.set((slot - 1)*4, circles.get(r1));
bitmaps.set((slot - 1)*4 + 1, circles.get(r2));
bitmaps.set((slot - 1)*4 + 2, circles.get(color));
bitmaps.set((slot - 1)*4 + 3, circles.get(r3));
} else {
bitmaps.set((slot - 1)*4,circles.get(r1));
bitmaps.set((slot - 1)*4 + 1,circles.get(r2));
bitmaps.set((slot - 1)*4 + 2,circles.get(r3));
bitmaps.set((slot - 1)*4 + 3,circles.get(color));
}
if(slot == 1) {
p1 = position;
centerX1 = x+position*(10 + width) + width/2;
centerY1 = y1 + width/2;
}
else if(slot == 2) {
p2 = position;
centerX2 = x+position*(10 + width) + width/2;
centerY2 = y2 + width/2;
}
}
public void onTouch(float X, float Y) {
int radius = (gameView.getWidth() / 4 - 10) / 2;
if(endGameCount == 0) {
if ((X >= centerX1 - radius) && (X <= centerX1 + radius) && (Y >= centerY1 - radius) && (Y <= centerY1 + radius)) {
GameView.score++;
touchedFirst = true;
centerX1 = centerY1 = -1;
if(p1 == (timerCount - 1) && timer != null && starSlot == 1) {
GameView.stars++;
starCollected = true;
timerCount = 0;
stopTimerTask(0);
}
} else if ((X >= centerX2 - radius) && (X <= centerX2 + radius) && (Y >= centerY2 - radius) && (Y <= centerY2 + radius)) {
GameView.score++;
touchedSecond = true;
centerX2 = centerY2 = -1;
if(p2 == (timerCount - 1) && timer != null && starSlot == 2) {
GameView.stars++;
starCollected = true;
timerCount = 0;
stopTimerTask(0);
}
} else {
endSlot = 0;
if ((Y >= centerY1 - radius) && (Y <= centerY1 + radius)) {
endSlot = 1;
if (X >= 10 && X <= 10 + 2 * radius) {
p1 = 0;
centerX1 = 10 + radius;
} else if (X >= 20 + 2 * radius && X <= 20 + 4 * radius) {
p1 = 1;
centerX1 = 20 + 3 * radius;
} else if (X >= 30 + 4 * radius && X <= 30 + 6 * radius) {
p1 = 2;
centerX1 = 30 + 5 * radius;
} else if (X >= 40 + 6 * radius && X <= 40 + 8 * radius) {
p1 = 3;
centerX1 = 40 + 2 * radius;
} else
endSlot = 0;
} else if ((Y >= centerY2 - radius) && (Y <= centerY2 + radius)) {
endSlot = 2;
if (X >= 10 && X <= 10 + 2 * radius) {
p2 = 0;
centerX2 = 10 + radius;
} else if (X >= 20 + 2 * radius && X <= 20 + 4 * radius) {
p2 = 1;
centerX2 = 20 + 3 * radius;
} else if (X >= 30 + 4 * radius && X <= 30 + 6 * radius) {
p2 = 2;
centerX2 = 30 + 5 * radius;
} else if (X >= 40 + 6 * radius && X <= 40 + 8 * radius) {
p2 = 3;
centerX2 = 40 + 2 * radius;
} else
endSlot = 0;
}
if (endSlot != 0) {
speedY1 = speedY2 = 0;
limit = endGameCount = 6;
if (endSlot == 1) {
endColor= bitmaps.get(p1).getPixel(width/2, width/2);
} else {
endColor = bitmaps.get(p2 + 4).getPixel(width/2, width/2);
}
}
}
if (GameView.score % 5 == 0 && GameView.score <= 110 && barCounter == 1) {
float ratio = (float)GameActivity.SCREEN_HEIGHT/1280;
speedY1 += ratio*0.5;
speedY2 += ratio*0.5;
}
if (GameView.score > 0 && GameView.score % 15 == 14) {
if(isOddScore)
stopY1 = true;
else
stopY2 = true;
}
if (GameView.score > 0 && GameView.score % 15 == 0 && barCounter == 1) {
if(isOddScore)
stopY2 = true;
else
stopY1 = true;
}
if (GameView.score % 15 == 1)
barCounter = 1;
}
}
public void draw(Canvas canvas) throws GameOverException {
GameView.isGameOver = false;
if(exception)
throw new GameOverException(color);
update();
for(int i=0;i<bitmaps.size();i++) {
if(i<4) {
Rect rect = new Rect(x+i*(10 + width),y1,(x+width)*(i+1),y1+width);
if(endGameCount == Math.ceil(limit) && endSlot == 1) {
if(i == p1) {
endRadiusCount += 1;
if (endRadiusCount > 23) {
star.recycle();
loopCount = loopCount%starInterval;
Cryptography.saveFile((loopCount + "").getBytes(), context, "interval");
endGameCount = 0;
exception = true;
throw new GameOverException(color);
}
rect = new Rect(x + i * (10 + width) - endRadiusCount*(int)Math.ceil(endRadiusSpeed), y1 - endRadiusCount*(int)Math.ceil(endRadiusSpeed), (x + width) * (i + 1) + endRadiusCount*(int)Math.ceil(endRadiusSpeed), y1 + width + endRadiusCount*(int)Math.ceil(endRadiusSpeed));
canvas.drawBitmap(bitmaps.get(i), null, rect, null);
}
}
// TOUCH ANIMATION : DIMINISH CIRCLE
else if(i==p1 && touchedFirst) {
rect = new Rect(x + i * (10 + width) + 3*count1 + ((int)speedY1-15), y1 + 3*count1 + ((int)speedY1-15), (x + width) * (i + 1) - 3*count1 - ((int)speedY1-15), y1 + width - 3*count1 - ((int)speedY1-15));
canvas.drawBitmap(bitmaps.get(i), null, rect, null);
count1++;
}
else if(endSlot != 2) {
canvas.drawBitmap(bitmaps.get(i), null, rect, null);
if(timerCount > 0 && starSlot == 1) {
int size = width * 30 / 50;
int difference = (width - size) / 2;
Rect starRect = new Rect(x + (timerCount - 1) * (10 + width) + difference, y1 + difference, (x + width) * (timerCount) - difference, y1 + width - difference);
canvas.drawBitmap(star, null, starRect, null);
}
}
}
if(i >= 4) {
Rect rect = new Rect(x + (i % 4) * (10 + width), y2, (x + width) * ((i % 4) + 1), y2 + width);
if(endGameCount == Math.ceil(limit) && endSlot == 2) {
if((i%4)==p2) {
endRadiusCount += 1;
if (endRadiusCount > 23) {
star.recycle();
loopCount = loopCount%starInterval;
Cryptography.saveFile((loopCount + "").getBytes(), context, "interval");
endGameCount = 0;
exception = true;
throw new GameOverException(color);
}
rect = new Rect(x + (i % 4) * (10 + width) - endRadiusCount*(int)Math.ceil(endRadiusSpeed), y2 - endRadiusCount*(int)Math.ceil(endRadiusSpeed), (x + width) * ((i % 4) + 1) + endRadiusCount*(int)Math.ceil(endRadiusSpeed), y2 + width + endRadiusCount*(int)Math.ceil(endRadiusSpeed));
canvas.drawBitmap(bitmaps.get(i), null, rect, null);
}
}
else if((i%4)==p2 && touchedSecond) {
rect = new Rect(x + (i % 4) * (10 + width) + 3*count2 + ((int)speedY1-15), y2 + 3*count2 + ((int)speedY1-15), (x + width) * ((i % 4) + 1) - 3*count2 - ((int)speedY1-15), y2 + width - 3*count2 - ((int)speedY1-15));
canvas.drawBitmap(bitmaps.get(i), null, rect, null);
count2++;
}
else if(endSlot != 1) {
canvas.drawBitmap(bitmaps.get(i), null, rect, null);
if(timerCount > 0 && starSlot == 2) {
int size = width * 30 / 50;
int difference = (width - size) / 2;
Rect starRect = new Rect(x + (timerCount - 1) * (10 + width) + difference, y2 + difference, (x + width) * (timerCount) - difference, y2 + width - difference);
canvas.drawBitmap(star, null, starRect, null);
}
}
}
}
Rect src = new Rect(circles.get(color).getWidth()/2 - 10,circles.get(color).getHeight()/2 - 10,circles.get(color).getWidth()/2 + 10,circles.get(color).getHeight()/2 + 10);
Rect dst;
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTextAlign(Paint.Align.RIGHT);
paint.setTypeface(Typeface.SANS_SERIF);
paint.setTextSize(72 * ratio);
canvas.drawText(GameView.score + " ", GameActivity.SCREEN_WIDTH, width / 2, paint);
dst = new Rect(5,5, (int) (120 * ratio - 5), (int) (120 * ratio - 5));
canvas.drawBitmap(star,null,dst,null);
paint.setTextAlign(Paint.Align.LEFT);
canvas.drawText("" + GameView.stars, 120 * ratio, width/2, paint);
}
}
Don't override draw(). That's used to render the View, not the Surface, and you generally shouldn't override that method even if you're creating a custom View:
When implementing a view, implement onDraw(android.graphics.Canvas) instead of overriding this method.
SurfaceViews have two parts, the Surface and the View. The View part is handled like any other View, but is generally just a transparent "hole" in the layout. The Surface is a separate layer that, by default, sits behind the View layer. Whatever you draw on the Surface "shows through" the transparent hole.
By overriding draw() you're drawing on the View whenever the View UI is invalidated. You're also calling draw() from the render thread, so you're drawing on the Surface, but with default Z-ordering you can't see that because the View contents are fully opaque. You will reduce your impact on the UI thread by not drawing everything in two different layers.
Unless you're deliberately drawing on the View, it's best to avoid subclassing SurfaceView entirely, and just use it as a member.
Because your draw code is synchronized, the two draw passes will not execute concurrently. That means your View layer draw call will block waiting for the Surface layer rendering to complete. Canvas rendering on a Surface is not hardware-accelerated, so if you're touching a lot of pixels it can get slow, and the UI thread will have to wait for it to run. That wouldn't be so bad, but you're holding on to the mutex while you're sleeping, which means the only opportunity for the main UI thread to run comes during the brief instant when the loop wraps around. The thread scheduler does not guarantee fairness, so it's entirely possible to starve the main UI thread this way.
If you change #override draw() to myDraw() things should get better. You should probably move your sleep call out of the synchronized block just on general principles, or work to eliminate it entirely. You might also want to consider using a custom View instead of SurfaceView.
On an unrelated note, you should probably avoid doing this every update:
Random random = new Random();
for the reasons noted here.
Successfully solved the issue. Can't imagine that the solution would be this much simple as compared to the problem that I was considering that complex. Just reduced the frame rate from 120 to 90 and guess what, it worked like charm!
Due to a high frame rate, the SurfaceView was busy doing all the drawing and onTouchEvent() method had to starve

Android surfaceView Block Scaling error Rendering

I have problem, with rendering blocks after reScalling (zoom in-out) whole thing in my game
(sorry with my eng syntax , cuz Eng not my native language)
first look at my video
>Error Rendering Video
there are problem , When it's rendering blocks after change blocks scale to some specific number
look at my code
GameLoopThread.java
public class GameLoopThread extends Thread {
static long FPS = 20;
private GameView view;
private boolean running = false;
public GameLoopThread ( GameView view ) {
this.view = view;
}
#Override
public void run () {
long ticksPS = 1000 / GameLoopThread.FPS; // 0.05 second (50) ;
long startTime;
long delayDelta = 0;
long tmpDelta = 0;
while (this.running) {
Canvas c = null;
startTime = System.currentTimeMillis();
try {
c = this.view.getHolder().lockCanvas();
synchronized (this.view.getHolder()) {
this.view.onDraw(c);
}
ClientCoreStatic.clientGear.updateWorlds();
}
catch (NullPointerException e) {
e.printStackTrace();
}
finally {
if (c != null) this.view.getHolder().unlockCanvasAndPost(c);
}
// 50
// sleepTime = ticksPS - (System.currentTimeMillis() - startTime);
tmpDelta = (System.currentTimeMillis() - startTime);
// time use Should below than 50
try {
if (tmpDelta > ticksPS) delayDelta += tmpDelta - ticksPS;
// d.pl("gameloop thread + " + delayDelta);
if (delayDelta > 0) {
//Thread.sleep(10);
if (ticksPS >= tmpDelta) {
delayDelta -= ticksPS - tmpDelta;
}
}
else {
delayDelta = 0;
Thread.sleep(ticksPS - tmpDelta);
}
if (this.view.hashCode() != ClientStatic.gameView.hashCode()) {
this.setRunning(false);
GameView.parentActivity.finish();
break;
}
}
catch (Exception e) {
e.printStackTrace();
d.pl("gameloop error");
}
}
}
GameView.java
#Override
public boolean onTouchEvent ( MotionEvent event ) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
// true
if (event.getPointerCount() == 1 ) {
if (GameView.spriteKeypadcircle.isCollition(
event.getX(),
event.getY()) == true) // d.pl("true..");
return true;
if (GameView.spriteBlocks.isCollition(event.getX(), event.getY())) {
// check
GameView.spriteBlocks.isCollitionOnBlock(event.getX(),event.getY());
d.pl("touching at "+ event.getX() + "," + event.getY());
return true;
}
}
if (event.getPointerCount() == 2 ) {
d.pl("distance 1 " +
GameView.distance1XY[0][0] +
"," +
GameView.distance1XY[0][1] +
" + " +
GameView.distance1XY[1][0] +
"," +
GameView.distance1XY[1][1] +
" | " +
GameView.distance2XY[0][0] +
"," +
GameView.distance2XY[0][1] +
" + " +
GameView.distance2XY[1][0] +
"," +
GameView.distance2XY[1][1]);
for (int size = event.getPointerCount(), i = 0; i < size; i++) {
// PointF point = mActivePointers.get(event.getPointerId(i));
// if (point != null) {
// point.x = event.getX(i);
// point.y = event.getY(i);
// }
float x = event.getX(i);
float y = event.getY(i);
if (!GameView.spriteBlocks.isCollition(x, y)) break;
GameView.distance2XY[i][0] = x;
GameView.distance2XY[i][1] = y;
} // for
// after get position
// check distance
double tmp1 = Math.sqrt((Math.pow(GameView.distance1XY[0][0] -
GameView.distance1XY[1][0], 2)) +
(Math.pow(GameView.distance1XY[0][1] -
GameView.distance1XY[1][1], 2)));
double tmp2 = Math.sqrt((Math.pow(GameView.distance2XY[0][0] -
GameView.distance2XY[1][0], 2)) +
(Math.pow(GameView.distance2XY[0][1] -
GameView.distance2XY[1][1], 2)));
GameView.newDistance = Math.abs(tmp1 - tmp2);
if (GameView.newDistance > 200) { // change too much
GameView.distance1XY[0][0] = GameView.distance2XY[0][0];
GameView.distance1XY[0][1] = GameView.distance2XY[0][1];
GameView.distance1XY[1][0] = GameView.distance2XY[1][0];
GameView.distance1XY[1][1] = GameView.distance2XY[1][1];
return true;
}
// if (newDistance < 100) break;
// if (newD < 100) break;
if (tmp1 < tmp2)
SpriteBlocks.viewScale += GameView.newDistance / 1000;
else
SpriteBlocks.viewScale -= GameView.newDistance / 1000;
if (SpriteBlocks.viewScale < 0.2) SpriteBlocks.viewScale = 0.2;
if (SpriteBlocks.viewScale > 10) SpriteBlocks.viewScale = 10;
GameView.spriteBlocks.updateScale();
GameView.distance1XY[0][0] = GameView.distance2XY[0][0];
GameView.distance1XY[0][1] = GameView.distance2XY[0][1];
GameView.distance1XY[1][0] = GameView.distance2XY[1][0];
GameView.distance1XY[1][1] = GameView.distance2XY[1][1];
return true;
}
return true;
case MotionEvent.ACTION_DOWN:
return true;
case MotionEvent.ACTION_UP:
return true;
}
return false;
}
#Override
protected void onDraw ( Canvas canvas ) {
canvas.drawColor(Color.GRAY);
GameView.spriteBlocks.onDraw(canvas);
GameView.spriteCharStand.onDraw(canvas);
GameView.spriteKeypadcircle.onDraw(canvas);
}
SpriteBlocks.java
public SpriteBlocks ( GameView gameView, Bitmap bmp ) {
this.bmp = bmp;
SpriteBlocks.width = bmp.getWidth() / SpriteBlocks.BMP_COLUMNS;
SpriteBlocks.height = bmp.getHeight() / SpriteBlocks.BMP_ROWS;
SpriteBlocks.widthPixels = Resources.getSystem().getDisplayMetrics().widthPixels;
SpriteBlocks.heightPixels = Resources.getSystem().getDisplayMetrics().heightPixels;
SpriteBlocks.centerXScreen = SpriteBlocks.widthPixels / 2;
SpriteBlocks.centerYScreen = SpriteBlocks.heightPixels / 2;
// System.out.println("fififi " + this.weightPixels + "," +
// this.heightPixels);
updateScale();
src2 = new Rect(0, 0, 400, 400);
paintTextPlayCur.setColor(Color.BLACK);
paintTextPlayCur.setTextSize(32);
paintTextSelectBlock.setColor(Color.RED);
paintTextSelectBlock.setTextSize(32);
}
public void updateScale () {
// SpriteBlocks.viewScale = 1;
SpriteBlocks.curBlockWidth = SpriteBlocks.viewScale *
SpriteBlocks.width;
SpriteBlocks.xBlockCount = Math.round(SpriteBlocks.widthPixels /
SpriteBlocks.curBlockWidth);
SpriteBlocks.yBlockCount = Math.round(SpriteBlocks.heightPixels /
SpriteBlocks.curBlockWidth);
SpriteCharStand.curPlayerRenderHeight = SpriteCharStand.playerRenderHeight *
SpriteBlocks.viewScale;
SpriteCharStand.curPlayerRenderWidth = SpriteCharStand.playerRenderWidth *
SpriteBlocks.viewScale;
SpriteCharStand.playerLeftTopX = SpriteBlocks.centerXScreen -
(SpriteCharStand.curPlayerRenderWidth / 2);
SpriteCharStand.playerLeftTopY = SpriteBlocks.centerYScreen -
(SpriteCharStand.curPlayerRenderHeight / 2);
SpriteCharStand.playerRightDownX = SpriteBlocks.centerXScreen +
(SpriteCharStand.curPlayerRenderWidth / 2);
SpriteCharStand.playerRightDownY = SpriteBlocks.centerYScreen +
(SpriteCharStand.curPlayerRenderHeight / 2);
d.pl("viewScale = " +
SpriteBlocks.viewScale +
", width = " +
SpriteBlocks.curBlockWidth);
}
#Override
public void onDraw ( Canvas canvas ) {
update();
if (ClientStatic.minePlayer == null) {
ClientStatic.minePlayer = ClientStatic.playerList
.get(ClientStatic.mineID);
if (ClientStatic.playerList.get(ClientStatic.mineID) == null) {
d.pl(" uuuu " + ClientStatic.mineID);
return;
}
}
// center screen point is this location
minePlayerX = ClientStatic.minePlayer.getLocation().getX();// + 0.5;
minePlayerY = ClientStatic.minePlayer.getLocation().getY();// + 1;
double adderPoint = 0.1;
for ( double adder = 0 ; adder <= 1 ; adder += adderPoint) {
minePlayerX += adderPoint;
// left top of screen is this location
bX = ((minePlayerX) - (SpriteBlocks.xBlockCount / 2) - 1);
bY = ((minePlayerY) + (SpriteBlocks.yBlockCount / 2) + 1);
// right down of screen is this position
cX = ((minePlayerX) + (SpriteBlocks.xBlockCount / 2) + 1);
cY = ((minePlayerY) - (SpriteBlocks.yBlockCount / 2) - 1);
// (SpriteCharStand.curPlayerRenderWidth / 2)
Material me;
Block bbo;
leftXdiff = (minePlayerX * 100) % 100;
leftYdiff = (minePlayerY * 100) % 100;
/*
* leftXdiff = Math.abs(leftXdiff);
* leftYdiff = Math.abs(leftYdiff);
*/
// calculating them from scale
leftXdiff = (curBlockWidth * leftXdiff) / 100;
leftYdiff = (curBlockWidth * leftYdiff) / 100;
// d.pl("cur x " + minePlayerX + " |m " + leftXdiff + " |bx " + bX);
for (double xloop = bX; xloop <= cX; xloop++) { // loop all position X
//for (double yloop = bY; yloop >= cY; yloop--) { // loop all position
// Y
for (double yloop = 140.5 ; yloop == 140.5 ; yloop ++) {
// range Y
if ((yloop < 0) || yloop > (FixVariable.CHUNK_HEIGHT - 1)) {
continue;
}
// get block of that location
bbo = ClientStatic.minePlayer
.getLocation()
.getWorld()
.getBlockAt(((xloop)), ((yloop)));
me = Material.getMaterial(bbo.getTypeId());
srcX = me.getX(bbo.getData()) * SpriteBlocks.width;
srcY = me.getY(bbo.getData()) * SpriteBlocks.height;
srcKey = ((double) srcX * 10) + ((double) (srcY));
src = srcList.get(srcKey);
if (src == null) {
src = new Rect(srcX, srcY, srcX + SpriteBlocks.width, srcY +
SpriteBlocks.height);
srcList.put(srcKey, src);
}
// position to drawing
if (xloop == 5 && yloop == 140.5) {
d.pl("SPY!! " + tmpXPosition + " = " + xloop + " - " + bX + " ) * 200 -" + leftXdiff);
}
tmpXPosition = ((xloop - bX) * SpriteBlocks.curBlockWidth) -
(leftXdiff );
if (xloop == 5 && yloop == 140.5) {
if (me != Material.BED){
d.pl("bed is spy");
}
if (Math.abs(lastTmpXPosition- tmpXPosition) < 1 &&
(Math.abs(lastTmpXPosition- tmpXPosition) > 0)) {
System.out.println("WT " + (Math.abs(lastTmpXPosition- tmpXPosition)));
}
d.pl("lastTmpXPos = " + lastTmpXPosition + " | " + tmpXPosition);
if (lastTmpXPosition != tmpXPosition) {
lastTmpXPosition = tmpXPosition;
}
}
tmpYPosition = (((SpriteBlocks.yBlockCount) - (yloop - cY + (10*adder) )) * SpriteBlocks.curBlockWidth) +
(leftYdiff);
if (dst == null) {
dst = new Rect();
}
dst.set(
(int) tmpXPosition,
(int) tmpYPosition,
(int) (tmpXPosition + SpriteBlocks.curBlockWidth),
(int) (tmpYPosition + SpriteBlocks.curBlockWidth));
canvas.drawBitmap(bmp, src, dst, null);
dst2.set(
(int) (tmpXPosition),
(int) (tmpYPosition),
(int) (tmpXPosition + SpriteBlocks.curBlockWidth),
(int) (tmpYPosition + SpriteBlocks.curBlockWidth));
canvas.drawBitmap(GameView.bmpRect, src2, dst2, null);
// break;
}
} // for
bbo = ClientStatic.minePlayer
.getLocation()
.getWorld()
.getBlockAt(
ClientStatic.minePlayer.getLocation().getX(),
ClientStatic.minePlayer.getLocation().getY());
me = Material.getMaterial(bbo.getTypeId());
srcX = me.getX(bbo.getData()) * SpriteBlocks.width;
srcY = me.getY(bbo.getData()) * SpriteBlocks.height;
srcKey = ((double) srcX * 10) + ((double) (srcY));
tmpXPosition = 5;
tmpYPosition = 5;
dst.set(
(int) tmpXPosition,
(int) tmpYPosition,
(int) (tmpXPosition + SpriteBlocks.curBlockWidth),
(int) (tmpYPosition + SpriteBlocks.curBlockWidth));
canvas.drawText(
"playLoc " +
ClientStatic.minePlayer.getLocation().getX() +
"," +
ClientStatic.minePlayer.getLocation().getY(),
200,
200,
paintTextPlayCur);
canvas.drawBitmap(bmp, src, dst, null);
canvas.drawText(
"block " +
ClientStatic.minePlayer
.getLocation()
.getWorld()
.getBlockAt(
ClientStatic.minePlayer
.getLocation()
.getX(),
ClientStatic.minePlayer
.getLocation()
.getY())
.getTypeId() +
" | chunk " +
ClientStatic.minePlayer
.getLocation()
.getWorld()
.getChunkAt(
ClientStatic.minePlayer
.getLocation()
.getX())
.getChunkNumberX() +
" | " +
ClientStatic.minePlayer
.getLocation()
.getWorld()
.getChunkAt(
ClientStatic.minePlayer
.getLocation()
.getX()).getX()
,
200,
300,
paintTextPlayCur);
canvas.drawBitmap(bmp, src, dst, null);
// draw touch block
if (blockTouching != null) {
canvas.drawText("touch " +
blockTouching.getX() +
"," +
blockTouching.getY() +
" = " +
blockTouching.getTypeId() +
":" +
blockTouching.getData()
, 300, 400, paintTextSelectBlock);
}
} // adder
}

dynamically updating position of an object using accelerometer and gyroscope

I am a beginner in android programming. Below is the program which is updating current position of the object using accelerometer and gyroscope readings.My objective is to update the object's position on the screen. Currently the output of the program is it just displays the object and it doesn't update it's position. Can you please suggest me where i am going wrong.
Mainactivity.java
public class MainActivity extends Activity implements SensorEventListener {
CustomDrawableView mCustomDrawableView = null;
ShapeDrawable mDrawable = new ShapeDrawable();
int UPDATE_THRESHOLD=20;
Sensor accelerometer,gyroscope;
SensorManager sm,sm1;
TextView acceleration,rotation,c_x,c_y;
long mLastUpdate;
public static int x;
public static int y;
double GRAVITY_THRESH = 12;
double one_step_freeze = 0;
double SENSOR_INTERVAL = 0.02;
double STEP_INTERVAL_THRESH = 0.4;
double init_x = 1;
double init_y = 0;
double init_theta = 0;
static int ACCE_FILTER_DATA_MIN_TIME = 20; // 1000ms
long lastSaved = System.currentTimeMillis();
double step_counter = 0;
double current_x,current_y;
double one_step_happend = 0;
double accumulated_rad = 0;
double trace_x = init_x;
double trace_x_particle = init_x;
double trace_y = init_y;
double trace_y_particle = init_y;
double last_x = init_x;
double last_y = init_y;
double last_theta = init_theta;
double z_gy;
float acc_z,acc_x,acc_y;
SensorEventListener mSensorListenerAcc,mSensorListenerGyro;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
sm=(SensorManager)getSystemService(SENSOR_SERVICE);
sm1=(SensorManager)getSystemService(SENSOR_SERVICE);
mCustomDrawableView = new CustomDrawableView(this);
setContentView(mCustomDrawableView);
accelerometer=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
gyroscope=sm1.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
sm.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL );
sm1.registerListener(this,gyroscope,SensorManager.SENSOR_DELAY_NORMAL);
//acceleration=(TextView)findViewById(R.id.acceleration);
//rotation=(TextView)findViewById(R.id.rotation);
// c_x=(TextView)findViewById(R.id.c_x);
//c_y=(TextView)findViewById(R.id.c_y);
}
/*#Override
protected void onResume()
{
super.onResume();
//sm.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_FASTEST);
sm.registerListener(mSensorListenerAcc, accelerometer, SensorManager.SENSOR_DELAY_FASTEST);
sm1.registerListener(mSensorListenerGyro, gyroscope,SensorManager.SENSOR_DELAY_FASTEST);
//mLastUpdate=System.currentTimeMillis();
}
#Override
protected void onPause()
{
sm.unregisterListener(this);
}*/
#Override
public void onSensorChanged(SensorEvent event) {
/* long actualTime = System.currentTimeMillis();
if(actualTime-mLastUpdate > UPDATE_THRESHOLD){
mLastUpdate=actualTime;
}*/
if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
/*rotation.setText("Xg: " + event.values[0] +
"\nYg: " + event.values[1] +
"\nZg: " + event.values[2]);*/
z_gy= event.values[2];
}
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
/* acceleration.setText("X: " + event.values[0] +
"\nY: " + event.values[1] +
"\nZ: " + event.values[2]);*/
acc_x=event.values[1];
acc_y=event.values[2];
acc_z = event.values[2];
System.out.println("acc_z:" + Float.toString(acc_z));
if (acc_z > GRAVITY_THRESH && one_step_freeze == 0) {
System.out.println("entering1oop1");
one_step_happend = 1;
step_counter = step_counter + 1;
System.out.println("stepcounter: " + Double.toString(step_counter) + "==========================");
one_step_freeze = STEP_INTERVAL_THRESH / SENSOR_INTERVAL;
/*System.out.println("onestepfreeze_in_firstloop_aft_div: " + Double.toString(one_step_freeze));
System.out.println("exitingloop1");*/
}
if (one_step_freeze > 0) {
System.out.println("stepcounterin 2 loop: " + Double.toString(step_counter) + "==========================");
if ((System.currentTimeMillis() - lastSaved) > ACCE_FILTER_DATA_MIN_TIME) {
lastSaved = System.currentTimeMillis();
one_step_freeze = one_step_freeze - 1;
/* System.out.println("onestepfreeze2:" + Double.toString(one_step_freeze));
System.out.println("exitin 2loop");*/
}
}
if(one_step_happend==1){
// System.out.println("entered 3 loop:");
last_theta=accumulated_rad+last_theta;
// System.out.println("last_theta value: "+last_theta);
current_x=last_x+STRIDE_LENGTH*Math.cos(last_theta);
System.out.println("current_x value: " + current_x);
current_y=last_y+STRIDE_LENGTH*Math.sin(last_theta);
//System.out.println("current_y value: " + current_y);
// System.out.println("processing c_x");
//c_x.setText("c_x:" + current_x);
// System.out.println("processing c_y");
//c_y.setText("c_y:" + current_y);
last_x = current_x;
// System.out.println("last_x value: " + last_x);
last_y = current_y;
// System.out.println("last_y value: "+last_y);
accumulated_rad = 0;
one_step_happend = 0;
}else{
accumulated_rad= accumulated_rad + z_gy * SENSOR_INTERVAL;
System.out.println("accumulatedrad: "+accumulated_rad);
}
}
/*if ((acc_z > GRAVITY_THRESH) && (one_step_freeze == 0)) {
one_step_happend = 1;
step_counter = step_counter + 1;
System.out.println("stepcounter: " + Double.toString(step_counter) + "==========================");
one_step_freeze = STEP_INTERVAL_THRESH / SENSOR_INTERVAL;
//System.out.println("onestepfreeze2:"+Double.toString(one_step_freeze)+"==========================");
/*spcounter.setText((int) step_counter);
}*/
/*if (one_step_freeze > 0) {
if ((System.currentTimeMillis() - lastSaved) > ACCE_FILTER_DATA_MIN_TIME) {
lastSaved = System.currentTimeMillis();
one_step_freeze = one_step_freeze - 1;
System.out.println("onestepfreeze2:" + Double.toString(one_step_freeze));
}
}
if (one_step_happend == 1) {
last_theta = accumulated_rad + last_theta;
double current_x = last_x + STRIDE_LENGTH * Math.cos(last_theta);
double current_y = last_y + STRIDE_LENGTH * Math.sin(last_theta);
c_x.setText((int) current_x);
c_y.setText((int)current_y);
/*trace_x = [trace_x current_x];
trace_y = [trace_y current_y];
last_x = current_x;
//System.out.println("last_x"+last_x);
last_y = current_y;
//System.out.println("last_y"+last_y);
accumulated_rad = 0;
one_step_happend = 0;
} *//*else {
accumulated_rad = accumulated_rad + z_gy * SENSOR_INTERVAL;
//System.out.println(accumulated_rad);
/* calculate(accumulated_rad);
}
}
*/
}
#Override
protected void onResume()
{
super.onResume();
// Register this class as a listener for the accelerometer sensor
sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
// ...and the orientation sensor
sm1.registerListener(this, sm1.getDefaultSensor(Sensor.TYPE_ORIENTATION),
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onStop()
{
// Unregister the listener
sm.unregisterListener(this);
super.onStop();
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public class CustomDrawableView extends View
{
static final int width = 50;
static final int height = 50;
public CustomDrawableView(Context context)
{
super(context);
mDrawable = new ShapeDrawable(new OvalShape());
mDrawable.getPaint().setColor(0xff74AC23);
mDrawable.setBounds((int) current_x, (int) current_y, (int) current_x + width, (int) current_y + height);
//mDrawable.setBounds((int)acc_x, (int)acc_y, (int)acc_x + width,(int) acc_y + height);
}
protected void onDraw(Canvas canvas)
{
/* x= (int)current_x;
y= (int)current_y;*/
RectF oval = new RectF(MainActivity.x, MainActivity.y, MainActivity.x + width, MainActivity.y
+ height); // set bounds of rectangle
Paint p = new Paint(); // set some paint options
p.setColor(Color.BLUE);
canvas.drawOval(oval, p);
invalidate();
}
}
}

How Can i get the Values of Rotation Vactor sensor in android

my aim to calculate almost all sensor's values from android device.. i have done it except the rotation vector sensor.. but i also want to know the authenticity of my code.. is all values display correctly.. here is my code..
public void onSensorChanged(SensorEvent sensorEvent) {
synchronized (this) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
long curTime = System.currentTimeMillis();
if (lastUpdate == -1 || (curTime - lastUpdate) > 500) {
lastUpdate = curTime;
gravity[0] = alpha * gravity[0] + (1 - alpha) * sensorEvent.values[0];
gravity[1] = alpha * gravity[1] + (1 - alpha) * sensorEvent.values[1];
gravity[2] = alpha * gravity[2] + (1 - alpha) * sensorEvent.values[2];
linear_acceleration[0] = sensorEvent.values[0] - gravity[0];
linear_acceleration[1] = sensorEvent.values[1] - gravity[1];
linear_acceleration[2] = sensorEvent.values[2] - gravity[2];
acceleration[0] = gravity[0] + linear_acceleration[0];
acceleration[1] = gravity[1] + linear_acceleration[1];
acceleration[2] = gravity[2] + linear_acceleration[2];
AccX.setText( "TYPE_ACCELEROMETER Sensor Values \n " +
"X = "+Float.toString( sensorEvent.values[0])+" m/s^2");
AccY.setText( "Y = "+Float.toString( sensorEvent.values[1])+" m/s^2");
AccZ.setText( "Z = "+Float.toString( sensorEvent.values[2])+" m/s^2 \n");
GravX.setText( "TYPE_GRAVITY Sensor Values \n " +
"X = "+Float.toString(gravity[0])+" m/s^2");
GravY.setText( "Y = "+Float.toString(gravity[1])+" m/s^2");
GravZ.setText( "Z = "+Float.toString(gravity[2])+" m/s^2\n");
LAccX.setText( "TYPE_LINEAR_ACCELERATION Sensor Values \n" +
"X = "+Float.toString(linear_acceleration[0])+" m/s^2");
LAccY.setText( "Y = "+Float.toString(linear_acceleration[1])+" m/s^2 ");
LAccZ.setText( "Z = "+Float.toString(linear_acceleration[2])+" m/s^2\n ");
}
}
if (sensorEvent.sensor.getType() == Sensor.TYPE_ORIENTATION) {
long curTime = System.currentTimeMillis();
if (lastUpdate == -1 || (curTime - lastUpdate) > 500) {
lastUpdate = curTime;
OriX.setText("TYPE_ORIENTATION Values \n " +
"X = "+Float.toString( sensorEvent.values[0])+" degree");
OriY.setText("Y = "+Float.toString( sensorEvent.values[1])+" degree");
OriZ.setText("Z = "+ Float.toString( sensorEvent.values[2])+" degree \n");
}
}
if (sensorEvent.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
long curTime = System.currentTimeMillis();
if (lastUpdate == -1 || (curTime - lastUpdate) > 500) {
lastUpdate = curTime;
magneticX.setText( "TYPE_MAGNETIC_FIELD Sensor Values \n " +
"X = "+ Float.toString( sensorEvent.values[0])+" micro-Tesla (uT) ");
magneticY.setText( "Y = "+Float.toString( sensorEvent.values[1])+" micro-Tesla (uT) ");
magneticZ.setText( "Z = "+Float.toString( sensorEvent.values[2])+" micro-Tesla (uT) \n");
}
}
if (sensorEvent.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
long curTime = System.currentTimeMillis();
if (lastUpdate == -1 || (curTime - lastUpdate) > 500) {
lastUpdate = curTime;
GyrX.setText( "TYPE_GYROSCOPE Sensor Values \n X = "+ Float.toString( sensorEvent.values[0])+" ");
GyrY.setText( "Y = "+Float.toString( sensorEvent.values[1])+" ");
GyrZ.setText( "Z = "+Float.toString( sensorEvent.values[2])+" ");
}
}
}
}
and please let me know about how to display rotation vcctor sensor values..

Categories

Resources