如何显示Android传感器列表?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (15)

我试图显示可用传感器的列表,但它就像没有! 我在想这是因为模拟器,但我在电话上试过了,结果是一样的:

private SensorManager mSensorManager;
TextView mSensorsTot,mSensorAvailables;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // Get the texts fields of the layout and setup to invisible
    mSensorsTot   = (TextView) findViewById(R.id.sensoritot);
    mSensorAvailables  = (TextView) findViewById(R.id.sensoridisponibili);

    // Get the SensorManager 
    mSensorManager= (SensorManager) getSystemService(SENSOR_SERVICE);

    // List of Sensors Available
    List<Sensor> msensorList = mSensorManager.getSensorList(SensorManager.SENSOR_ALL);

    // Print how may Sensors are there
    mSensorsTot.setText(msensorList.size()+" "+this.getString(R.string.sensors)+"!");

    // Print each Sensor available using sSensList as the String to be printed
    String sSensList = new String("");
    Sensor tmp;
    int x,i;
    for (i=0;i<msensorList.size();i++){
     tmp = msensorList.get(i);
     sSensList = " "+sSensList+tmp.getName(); // Add the sensor name to the string of sensors available
    }
    // if there are sensors available show the list
    if (i>0){
     sSensList = getString(R.string.sensors)+":"+sSensList;
     mSensorAvailables.setText(sSensList);
    }
}
提问于
用户回答回答于

该常数SensorManager.SENSOR_ALL已被弃用,似乎不再有效。

用查询传感器列表,Sensor.TYPE_ALL它应该工作。

用户回答回答于

你可以试试这个代码:-

package com.example.sensor;

import java.util.List;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends ActionBarActivity {

SensorManager smm;
List<Sensor> sensor;
ListView lv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    smm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    lv = (ListView) findViewById (R.id.listView1);
    sensor = smm.getSensorList(Sensor.TYPE_ALL);
    lv.setAdapter(new ArrayAdapter<Sensor>(this, android.R.layout.simple_list_item_1,  sensor));
}
}

只需在XML布局中放置一个列表视图即可。

扫码关注云+社区