2. Sensor Learning Note light sensor

Source: Internet
Author: User

In this lesson, we will learn the wirelessly light sensor, please bypass this article.

The Android system has a feature that automatically adjusts the brightness of the screen. It detects the light intensity of the environment around the phone and adjusts the brightness of the phone's screen accordingly to ensure that the screen can be seen clearly, whether in strong or weak light.

Said too much theory is a bit virtual, here Direct combat practical light sensor to do a project.

Objective of this lesson: to write a simple light detector program that allows the phone to detect changes in the light intensity of the surrounding environment.


Description
The value will change when the light is illuminated.
Friendly tips:
The simulator is not aware of the light intensity, so it is recommended to run on a real phone.

1. First we create a new Android project:

2. Use TextView to display the current light intensity

Here, a TextView control is used to display the light intensity.
The Activity_main layout file is as follows:

<relativelayout  xmlns: Android  = "http://schemas.android.com/apk/res/android"  xmlns:tools  =" Http://schemas.android.com/tools " android:layout_width  = "match_parent"  android:layout_height  =" match_parent " tools:context  =" com.xingyun.androidlightsensordemo.MainActivity ";     <TextViewandroid:id="@+id/light_level_id"android:layout_height=  "Wrap_content"android:layout_width="Wrap_content"android:layout_centerinparent ="true"android:textsize="20sp"/>                                         </relativelayout>
3.mainactivity.java Background Processing code:
 PackageCom.xingyun.androidlightsensordemo;ImportAndroid.content.Context;ImportAndroid.hardware.Sensor;ImportAndroid.hardware.SensorEvent;ImportAndroid.hardware.SensorEventListener;ImportAndroid.hardware.SensorManager;ImportAndroid.os.Bundle;Importandroid.support.v7.app.ActionBarActivity;ImportAndroid.widget.TextView; Public  class mainactivity extends actionbaractivity {    PrivateTextView Showlightleveltextview;//Display light sensor strength    PrivateSensormanager Sensormanager;//Sensor manager    PrivateSensor Lightsensor;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); Showlightleveltextview = (TextView) Findviewbyid (r.id.light_level_id);/*************************************************************************** * * Sensormanager is the system all sensor The Getdefaultsensor () method can be called after the manager has its instance () to get any sensor type * * Sensor.type_light constant to specify the sensor Type * ************************************************************************/        //Get an instance of SensormanagerSensormanager = (Sensormanager) getsystemservice (Context.sensor_service);//Specify sensor type as light sensorLightsensor = Sensormanager.getdefaultsensor (sensor.type_light); }/* This method is called when the activity is ready to interact with the user.     The activity at this point must be at the top of the stack that is returned and is in a running state. * */    @Override    protected void Onresume() {//TODO auto-generated method stub        Super. Onresume ();/* * Registerlistener () method receives three parameters the first parameter is an instance of Sensoreventlistener, and the second parameter is an instance of Sensor, both of which we have successfully          Here it is.         * The third parameter is the update rate used to represent the sensor output information, and their update rate is incremented sequentially. */        //Call Sensormanager's Registerlistener () method to register to make the listener effectiveSensormanager.registerlistener (Listener, Lightsensor, sensormanager.sensor_delay_normal); }/* This method is called when the system is ready to start or resume another activity. * We usually release some CPU-consuming resources in this method, and save some key data, but this method must be executed fast, otherwise it will affect the use of the new stack top activity.    @Override    protected void OnPause() {//TODO auto-generated method stub        Super. OnPause ();    Sensormanager.unregisterlistener (listener); }//This method is called before the activity is destroyed, and then the state of the activity becomes the destroy state.     @Override    protected void OnDestroy() {//TODO auto-generated method stub        Super. OnDestroy ();if(Sensormanager! =NULL) {Sensormanager.unregisterlistener (listener); }    }/** * requires monitoring of the sensor output signal, which is achieved by means of sensoreventlistener. Sensoreventlistener * is an interface that defines the two methods of Onsensorchanged () and onaccuracychanged () */    PrivateSensoreventlistener listener =NewSensoreventlistener () {the Onaccuracychanged () method is called when the sensor's accuracy is changed.        @Override         Public void onsensorchanged(Sensorevent event) {//TODO auto-generated method stub            /********************************************************* * * onsensorchanged () method passed in a Sen             Sorevent parameter * * This parameter also contains a values array, all sensor output information is stored here. *              * ******************************************************/            floatValue = event.values[0];//Display current screen brightness valueShowlightleveltextview.settext ("Current light intensity is:"+ Value +"LX"); }the Onsensorchanged () method is called when the sensor detects a change in the value.         @Override         Public void onaccuracychanged(Sensor sensor,intAccuracy) {//TODO auto-generated method stub}    };}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

2. Sensor Learning Note light sensor

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.