很常见的需求:App 通过手机光感器,获取当前的光线强度。根据光线强弱,弹窗提示用户是否切换白天/夜间模式。网上看了很多的博客,都没有解决我的问题。这个需求应该是挺常见的,
layout/activity_main.xml界面布局代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp">
<CheckBox
android:id="@+id/ck_bright"
android:layout_width="match_parent"
android:layout_height="50dp"
android:button="@null"
android:checked="false"
android:drawableLeft="@drawable/ck_status_selector"
android:padding="10dp"
android:text="亮度自动调节"
android:textColor="#ff000000"
android:textSize="18sp" />
<TextView
android:id="@+id/tv_light"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:padding="10dp"
android:text="看看光线变化了没有"
android:textColor="#ff000000"
android:textSize="18sp" />
</LinearLayout>
MainActivity.java逻辑代码如下:
package com.fukaimei.lightsensor;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import com.fukaimei.lightsensor.util.SwitchUtil;
import com.fukaimei.lightsensor.util.Utils;
public class MainActivity extends AppCompatActivity implements
OnCheckedChangeListener, SensorEventListener {
private CheckBox ck_bright;
private TextView tv_light;
private SensorManager mSensroMgr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ck_bright = (CheckBox) findViewById(R.id.ck_bright);
if (SwitchUtil.getAutoBrightStatus(this) == true) {
ck_bright.setChecked(true); android光线传感器开发:http://www.751com.cn/fanwen/lunwen_30827.html