Using an Android phone's sensors


SDK Version: 
M3

Accessing the sensor data of a phone, is not too complicated, but since API level 3, a lot of things got deprecated. Using only the emulator, you have only a few (here is one) options, to simulate sensor data. I would recommend the use of a physical phone. Keep in mind, that not all phones have the same sensors integrated! Cheaper phones might not have a temperature sensor, or a gyroscope, but I'm pretty sure, that all Android phones have at least an accelerometer, and an orientation sensor.

Here is an example, how to access acceleration and orientation sensor data (in API level 3 and above), without using any deprecated methods.

  1. public class SensorTest extends Activity implements SensorEventListener {
  2.  
  3. SensorManager sensorManager = null;
  4.  
  5. //for accelerometer values
  6. TextView outputX;
  7. TextView outputY;
  8. TextView outputZ;
  9.  
  10. //for orientation values
  11. TextView outputX2;
  12. TextView outputY2;
  13. TextView outputZ2;
  14.  
  15.  @Override
  16.  public void onCreate(Bundle savedInstanceState) {
  17.     super.onCreate(savedInstanceState);

Start with sensorManager setup

  1.     sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
  2.     setContentView(R.layout.main);
  3.  
  4.     //just some textviews, for data output
  5.     outputX = (TextView) findViewById(R.id.TextView01);
  6.     outputY = (TextView) findViewById(R.id.TextView02);
  7.     outputZ = (TextView) findViewById(R.id.TextView03);
  8.  
  9.     outputX2 = (TextView) findViewById(R.id.TextView04);
  10.     outputY2 = (TextView) findViewById(R.id.TextView05);
  11.     outputZ2 = (TextView) findViewById(R.id.TextView06);
  12.  }

Now register the required listeners, it is recommended, to put this part in onResume.
What's interesting here, is the refresh speed. Just like using a toast(short,long...), there is no easy way, to set up a proper time limit. There are 4 sensor delay settings: fastest, game, normal, and ui.
Try them all out, and check which one works the best for your application. Aim for the lowest required refresh speed!

  1. @Override
  2.  protected void onResume() {
  3.     super.onResume();
  4.     sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), sensorManager.SENSOR_DELAY_GAME);
  5.     sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), sensorManager.SENSOR_DELAY_GAME);
  6.  }

It is recommended, to stop using the sensor event listener, as soon as you don't need it, and it should not be left running in the background. It can drain the battery pretty fast.

  1. @Override
  2.  protected void onStop() {
  3.     super.onStop();
  4.     sensorManager.unregisterListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER));
  5.     sensorManager.unregisterListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION));
  6.  }

The event.sensor.getType() will tell us, what kind of event just happened.

  1. public void onSensorChanged(SensorEvent event) {
  2.     synchronized (this) {
  3.         switch (event.sensor.getType()){
  4.             case Sensor.TYPE_ACCELEROMETER:
  5.                 outputX.setText("x:"+Float.toString(event.values[0]));
  6.                 outputY.setText("y:"+Float.toString(event.values[1]));
  7.                 outputZ.setText("z:"+Float.toString(event.values[2]));
  8.             break;
  9.         case Sensor.TYPE_ORIENTATION:
  10.                 outputX2.setText("x:"+Float.toString(event.values[0]));
  11.                 outputY2.setText("y:"+Float.toString(event.values[1]));
  12.                 outputZ2.setText("z:"+Float.toString(event.values[2]));
  13.         break;
  14.  
  15.         }
  16.     }
  17.  }

There is also an onAccuracyChanged part, which we don't care about right now.

  1.  @Override
  2. public void onAccuracyChanged(Sensor sensor, int accuracy) {}  
  3. }

To sum things up, to access sensor data you have to do the following things:
1. Check sensor availability.
2. Register a listener to a sensorManager.
3. Catch the needed data , from onSensorChanged.
4. Unregister the sensorManager's listener.

screenshot

You can read more, about those seemingly random numbers on the above screenshot, in the official google documentation of Android here.

Comments

A very good and informative article indeed . It helps me a lot to enhance my knowledge, I really like the way the writer presented his views. Bye
gadget personalizzati
bakeca

Great one
botox orlando

nice article. Loved it
youth soccer

Backlinks Checker

Your blog is nice. Thanks for providing us this information.

Hello! I have found the gradient tool but the cross does not look the same as your doing. Its diffrent strength in the shades. Like the are overlaying eachother. Please help.First Aid Course

Very interesting articles. Good work done
batik clothing

Wow... This is nice function on Android phone's. Thanks for the information.

car showrooms in mumbai
Cruises in mumbai

Car accident claims
Car accident claims

lots of people have gingerbread, why are we still waiting for it on providers locked phones?

Mike

self build conservatories

computer adviser

Really Nice
Fat Burning Furnace

Really Nice
Kent Conservatories

Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.

Really nice one
carpet cleaners nyc

Nice information, valuable and excellent design, as share good stuff with good ideas and concepts, lots of great information and inspiration, both of which we all need, thanks for all the enthusiasm to offer such helpful information here.
trade show exhibits

Keylogger

it's very nice is actually a good post.........

Hello Tamas,
Great share ! Very useful comparisons ! Beauty tips

I am very glad that I zak³ady bukmacherskie find your regular post here. zak³ady sportowe Which seems to be very important and it bukmacherzy made good time pass for me. I will Stop Sweating and Start Living always give a nice thrust look in to you Stop Sweating and Start Living Review from my bookmark feed. I don’t actually comment and don’t like to spend time in typing Learn More About Stop Sweating and Start Living the comment. But here I have to do this because this Visit The Website one deserves a good like.
Check out these resources:

good job........Jonestown Real Estate

As a professional Miami web designer I wonder how some of you developers would compare the robustness of this API to those of the competition.

This blog seems to get a great deal of visitors. How do you advertise it? It gives a nice individual twist on things. I guess having something real or substantial to give info on is the most important thing.

examination, OPC, especially in diabetic patients were found to be successful in the treatment of eye disorders that cause retinopati’nin.Cedar Park Real Estate

That is really the funniest way to present such issues right over here. Its a great platform showing such impressive way to deliver any message. Hope that you will keep posting in the future too to let us know more. Keep sharing.
Turning 65 Leads

Thanks for the code and the great help you offer.

BMW

Thanks for share this valuable information.

Nikmaya John

Friendzone

get best eBooks here
littlewhiteebook

thanks for the info

mediafire movies
mediafire links

Really a nice one
jobs abroad

Thank you - the site very very nice

المجتمع المصري هو مجتمع يحب الترفية حيث ان سكان مصر تصل الى تسعون مليون فرد ولذلك نحن نقدم خدمة دردشة مصرية لكل اهل مصر ام الدنيا , وتعتبر مصر متقدمة فى هذا العالم من حيث النمو فى مجالات التكنولوجيا و الكمبيوتر بنسبة كبيرة جدا لذلك نفضل دخول شات مصري اكبر تجمع بنات و شباب فى شات الحب و اجمل بنات فى دردشة دردشة الحب , اضافة الى ذلك حيث يوجد دردشة قوية تضم جميع محافظات مصر هي شات مصرية الكتابية نتمني لكم قضاء وقت ممكن فى شات الاصدقاء و احلي دردشة التعارف الذي يوجد به بنات رومانسية فى دردشة بنات مصر المصرية


شات الحب - دردشة مصرية - شات - شات مصري - شات حب - دردشة - دردشة كتابية - دردشة الحب - شات حبنا - شات حبي - شات مصرية - دردشة حب - شات بنات - دردشة مصر - دردشة بنات مصر - شات بنات مصر - شات صوتي - chat love - دردشة ياحبي - شات بنات لبنان - الحب - شات كتابي - منتدي ياحبي - شات مصر - دردشة حبنا - العاب تلبيس البنات - دردشة بنات - شات ياحبي - Chat - شات لبناني - شات كلامنجي - دردشة كلامنجي - شبكة - تصميم مواقع - تصميم - شات الاسكندرية - دردشة لبنانية - دردشة بنات لبنان - بنات لبنان - موقع شات - سعودي كول - شات سعودي كول - شات بنت مصر - شات سكس

Really an interesting one.
Traslochi Milano

I review your articles each morning. The particular content articles happens to be the most significant that I have noticed as well as it is educational. Spectacular. download movies

thank you for information

حجز فنادق مكة
فنادق مكة

The compatibility of android based applications are also astonishingly perfect. They can work best with so many appliances in the market and this is something which we can’t find in any other applications too. online quoting software

The Post Is Written in a very good manner "and it" entail Many Useful information for me. I Appreciated What You Have Done here. I am Always searching for informative information like this.Outlet

Hello,
Thanks for a nice share you have given to us,with such a large collection of information ! Great work you have done by sharing them to all.

Simply superb..! Shopping place mumbai

Android technology perhaps considered as one of the most developed technology for the last couple of years. The eagerness of many software developers are continuingly happending with more and more practical android applications we can have in the market today. Las Vegas Web Design

Wow this is really insane. its one of the most comprehensive and complete site I had been. i believe this site can go far, and with proper development, its deemed unstoppable. Deta Fukkyuu

It is a very informative and useful post… Thank you it is good material to read this post increases my knowledge....... Jason Hunt // imprimerie montreal

It's a very interesting and modern note, thanks for the article I really liked your blog. Casas Prefabricadas

One of the things that I love the most about my Android is the number of sensors that it has. Many GPS-enabled Android apps simply connect to GPS satellites and initiate the application with your location.
Advertising Agency Melbourne

I totally understand the beauty of this article. Nice attempt. iphone