Android - 如何根据传感器名称获取传感器详细信息?

时间:2016-02-22 03:12:30

标签: android android-intent android-sensors

我正在编写一个简单的应用程序作为练习 - 在ListView上显示设备上所有传感器的列表,并在单击ListView中的每个传感器名称时在新活动中显示当前传感器值/详细信息。

我使ListView正常工作,并且可以将传感器名称传递给目前为止的新活动。有没有办法使用此传递的名称获取传感器详细信息?好像我不能使用putExtra()将传感器本身传递给新活动。或者还有另一种方法吗?

传感器列表活动:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_sensor_activity);

    sensorListView = (ListView) findViewById(R.id.sensorlist);
    sensorListView.setOnItemClickListener((AdapterView.OnItemClickListener) this); //allows each item in ListView to be clickable

    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

    sensorList = mSensorManager.getSensorList(Sensor.TYPE_ALL); //get list of sensors
    ArrayList<String> sensorNames =  new ArrayList<String>(); //list of sensor names

    //iterate through list of sensors, get name of each and append to list of names
    for(int i=0; i< sensorList.size(); i++) {
        String sensor= sensorList.get(i).getName();
        if(sensor == null || sensor.equals(""))
            continue;
        sensorNames.add(sensor);
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, sensorNames);
    sensorListView.setAdapter(adapter); //populate ListView with sensor names
}

@Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long id ) {
    Intent sensorDetails = new Intent(ListSensorActivity.this, SensorDetailActivity.class);
    sensorDetails.putExtra("SENSOR_NAME", sensorList.get(position).getName()); //pass sensor name to detail activity
    startActivity(sensorDetails);
}

**传感器详情活动**

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sensor_detail);

        sensorTitle = (TextView) findViewById(R.id.sensortitle);

        manager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);

        Bundle extras = getIntent().getExtras();
        sensorName = extras.getString("SENSOR_NAME");
        sensorTitle.setText(sensorName);
    }

2 个答案:

答案 0 :(得分:2)

将传感器中的类型传递给第二个活动,然后通过SensorManager.getDefaultSensor(类型)请求活动中的传感器

答案 1 :(得分:0)

请检查:

 private  SensorManager mSensorManager;
 private  Sensor sensorNames;

并在课堂上

 mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
 sensorNames= mSensorManager.getDefaultSensor(Sensor.TYPE_ALL);

并根据位置传递列表中的值:

  Intent intent= new Intent(this, SensorDetailActivity.class);
  intent.putExtra("SENSOR_NAME", sensorNames.get(position).toString()); 
  startActivity(intent);

如果你还没有得到解决方案,请告诉我.. :)