0
我想建立一個簡單的Android應用程序時,接近傳感器值的變化,其更新一個TextView的文本。但是,儘管將物體靠近傳感器,textview值仍保持不變。接近傳感器在Android不響應
這裏是我的MainActivity.java代碼
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements SensorEventListener{
private SensorManager mSensorManager;
private Sensor mProximity;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get an instance of the sensor service, and use that to get an instance of
// a particular sensor.
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
mSensorManager.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_NORMAL);
textView = (TextView) findViewById(R.id.newtext);
}
public final void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do something here if sensor accuracy changes.
}
public final void onSensorChanged(SensorEvent event) {
float distance = event.values[0];
textView.setText(""+event.values[0]);
if (distance<3){
textView.setText("near"+distance);
}
// Do something with this sensor data.
}
@Override
protected void onResume() {
// Register a listener for the sensor.
super.onResume();
mSensorManager.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
// Be sure to unregister the sensor when the activity pauses.
super.onPause();
mSensorManager.unregisterListener(this);
}
}
這裏是我的XML代碼:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:orientation="vertical"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.suzancruz.senapp.MainActivity">
<TextView
android:layout_width="200dp"
android:layout_height="200dp"
android:id="@+id/newtext"
android:text="hjkhjk"
/>
</LinearLayout>
有你添加的權限在清單中? – AwaisMajeed
我已經使用權限:<使用的許可機器人:名稱=「android.permission.BODY_SENSORS」 /> –
和這個???? '<使用特徵 機器人:名字= 「android.hardware.sensor.proximity」 機器人:要求= 「真」/>' – AwaisMajeed