首页 > code, 技术相关 > Android下调用传感器(温度,亮度方向,地磁等,附源码)

Android下调用传感器(温度,亮度方向,地磁等,附源码)

2011年4月29日 发表评论 阅读评论

装好Adroid SDK后,在sample的指导下,写了几个简单的类似hello world的程序,在这里介绍一下所写的在android下调用传感器的程序。

Android中支持的几种传感器:

Sensor.TYPE_ACCELEROMETER:加速度传感器。
Sensor.TYPE_GYROSCOPE:陀螺仪传感器。
Sensor.TYPE_LIGHT:亮度传感器。
Sensor.TYPE_MAGNETIC_FIELD:地磁传感器。
Sensor.TYPE_ORIENTATION:方向传感器。
Sensor.TYPE_PRESSURE:压力传感器。
Sensor.TYPE_PROXIMITY:近程传感器。
Sensor.TYPE_TEMPERATURE:温度传感器。

使用传感器最关键的一些知识是:SensorManager是所有传感器的一个综合管理类,包括了传感器的种类、采样率、精准度等。我们可以通过getSystemService方法来取得一个SensorManager对象。使用传感器时,需要通过registerListener函数注册传感器,使用完后需要通过unregisterListener取消注册。

百闻不如一见,还是直接讲代码:

新建一个Sensors的工程,创建一个Sensors.java,内容如下:

 package me.sigma.sensors;


import android.app.Activity;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

public class Sensors extends Activity {
    TextView myTextView1;//t
    //gen
    TextView myTextView2;//x
    TextView myTextView3;//y
    TextView myTextView4;//z
    //acc
    TextView myTextView5;//x
    TextView myTextView6;//y
    TextView myTextView7;//z
   //ori
    TextView myTextView8;//x
    TextView myTextView9;//y
    TextView myTextView10;//z
    //Light
    TextView myTextView11;//z

    SensorManager  mySensorManager;//
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        myTextView1 = (TextView) findViewById(R.id.myTextView1);
        myTextView2 = (TextView) findViewById(R.id.myTextView2);
        myTextView3 = (TextView) findViewById(R.id.myTextView3);
        myTextView4 = (TextView) findViewById(R.id.myTextView4);
        myTextView5 = (TextView) findViewById(R.id.myTextView5);
        myTextView6 = (TextView) findViewById(R.id.myTextView6);
        myTextView7 = (TextView) findViewById(R.id.myTextView7);
        myTextView8 = (TextView) findViewById(R.id.myTextView8);
        myTextView9 = (TextView) findViewById(R.id.myTextView9);
        myTextView10 = (TextView) findViewById(R.id.myTextView10);
        myTextView11 = (TextView) findViewById(R.id.myTextView11);
        mySensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    }
    private SensorListener mySensorListener = new SensorListener(){
    	@Override
    	public void onAccuracyChanged(int sensor, int accuracy) {}
    	@Override
    	public void onSensorChanged(int sensor, float[] values) {
    		if(sensor == SensorManager.SENSOR_TEMPERATURE){
    			myTextView1.setText("Current Temprature:"+values[0]);
    		}else if(sensor == SensorManager.SENSOR_MAGNETIC_FIELD){
    			myTextView2.setText("Current Magnetic x:"+values[0]);
    			myTextView3.setText("Current Magnetic y:"+values[1]);
    			myTextView4.setText("Current Magnetic z:"+values[2]);
    		}else if(sensor == SensorManager.SENSOR_ACCELEROMETER){
    			myTextView5.setText("Current Accelero x:"+values[0]);
    			myTextView6.setText("Current Accelero y:"+values[1]);
    			myTextView7.setText("Current Accelero z:"+values[2]);
    		}else if(sensor == SensorManager.SENSOR_ORIENTATION){
    			myTextView8.setText("Current Oraenttation x:"+values[0]);
    			myTextView9.setText("Current Oraenttation y:"+values[1]);
    			myTextView10.setText("Current Oraenttation z:"+values[2]);
    		}else if(sensor == SensorManager.SENSOR_LIGHT){
    			myTextView11.setText("Current Oraenttation x:"+values[0]);
    		}
    	}
    };
    @Override
    protected void onResume() {
    	mySensorManager.registerListener(
    			mySensorListener,
    			SensorManager.SENSOR_TEMPERATURE |
    			SensorManager.SENSOR_MAGNETIC_FIELD |
    			SensorManager.SENSOR_ACCELEROMETER |
    			SensorManager.SENSOR_LIGHT |
                        SensorManager.SENSOR_ORIENTATION,
    			SensorManager.SENSOR_DELAY_UI
    			);
    	super.onResume();
    }
    @Override
    protected void onPause() {
    	mySensorManager.unregisterListener(mySensorListener);
    	super.onPause();
    }
}
 

更改res/layout/下面的main.xml,为如下内容:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
	<TextView
		android:id="@+id/title"
		android:gravity="center_horizontal"
		android:textSize="20px"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="@string/title"/>
	<TextView
		android:id="@+id/myTextView1"
		android:textSize="18px"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="@string/myTextView1"/>
	    <TextView
		android:id="@+id/myTextView2"
		android:textSize="18px"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="@string/myTextView2"/>
	    <TextView
		android:id="@+id/myTextView3"
		android:textSize="18px"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="@string/myTextView3"/>
	    <TextView
		android:id="@+id/myTextView4"
		android:textSize="18px"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="@string/myTextView4"/>
	    <TextView
		android:id="@+id/myTextView5"
		android:textSize="18px"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="@string/myTextView5"/>
	    <TextView
		android:id="@+id/myTextView6"
		android:textSize="18px"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="@string/myTextView6"/>
	    <TextView
		android:id="@+id/myTextView7"
		android:textSize="18px"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="@string/myTextView7"/>
	    <TextView
		android:id="@+id/myTextView8"
		android:textSize="18px"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="@string/myTextView8"/>
	    <TextView
		android:id="@+id/myTextView9"
		android:textSize="18px"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="@string/myTextView9"/>
	    <TextView
		android:id="@+id/myTextView10"
		android:textSize="18px"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="@string/myTextView10"/>
	    <TextView
		android:id="@+id/myTextView11"
		android:textSize="18px"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="@string/myTextView11"/>
</LinearLayout>

 

更改res/values/strings.xml为如下内容:

 <?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">templator!</string>
    <string name="app_name">templator</string>
    <string name="title">Sigma Sensors</string>
    <string name="myTextView1">Current Temprature:</string>
    <string name="myTextView2">Current Magnetic x:</string>
    <string name="myTextView3">Current Magnetic y:</string>
    <string name="myTextView4">Current Magnetic z:</string>
    <string name="myTextView5">Current Accelero x:</string>
    <string name="myTextView6">Current Accelero y:</string>
    <string name="myTextView7">Current Accelero z:</string>
    <string name="myTextView8">Current Oraenttation x:</string>
    <string name="myTextView9">Current Oraenttation y:</string>
    <string name="myTextView10">Current Oraenttation z:</string>
    <string name="myTextView11">Current Light:</string>
</resources>

 


本文作者: Sigma    在新浪微博关注SigmaSigmaWeibo    RSS订阅本博客
本文链接: http://www.sigma.me/2011/04/29/android-develop-using-sensors.html
本博客采用知识共享署名—非商业性-禁止演绎使用3.0协议进行许可,转载请保留作者和原文链接。

  1. 2011年5月3日02:09 | #1

    学习,收藏了~

  2. 2011年5月6日14:02 | #2

    你搞Android做啥阿?

  3. 2011年5月6日17:50 | #3

    Android黑飘过。。。

  4. 2019年1月9日12:18 | #4

    I wish to express thanks to this writer for rescuing me from this type of problem. Right after looking out throughout the world-wide-web and coming across methods that were not productive, I figured my life was over. Being alive without the presence of approaches to the problems you’ve resolved by way of your good blog post is a serious case, and the kind that would have adversely affected my entire career if I had not discovered your website. The skills and kindness in touching a lot of stuff was vital. I am not sure what I would’ve done if I had not encountered such a solution like this. I am able to at this time relish my future. Thanks a lot very much for your impressive and effective guide. I won’t be reluctant to recommend the website to any person who ought to have care on this situation.

  5. 2019年1月10日09:04 | #5

    I precisely desired to thank you very much all over again. I do not know what I would’ve gone through without the type of advice revealed by you on this industry. It truly was a real horrifying matter in my view, but observing the very well-written technique you handled the issue made me to leap with gladness. Now i’m thankful for this service and wish you know what an amazing job you are always getting into training other individuals thru your site. More than likely you’ve never come across all of us.

  6. 2019年1月11日05:07 | #6

    I in addition to my friends appeared to be checking the nice tips and hints found on your web blog and then then came up with a horrible suspicion I had not thanked you for those secrets. Those ladies were absolutely passionate to read through all of them and have in effect unquestionably been enjoying those things. Appreciate your being considerably kind and then for having certain excellent things most people are really desirous to be informed on. My sincere regret for not expressing appreciation to you sooner.

  7. 2019年1月12日01:02 | #7

    Needed to send you a little observation so as to thank you very much once again for these pleasant techniques you have shared above. It has been so seriously generous of people like you to deliver freely what many people could possibly have offered for sale as an electronic book in making some cash for their own end, notably since you could have tried it in the event you wanted. These basics in addition served to be the easy way to realize that someone else have similar eagerness similar to my own to grasp a little more pertaining to this issue. I know there are some more fun situations up front for folks who discover your blog post.

  8. 2019年1月12日23:15 | #8

    Thanks for your whole labor on this web site. Kim loves setting aside time for investigation and it’s easy to understand why. Most of us learn all about the lively medium you make reliable tips via your website and as well improve contribution from other ones on this idea and our own simple princess is discovering a great deal. Take advantage of the rest of the new year. You’re the one doing a dazzling job.

  9. 2019年1月13日11:59 | #9

    I together with my pals happened to be checking the great information and facts located on your web site and then then came up with a terrible suspicion I never thanked you for those secrets. These ladies appeared to be consequently excited to study all of them and now have pretty much been enjoying those things. Appreciation for indeed being indeed accommodating and then for finding this kind of essential ideas millions of individuals are really eager to learn about. My sincere apologies for not expressing appreciation to earlier.

  10. 2019年1月14日07:27 | #10

    I happen to be commenting to make you be aware of what a impressive encounter my cousin’s daughter undergone viewing your web page. She discovered a wide variety of details, most notably what it is like to have a very effective coaching spirit to make certain people effortlessly gain knowledge of selected complex issues. You undoubtedly surpassed our own expected results. Thank you for distributing the useful, dependable, informative and also cool guidance on that topic to Sandra.

  11. 2019年1月15日02:26 | #11

    I would like to express thanks to this writer just for rescuing me from such a crisis. After browsing through the world-wide-web and seeing strategies which were not beneficial, I assumed my entire life was over. Being alive without the presence of approaches to the problems you’ve sorted out by means of the posting is a crucial case, and ones that might have in a negative way damaged my entire career if I had not encountered your web blog. The training and kindness in handling all things was very helpful. I don’t know what I would have done if I had not come across such a solution like this. I can also at this time look forward to my future. Thank you very much for this skilled and effective guide. I won’t hesitate to recommend your blog post to anyone who needs and wants tips on this area.

  12. 2019年1月15日10:01 | #12

    I wanted to put you a little bit of word in order to say thanks a lot as before for the pleasant opinions you’ve shared on this website. It was simply open-handed of you giving unhampered just what some people could have supplied for an e book to get some bucks for their own end, primarily now that you could have tried it in the event you decided. The smart ideas additionally served to become a great way to be aware that someone else have similar keenness similar to my personal own to learn more and more pertaining to this matter. I think there are several more pleasurable moments ahead for folks who start reading your blog.

  13. 2019年1月15日19:09 | #13

    I wanted to create you the very little observation just to say thanks over again with the great principles you have shown above. This is certainly generous of people like you to grant without restraint what a number of people could have distributed for an electronic book to end up making some profit for themselves, precisely seeing that you could possibly have tried it in the event you considered necessary. The thoughts in addition acted as a fantastic way to fully grasp that someone else have the identical dreams really like mine to see much more around this condition. I know there are a lot more pleasant moments in the future for people who check out your website.

  14. 2019年1月16日04:17 | #14

    I actually wanted to write a small message in order to say thanks to you for all the remarkable suggestions you are writing on this site. My time-consuming internet research has finally been recognized with really good facts to go over with my co-workers. I ‘d declare that we website visitors are very much endowed to live in a useful network with very many brilliant people with good tips and hints. I feel pretty blessed to have come across your entire website page and look forward to some more excellent moments reading here. Thanks once again for everything.

  15. 2019年1月16日11:54 | #15

    I definitely wanted to make a brief note so as to thank you for all of the wonderful tips and tricks you are sharing at this website. My extended internet investigation has at the end been paid with good quality know-how to go over with my classmates and friends. I would claim that many of us readers are very much endowed to be in a wonderful network with very many special professionals with good tactics. I feel very much lucky to have discovered your website and look forward to plenty of more excellent moments reading here. Thanks a lot once again for all the details.

  16. 2019年1月16日22:18 | #16

    Needed to draft you the bit of word to finally say thanks the moment again over the nice techniques you have shared on this website. It was certainly tremendously open-handed with people like you to convey unhampered all that numerous people might have offered as an ebook in order to make some money for themselves, notably considering that you might well have tried it if you ever desired. Those basics in addition worked to become good way to realize that many people have the same interest just as my personal own to see more with reference to this problem. I’m certain there are thousands of more fun instances in the future for individuals that browse through your site.

  17. 2019年1月17日07:11 | #17

    Needed to post you the bit of observation to give many thanks again just for the exceptional knowledge you have provided above. This is quite particularly open-handed with you to make openly all that a few people could possibly have distributed as an e-book to get some bucks for themselves, even more so seeing that you could possibly have done it if you desired. These principles in addition served like a good way to comprehend other individuals have the same dream just as mine to grasp lots more with reference to this condition. I know there are some more pleasant periods in the future for individuals that take a look at your blog post.

  18. 2019年1月17日15:24 | #18

    Needed to send you a little bit of remark to help say thank you over again for the remarkable opinions you have shared in this case. It is really particularly open-handed with you to grant publicly all that some people would’ve offered for an ebook to help make some cash for their own end, principally seeing that you might have done it in case you considered necessary. Those thoughts in addition served to become good way to be aware that the rest have the identical eagerness similar to my personal own to find out much more related to this matter. I think there are millions of more enjoyable periods ahead for individuals that scan your site.

  19. 2019年1月17日15:26 | #19

    I am only commenting to make you know what a outstanding discovery our princess developed using your web page. She came to understand plenty of details, most notably what it is like to have an ideal helping style to have folks without problems learn some complicated subject matter. You undoubtedly did more than readers’ desires. Many thanks for supplying those essential, trusted, explanatory and fun tips on your topic to Mary.

  20. 2019年1月18日01:48 | #20

    I would like to show thanks to this writer just for rescuing me from this challenge. Just after checking through the world-wide-web and getting notions that were not powerful, I figured my entire life was gone. Living devoid of the solutions to the issues you have fixed by way of this write-up is a crucial case, as well as the kind which might have adversely damaged my career if I hadn’t noticed your website. That expertise and kindness in taking care of almost everything was valuable. I’m not sure what I would have done if I hadn’t come across such a stuff like this. It’s possible to at this time look ahead to my future. Thanks for your time so much for this professional and amazing help. I will not think twice to recommend the website to anyone who desires tips on this subject.

  21. 2019年1月18日02:10 | #21

    I wish to show thanks to the writer just for rescuing me from this type of issue. Just after researching throughout the world-wide-web and meeting strategies which are not powerful, I figured my life was done. Living minus the solutions to the issues you have fixed by means of your post is a crucial case, as well as those which could have badly affected my career if I hadn’t discovered your site. Your own personal training and kindness in playing with all the things was priceless. I don’t know what I would have done if I had not discovered such a solution like this. I’m able to at this time look ahead to my future. Thanks so much for the professional and sensible guide. I will not hesitate to suggest your web sites to any individual who needs guidance on this topic.

  22. 2019年1月18日08:55 | #22

    I’m writing to make you be aware of of the impressive encounter my cousin’s daughter experienced viewing your web site. She realized a good number of things, which included what it is like to possess a great coaching mood to let most people completely gain knowledge of selected hard to do subject matter. You truly surpassed our own desires. I appreciate you for coming up with such helpful, safe, revealing and fun thoughts on the topic to Tanya.

  23. 2019年1月18日16:39 | #23

    Needed to send you a very small remark in order to thank you so much again with the spectacular knowledge you’ve featured here. This has been simply seriously generous of you in giving freely all that many people could have advertised as an e book to help with making some profit for their own end, notably seeing that you could possibly have done it in the event you desired. These smart ideas as well served to provide a great way to be certain that many people have a similar fervor really like my own to know the truth a good deal more in terms of this issue. I am sure there are lots of more pleasurable periods up front for individuals who take a look at your blog.

  24. 2019年1月19日02:22 | #24

    I simply wanted to say thanks once more. I am not sure what I might have carried out without the actual pointers shared by you about that area of interest. It was before a real alarming problem in my opinion, nevertheless taking note of a new expert avenue you resolved it took me to cry with joy. I will be grateful for your work and even believe you comprehend what a great job you are undertaking instructing other individuals through your web blog. More than likely you’ve never got to know any of us.

  25. 2019年1月19日08:57 | #25

    I’m commenting to make you be aware of what a beneficial experience my child experienced browsing your web page. She realized so many things, including what it is like to have a great teaching nature to let the others with ease gain knowledge of some specialized things. You actually exceeded my expected results. Thank you for coming up with these interesting, dependable, informative not to mention cool tips on that topic to Jane.

  26. 2019年1月19日17:21 | #26

    I’m writing to make you understand of the terrific experience my friend’s child had reading through your blog. She even learned a lot of issues, including what it is like to possess a great helping character to make many more with ease completely grasp specified tortuous things. You undoubtedly surpassed readers’ expected results. Many thanks for providing the essential, safe, revealing not to mention fun guidance on the topic to Kate.

  27. 2019年1月20日03:07 | #27

    I definitely wanted to type a quick note to appreciate you for all the nice recommendations you are placing here. My rather long internet look up has at the end been compensated with beneficial content to talk about with my family members. I ‘d express that we site visitors actually are really endowed to be in a perfect place with so many outstanding professionals with valuable methods. I feel somewhat fortunate to have seen your entire website and look forward to really more thrilling minutes reading here. Thanks a lot once more for everything.

  28. 2019年1月20日09:46 | #28

    I actually wanted to send a message to say thanks to you for some of the superb points you are placing on this site. My time consuming internet lookup has now been paid with good quality suggestions to write about with my pals. I ‘d repeat that we visitors are definitely endowed to live in a very good website with very many brilliant individuals with insightful opinions. I feel quite lucky to have used your weblog and look forward to really more cool times reading here. Thanks once again for a lot of things.

  29. 2019年1月20日19:04 | #29

    I am only writing to make you be aware of what a great encounter my wife’s daughter experienced checking your web site. She picked up plenty of things, including what it’s like to have an amazing coaching style to let certain people just understand several extremely tough things. You undoubtedly exceeded our desires. Thanks for rendering these warm and friendly, safe, edifying and as well as cool tips on your topic to Sandra.

  30. 2019年1月20日20:04 | #30

    I enjoy you because of all your valuable hard work on this web page. My aunt delights in participating in investigations and it’s easy to see why. My partner and i notice all relating to the powerful mode you produce valuable information through this website and welcome response from visitors on this point so my simple princess is being taught so much. Take advantage of the remaining portion of the year. Your performing a superb job.

  31. 2019年1月21日10:33 | #31

    I enjoy you because of your own work on this blog. My daughter loves going through investigation and it’s really obvious why. Most people know all relating to the dynamic way you convey reliable tips via your web site and attract participation from some others on that article then my girl has been studying a whole lot. Have fun with the rest of the new year. You’re performing a splendid job.

  32. 2019年1月21日18:15 | #32

    I needed to compose you a very little note just to say thanks once again considering the exceptional tricks you have contributed on this site. This has been extremely open-handed with people like you to present freely exactly what a number of us might have advertised for an e-book in making some money for their own end, even more so since you might well have done it if you desired. The advice likewise served to become good way to be aware that other people have the identical fervor like my personal own to see somewhat more regarding this matter. I think there are some more pleasurable periods ahead for individuals who find out your website.

  33. 2019年1月22日12:35 | #33

    I’m commenting to let you know what a remarkable experience our girl went through browsing your site. She learned such a lot of pieces, most notably what it is like to have an awesome teaching style to have others without difficulty learn about several tricky topics. You truly surpassed her desires. Many thanks for presenting such useful, safe, revealing and even cool thoughts on that topic to Gloria.

  1. 本文目前尚无任何 trackbacks 和 pingbacks.

无觅相关文章插件,快速提升流量