This document provides a tutorial on using the accelerometer sensor in Android applications. It discusses retrieving the accelerometer sensor from the SensorManager, registering a listener, and handling sensor events to detect phone movements like shaking. Code examples are given for an AccelerometerListener interface, AccelerometerManager class to manage sensor access, and an Activity that implements the listener to detect shakes and log accelerometer data.
Android brings to the table a whole new set of building blocks:. Each has its own unique properties. Building an app is mashing them together in a unique way. Often, there are multiple approaches to seemingly the same result. Knowing what component to use when is often a balance of art and science. In this talk, we’ll explore the main building blocks of Android: activities, services, providers, receivers as well as intents that glue them all together. We’ll learn about properties and variations of each. By the end of this talk, you should know how to write a straw-man implementation of basic building blocks, when to use them, and how to connect them together. This talk is based on Ice Cream Sandwich release of Android.
Do you have a need for custom components or behavior? This session will bring you the knowledge you require to create and extend custom components. Learn which calls to intercept for your custom logic.
Android brings to the table a whole new set of building blocks:. Each has its own unique properties. Building an app is mashing them together in a unique way. Often, there are multiple approaches to seemingly the same result. Knowing what component to use when is often a balance of art and science. In this talk, we’ll explore the main building blocks of Android: activities, services, providers, receivers as well as intents that glue them all together. We’ll learn about properties and variations of each. By the end of this talk, you should know how to write a straw-man implementation of basic building blocks, when to use them, and how to connect them together. This talk is based on Ice Cream Sandwich release of Android.
Do you have a need for custom components or behavior? This session will bring you the knowledge you require to create and extend custom components. Learn which calls to intercept for your custom logic.
Тема №2 Расширяем сознание реактивным подходом. RxJava и Android
Спикер — Владимир Артеменко — android developer Компания Rooky Pro
Уровень аудитории — Теория есть, начальный опыт применения
Цель доклада – Обучение
Introdução à programação orientada para aspectos em AspectJ. Diapositivos de seminário realizado no contexto da disciplina de Engenharia do Software II, DCTI, ISCTE-IUL.
Behavioral Pattern of the design pattern.
Introducing 6 type patterns and also including the pros and cons. It's easy to understand what's kind of scenario it should be used.
please send edited code of RCBug.javaRCBUG.javaimport java.util..pdfFashionBoutiquedelhi
please send edited code of RCBug.java
RCBUG.java
import java.util.Random;
public class RCBug {
private EZImage bugPicture; // Member variable to store bug picture
private int x, y, startx, starty; // Member variables to store x, y, startx, starty
private int destx, desty; // Member variables to store destination values
private long starttime; // Member variable to store the start time
private long duration; // Member variable to store the duration
private boolean interpolation; // Member variable that is set to true if it is in the
interpolation state
//1) add the private static final variables here
// Constructor for RCBug takes 3 parameters
public RCBug(String filename,int posx, int posy){
// Set the current position of the bug
x=posx;y=posy;
// Create the image of the bug
bugPicture = EZ.addImage(filename, posx, posy);
// Move it to the starting position. This is actually redundant.
bugPicture.translateTo(x,y);
// Set interpolation mode to false initially
interpolation = false;
}
// Set the destination by giving it 3 variables
// Dur means duration and is measured in seconds
public void setDestination(int posx, int posy, long dur){
// Set destination position and duration
// Convert seconds to miliseconds
destx = posx; desty = posy; duration = dur*1000;
// Get the startting time (i.e. time according to your computer)
starttime = System.currentTimeMillis();
// Set the starting position of your bug
startx=x; starty=y;
// Set interolation mode to true
interpolation = true;
}
// If you?re in interpolation state then return true, else false.
public boolean moving() {
return interpolation;
}
// This moves the bug based on the current time and elapsed time according to the
interpolation equation
public void go(){
// If interpolation mode is true then do interpolation
if (interpolation == true) {
// Normalize the time (i.e. make it a number from 0 to 1)
float normTime = (float) (System.currentTimeMillis() - starttime)/ (float) duration;
// Calculate the interpolated position of the bug
x = (int) (startx + ((float) (destx - startx) * normTime));
y = (int) (starty + ((float) (desty - starty) * normTime));
// If the difference between current time and start time has exceeded the duration
// then the animation/interpolation is over.
if ((System.currentTimeMillis() - starttime) >= duration) {
// Set interpolation to false
interpolation = false;
// Move the bug all the way to the destination
x = destx; y = desty;
}
//2)add a random amount to the x and y coordinates
// Don?t forget to move the image itself.
bugPicture.translateTo(x,y);
}
}
}
RCBugMain.java
import java.awt.Color;
import java.io.InputStreamReader;
import java.util.Scanner;
public class RCBugMain {
public static void main(String[] args) {
// Setup EZ graphics system.
EZ.initialize(512, 512);
// Set background color to dark green
EZ.setBackgroundColor(new Color(0, 100, 0));
// Make an InputStreamReader object which reads from the keyboard.
// Make a Scanner object that uses the InputStreamRe.
Learning Rx does not have to be boring like working your way through theoretical sermons about esoteric concepts like category theory and duality. Life is too short for that kind of abstract nonsense.
So what is a better way to spend a hot summer day with an ice-cold drink, or a cold winter night with a piping hot drink, than to learn Rx by writing an awesome platform game? In this talk, Erik will walk you through many of the features of Rx through programming a friendly bug to run across a lushy grassy meadow and jump for the stars.
Zybotech solutions, offers job oriented courses on mobile application development for freshers and professionals with placement assistance, interactive training sessions with live project exposure.
Тема №2 Расширяем сознание реактивным подходом. RxJava и Android
Спикер — Владимир Артеменко — android developer Компания Rooky Pro
Уровень аудитории — Теория есть, начальный опыт применения
Цель доклада – Обучение
Introdução à programação orientada para aspectos em AspectJ. Diapositivos de seminário realizado no contexto da disciplina de Engenharia do Software II, DCTI, ISCTE-IUL.
Behavioral Pattern of the design pattern.
Introducing 6 type patterns and also including the pros and cons. It's easy to understand what's kind of scenario it should be used.
please send edited code of RCBug.javaRCBUG.javaimport java.util..pdfFashionBoutiquedelhi
please send edited code of RCBug.java
RCBUG.java
import java.util.Random;
public class RCBug {
private EZImage bugPicture; // Member variable to store bug picture
private int x, y, startx, starty; // Member variables to store x, y, startx, starty
private int destx, desty; // Member variables to store destination values
private long starttime; // Member variable to store the start time
private long duration; // Member variable to store the duration
private boolean interpolation; // Member variable that is set to true if it is in the
interpolation state
//1) add the private static final variables here
// Constructor for RCBug takes 3 parameters
public RCBug(String filename,int posx, int posy){
// Set the current position of the bug
x=posx;y=posy;
// Create the image of the bug
bugPicture = EZ.addImage(filename, posx, posy);
// Move it to the starting position. This is actually redundant.
bugPicture.translateTo(x,y);
// Set interpolation mode to false initially
interpolation = false;
}
// Set the destination by giving it 3 variables
// Dur means duration and is measured in seconds
public void setDestination(int posx, int posy, long dur){
// Set destination position and duration
// Convert seconds to miliseconds
destx = posx; desty = posy; duration = dur*1000;
// Get the startting time (i.e. time according to your computer)
starttime = System.currentTimeMillis();
// Set the starting position of your bug
startx=x; starty=y;
// Set interolation mode to true
interpolation = true;
}
// If you?re in interpolation state then return true, else false.
public boolean moving() {
return interpolation;
}
// This moves the bug based on the current time and elapsed time according to the
interpolation equation
public void go(){
// If interpolation mode is true then do interpolation
if (interpolation == true) {
// Normalize the time (i.e. make it a number from 0 to 1)
float normTime = (float) (System.currentTimeMillis() - starttime)/ (float) duration;
// Calculate the interpolated position of the bug
x = (int) (startx + ((float) (destx - startx) * normTime));
y = (int) (starty + ((float) (desty - starty) * normTime));
// If the difference between current time and start time has exceeded the duration
// then the animation/interpolation is over.
if ((System.currentTimeMillis() - starttime) >= duration) {
// Set interpolation to false
interpolation = false;
// Move the bug all the way to the destination
x = destx; y = desty;
}
//2)add a random amount to the x and y coordinates
// Don?t forget to move the image itself.
bugPicture.translateTo(x,y);
}
}
}
RCBugMain.java
import java.awt.Color;
import java.io.InputStreamReader;
import java.util.Scanner;
public class RCBugMain {
public static void main(String[] args) {
// Setup EZ graphics system.
EZ.initialize(512, 512);
// Set background color to dark green
EZ.setBackgroundColor(new Color(0, 100, 0));
// Make an InputStreamReader object which reads from the keyboard.
// Make a Scanner object that uses the InputStreamRe.
Learning Rx does not have to be boring like working your way through theoretical sermons about esoteric concepts like category theory and duality. Life is too short for that kind of abstract nonsense.
So what is a better way to spend a hot summer day with an ice-cold drink, or a cold winter night with a piping hot drink, than to learn Rx by writing an awesome platform game? In this talk, Erik will walk you through many of the features of Rx through programming a friendly bug to run across a lushy grassy meadow and jump for the stars.
Similar to Android accelerometer sensor tutorial (20)
Zybotech solutions, offers job oriented courses on mobile application development for freshers and professionals with placement assistance, interactive training sessions with live project exposure.
What are the main advantages of using HR recruiter services.pdfHumanResourceDimensi1
HR recruiter services offer top talents to companies according to their specific needs. They handle all recruitment tasks from job posting to onboarding and help companies concentrate on their business growth. With their expertise and years of experience, they streamline the hiring process and save time and resources for the company.
Remote sensing and monitoring are changing the mining industry for the better. These are providing innovative solutions to long-standing challenges. Those related to exploration, extraction, and overall environmental management by mining technology companies Odisha. These technologies make use of satellite imaging, aerial photography and sensors to collect data that might be inaccessible or from hazardous locations. With the use of this technology, mining operations are becoming increasingly efficient. Let us gain more insight into the key aspects associated with remote sensing and monitoring when it comes to mining.
Skye Residences | Extended Stay Residences Near Toronto Airportmarketingjdass
Experience unparalleled EXTENDED STAY and comfort at Skye Residences located just minutes from Toronto Airport. Discover sophisticated accommodations tailored for discerning travelers.
Website Link :
https://skyeresidences.com/
https://skyeresidences.com/about-us/
https://skyeresidences.com/gallery/
https://skyeresidences.com/rooms/
https://skyeresidences.com/near-by-attractions/
https://skyeresidences.com/commute/
https://skyeresidences.com/contact/
https://skyeresidences.com/queen-suite-with-sofa-bed/
https://skyeresidences.com/queen-suite-with-sofa-bed-and-balcony/
https://skyeresidences.com/queen-suite-with-sofa-bed-accessible/
https://skyeresidences.com/2-bedroom-deluxe-queen-suite-with-sofa-bed/
https://skyeresidences.com/2-bedroom-deluxe-king-queen-suite-with-sofa-bed/
https://skyeresidences.com/2-bedroom-deluxe-queen-suite-with-sofa-bed-accessible/
#Skye Residences Etobicoke, #Skye Residences Near Toronto Airport, #Skye Residences Toronto, #Skye Hotel Toronto, #Skye Hotel Near Toronto Airport, #Hotel Near Toronto Airport, #Near Toronto Airport Accommodation, #Suites Near Toronto Airport, #Etobicoke Suites Near Airport, #Hotel Near Toronto Pearson International Airport, #Toronto Airport Suite Rentals, #Pearson Airport Hotel Suites
3.0 Project 2_ Developing My Brand Identity Kit.pptxtanyjahb
A personal brand exploration presentation summarizes an individual's unique qualities and goals, covering strengths, values, passions, and target audience. It helps individuals understand what makes them stand out, their desired image, and how they aim to achieve it.
Taurus Zodiac Sign_ Personality Traits and Sign Dates.pptxmy Pandit
Explore the world of the Taurus zodiac sign. Learn about their stability, determination, and appreciation for beauty. Discover how Taureans' grounded nature and hardworking mindset define their unique personality.
Accpac to QuickBooks Conversion Navigating the Transition with Online Account...PaulBryant58
This article provides a comprehensive guide on how to
effectively manage the convert Accpac to QuickBooks , with a particular focus on utilizing online accounting services to streamline the process.
India Orthopedic Devices Market: Unlocking Growth Secrets, Trends and Develop...Kumar Satyam
According to TechSci Research report, “India Orthopedic Devices Market -Industry Size, Share, Trends, Competition Forecast & Opportunities, 2030”, the India Orthopedic Devices Market stood at USD 1,280.54 Million in 2024 and is anticipated to grow with a CAGR of 7.84% in the forecast period, 2026-2030F. The India Orthopedic Devices Market is being driven by several factors. The most prominent ones include an increase in the elderly population, who are more prone to orthopedic conditions such as osteoporosis and arthritis. Moreover, the rise in sports injuries and road accidents are also contributing to the demand for orthopedic devices. Advances in technology and the introduction of innovative implants and prosthetics have further propelled the market growth. Additionally, government initiatives aimed at improving healthcare infrastructure and the increasing prevalence of lifestyle diseases have led to an upward trend in orthopedic surgeries, thereby fueling the market demand for these devices.
Buy Verified PayPal Account | Buy Google 5 Star Reviewsusawebmarket
Buy Verified PayPal Account
Looking to buy verified PayPal accounts? Discover 7 expert tips for safely purchasing a verified PayPal account in 2024. Ensure security and reliability for your transactions.
PayPal Services Features-
🟢 Email Access
🟢 Bank Added
🟢 Card Verified
🟢 Full SSN Provided
🟢 Phone Number Access
🟢 Driving License Copy
🟢 Fasted Delivery
Client Satisfaction is Our First priority. Our services is very appropriate to buy. We assume that the first-rate way to purchase our offerings is to order on the website. If you have any worry in our cooperation usually You can order us on Skype or Telegram.
24/7 Hours Reply/Please Contact
usawebmarketEmail: support@usawebmarket.com
Skype: usawebmarket
Telegram: @usawebmarket
WhatsApp: +1(218) 203-5951
USA WEB MARKET is the Best Verified PayPal, Payoneer, Cash App, Skrill, Neteller, Stripe Account and SEO, SMM Service provider.100%Satisfection granted.100% replacement Granted.
What is the TDS Return Filing Due Date for FY 2024-25.pdfseoforlegalpillers
It is crucial for the taxpayers to understand about the TDS Return Filing Due Date, so that they can fulfill your TDS obligations efficiently. Taxpayers can avoid penalties by sticking to the deadlines and by accurate filing of TDS. Timely filing of TDS will make sure about the availability of tax credits. You can also seek the professional guidance of experts like Legal Pillers for timely filing of the TDS Return.
Business Valuation Principles for EntrepreneursBen Wann
This insightful presentation is designed to equip entrepreneurs with the essential knowledge and tools needed to accurately value their businesses. Understanding business valuation is crucial for making informed decisions, whether you're seeking investment, planning to sell, or simply want to gauge your company's worth.
Falcon stands out as a top-tier P2P Invoice Discounting platform in India, bridging esteemed blue-chip companies and eager investors. Our goal is to transform the investment landscape in India by establishing a comprehensive destination for borrowers and investors with diverse profiles and needs, all while minimizing risk. What sets Falcon apart is the elimination of intermediaries such as commercial banks and depository institutions, allowing investors to enjoy higher yields.
1. Android Application Development Training Tutorial
For more info visit
http://www.zybotech.in
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
2. Android Accelerometer Sensor tutorial
Android supports a wide variety of sensors that can be used by applications to capture informations about the
phone’s environment.
In this tutorial, we’ll see how to use the accelerometer sensor in an application in order to capture acceleration
change events. We’ll use these events to build a custom listener that will trigger others events such as shake
events :
package net.androgames.bolg.sample.accelerometer;
public interface AccelerometerListener {
public void onAccelerationChanged(float x, float y, float z);
public void onShake(float force);
}
An instance of the SensorManager is required in order to retrieve informations about the supported sensors. No
permission is required to access the sensor service. It is then possible to retrieve the list of available sensors of a
certain type. For an accelerometer sensor, the type to use is given by the Sensor.TYPE_ACCELEROMETER
constant. If at least one Sensor exists, it is possible to register a SensorEventListener for a Sensor of the list. It
is possible to specify the delivering rate for sensor events. Specified rate must be one of :
1. SensorManager.SENSOR_DELAY_FASTEST : as fast as possible
2. SensorManager.SENSOR_DELAY_GAME : rate suitable for game
3. SensorManager.SENSOR_DELAY_NORMAL : normal rate
4. SensorManager.SENSOR_DELAY_UI : rate suitable for UI Thread
In order to allow a correct shake detection, it is preferable to use at least
SensorManager.SENSOR_DELAY_GAME.
The custom accelerometer manager is as follow :
package net.androgames.bolg.sample.accelerometer;
import java.util.List;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
/**
* Android Accelerometer Sensor Manager Archetype
* @author antoine vianey
* under GPL v3 : http://www.gnu.org/licenses/gpl-3.0.html
*/
public class AccelerometerManager {
/** Accuracy configuration */
private static float threshold = 0.2f;
private static int interval = 1000;
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
3. private static Sensor sensor;
private static SensorManager sensorManager;
// you could use an OrientationListener array instead
// if you plans to use more than one listener
private static AccelerometerListener listener;
/** indicates whether or not Accelerometer Sensor is supported */
private static Boolean supported;
/** indicates whether or not Accelerometer Sensor is running */
private static boolean running = false;
/**
* Returns true if the manager is listening to orientation changes
*/
public static boolean isListening() {
return running;
}
/**
* Unregisters listeners
*/
public static void stopListening() {
running = false;
try {
if (sensorManager != null && sensorEventListener != null) {
sensorManager.unregisterListener(sensorEventListener);
}
} catch (Exception e) {}
}
/**
* Returns true if at least one Accelerometer sensor is available
*/
public static boolean isSupported() {
if (supported == null) {
if (Accelerometer.getContext() != null) {
sensorManager = (SensorManager) Accelerometer.getContext().
getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(
Sensor.TYPE_ACCELEROMETER);
supported = new Boolean(sensors.size() > 0);
} else {
supported = Boolean.FALSE;
}
}
return supported;
}
/**
* Configure the listener for shaking
* @param threshold
* minimum acceleration variation for considering shaking
* @param interval
* minimum interval between to shake events
*/
public static void configure(int threshold, int interval) {
AccelerometerManager.threshold = threshold;
AccelerometerManager.interval = interval;
}
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
4. /**
* Registers a listener and start listening
* @param accelerometerListener
* callback for accelerometer events
*/
public static void startListening(
AccelerometerListener accelerometerListener) {
sensorManager = (SensorManager) Accelerometer.getContext().
getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(
Sensor.TYPE_ACCELEROMETER);
if (sensors.size() > 0) {
sensor = sensors.get(0);
running = sensorManager.registerListener(
sensorEventListener, sensor,
SensorManager.SENSOR_DELAY_GAME);
listener = accelerometerListener;
}
}
/**
* Configures threshold and interval
* And registers a listener and start listening
* @param accelerometerListener
* callback for accelerometer events
* @param threshold
* minimum acceleration variation for considering shaking
* @param interval
* minimum interval between to shake events
*/
public static void startListening(
AccelerometerListener accelerometerListener,
int threshold, int interval) {
configure(threshold, interval);
startListening(accelerometerListener);
}
/**
* The listener that listen to events from the accelerometer listener
*/
private static SensorEventListener sensorEventListener =
new SensorEventListener() {
private long now = 0;
private long timeDiff = 0;
private long lastUpdate = 0;
private long lastShake = 0;
private float x = 0;
private float y = 0;
private float z = 0;
private float lastX = 0;
private float lastY = 0;
private float lastZ = 0;
private float force = 0;
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
public void onSensorChanged(SensorEvent event) {
// use the event timestamp as reference
// so the manager precision won't depends
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
5. // on the AccelerometerListener implementation
// processing time
now = event.timestamp;
x = event.values[0];
y = event.values[1];
z = event.values[2];
// if not interesting in shake events
// just remove the whole if then else bloc
if (lastUpdate == 0) {
lastUpdate = now;
lastShake = now;
lastX = x;
lastY = y;
lastZ = z;
} else {
timeDiff = now - lastUpdate;
if (timeDiff > 0) {
force = Math.abs(x + y + z - lastX - lastY - lastZ)
/ timeDiff;
if (force > threshold) {
if (now - lastShake >= interval) {
// trigger shake event
listener.onShake(force);
}
lastShake = now;
}
lastX = x;
lastY = y;
lastZ = z;
lastUpdate = now;
}
}
// trigger change event
listener.onAccelerationChanged(x, y, z);
}
};
}
In the case of a SensorEvent triggered by a Sensor of type Sensor.TYPE_ACCELEROMETER, the event’s
values represents the acceleration of the phone given by a vector in a cartesian coordinate system. Landing on a
table, the values returned by the SensorEvent for the phone should be :
1. 0 m/s2 along x axis
2. 0 m/s2 along y axis
3. 9,80665 m/s2 along z axis
From an event to another, the coordinates of the acceleration vector are stored to detect suddent acceleration
changes and to trigger a shake event when the threshold is reached. Others events could be implemented such
as the detection of up and down gestures, circular gestures and lot more…
The custom AccelerometerManager can be use in any Activity or Service :
package net.androgames.bolg.sample.accelerometer;
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
6. import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
/**
* Android accelerometer sensor tutorial
* @author antoine vianey
* under GPL v3 : http://www.gnu.org/licenses/gpl-3.0.html
*/
public class Accelerometer extends Activity
implements AccelerometerListener {
private static Context CONTEXT;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CONTEXT = this;
}
protected void onResume() {
super.onResume();
if (AccelerometerManager.isSupported()) {
AccelerometerManager.startListening(this);
}
}
protected void onDestroy() {
super.onDestroy();
if (AccelerometerManager.isListening()) {
AccelerometerManager.stopListening();
}
}
public static Context getContext() {
return CONTEXT;
}
/**
* onShake callback
*/
public void onShake(float force) {
Toast.makeText(this, "Phone shaked : " + force, 1000).show();
}
/**
* onAccelerationChanged callback
*/
public void onAccelerationChanged(float x, float y, float z) {
((TextView) findViewById(R.id.x)).setText(String.valueOf(x));
((TextView) findViewById(R.id.y)).setText(String.valueOf(y));
((TextView) findViewById(R.id.z)).setText(String.valueOf(z));
}
}
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
7. As usual, it is preferable to register listeners in the onResume() method of the Activity and removed in the
onFinish() method of the Activity.
Android Orientation Sensor tutorial
Posted by Tonio | Filed under Tutorial
Android phones includes an orientation sensor that is used to detect the orientation of the phone in space. The
orientation is given throught three values :
1. Azimtuh in degres
angle between the x axis of the phone and the north direction
0 ≤ azimuth ≤ 360
2. Pitch in degres
angle made by the y axis of the phone relatively to the phone’s horizontal position
-180 ≤ pitch ≤ 180
3. Roll in degres
angle made by the x axis of the phone relatively to the phone’s horizontal position
-90 ≤ roll ≤ 90
In this tutorial, we’ll see how to use the orientation sensor in an application in order to capture orientation
change events. We’ll use these events to build a custom listener that will trigger phone’s orientation change
events :
package net.androgames.blog.sample.orientation;
public interface OrientationListener {
public void onOrientationChanged(float azimuth,
float pitch, float roll);
/**
* Top side of the phone is up
* The phone is standing on its bottom side
*/
public void onTopUp();
/**
* Bottom side of the phone is up
* The phone is standing on its top side
*/
public void onBottomUp();
/**
* Right side of the phone is up
* The phone is standing on its left side
*/
public void onRightUp();
/**
* Left side of the phone is up
* The phone is standing on its right side
*/
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
8. public void onLeftUp();
}
An instance of the SensorManager is needed in order to retrieve informations about the supported sensors. No
permission is required to access the sensor service and to retrieve the list of available orientation sensors given
by the Sensor.TYPE_ORIENTATION constant. If at least one Sensor exists, it is possible to register a
SensorEventListener for a Sensor of the list. The delivering rate for the orientation sensor events can be
specified and must be one of these :
1. SensorManager.SENSOR_DELAY_FASTEST : as fast as possible
2. SensorManager.SENSOR_DELAY_GAME : rate suitable for game
3. SensorManager.SENSOR_DELAY_NORMAL : normal rate
4. SensorManager.SENSOR_DELAY_UI : rate suitable for UI Thread
The custom orientation manager is as follow :
package net.androgames.blog.sample.orientation;
import java.util.List;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
/**
* Android Orientation Sensor Manager Archetype
* @author antoine vianey
* under GPL v3 : http://www.gnu.org/licenses/gpl-3.0.html
*/
public class OrientationManager {
private static Sensor sensor;
private static SensorManager sensorManager;
// you could use an OrientationListener array instead
// if you plans to use more than one listener
private static OrientationListener listener;
/** indicates whether or not Orientation Sensor is supported */
private static Boolean supported;
/** indicates whether or not Orientation Sensor is running */
private static boolean running = false;
/** Sides of the phone */
enum Side {
TOP,
BOTTOM,
LEFT,
RIGHT;
}
/**
* Returns true if the manager is listening to orientation changes
*/
public static boolean isListening() {
return running;
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
9. }
/**
* Unregisters listeners
*/
public static void stopListening() {
running = false;
try {
if (sensorManager != null && sensorEventListener != null) {
sensorManager.unregisterListener(sensorEventListener);
}
} catch (Exception e) {}
}
/**
* Returns true if at least one Orientation sensor is available
*/
public static boolean isSupported() {
if (supported == null) {
if (Orientation.getContext() != null) {
sensorManager = (SensorManager) Orientation.getContext()
.getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(
Sensor.TYPE_ORIENTATION);
supported = new Boolean(sensors.size() > 0);
} else {
supported = Boolean.FALSE;
}
}
return supported;
}
/**
* Registers a listener and start listening
*/
public static void startListening(
OrientationListener orientationListener) {
sensorManager = (SensorManager) Orientation.getContext()
.getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(
Sensor.TYPE_ORIENTATION);
if (sensors.size() > 0) {
sensor = sensors.get(0);
running = sensorManager.registerListener(
sensorEventListener, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
listener = orientationListener;
}
}
/**
* The listener that listen to events from the orientation listener
*/
private static SensorEventListener sensorEventListener =
new SensorEventListener() {
/** The side that is currently up */
private Side currentSide = null;
private Side oldSide = null;
private float azimuth;
private float pitch;
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
10. private float roll;
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
public void onSensorChanged(SensorEvent event) {
azimuth = event.values[0]; // azimuth
pitch = event.values[1]; // pitch
roll = event.values[2]; // roll
if (pitch < -45 && pitch > -135) {
// top side up
currentSide = Side.TOP;
} else if (pitch > 45 && pitch < 135) {
// bottom side up
currentSide = Side.BOTTOM;
} else if (roll > 45) {
// right side up
currentSide = Side.RIGHT;
} else if (roll < -45) {
// left side up
currentSide = Side.LEFT;
}
if (currentSide != null && !currentSide.equals(oldSide)) {
switch (currentSide) {
case TOP :
listener.onTopUp();
break;
case BOTTOM :
listener.onBottomUp();
break;
case LEFT:
listener.onLeftUp();
break;
case RIGHT:
listener.onRightUp();
break;
}
oldSide = currentSide;
}
// forwards orientation to the OrientationListener
listener.onOrientationChanged(azimuth, pitch, roll);
}
};
}
The custom OrientationManager can be use in any Activity or Service :
package net.androgames.blog.sample.orientation;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
/**
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
12. public void onTopUp() {
Toast.makeText(this, "Top UP", 1000).show();
}
}
As usual, it is preferable to register listeners in the onResume() method of the Activity and removed in the
onFinish() method of the Activity.
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi