Today we can find a countless smartphones and mobile devices.
When developing this can be a problem, because the hardware available in them, varies a lot.
In Android there is a way to list the available sensors in a device, so based on this, we can check if the sensor we need is available or create the necessary logic otherwise.
Para esto crearemos un nuevo proyecto, como blank o empty activity y dentro del MainActivity.java, colocaremos el siguiente código:
For this we will create a new project, as blank or empty activity and inside the MainActivity.java, we will place the following code:
package your.package.name.here; 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.TextView; import java.util.List; public class MainActivity extends AppCompatActivity implements SensorEventListener { private SensorManager mSensorManager; private TextView sensor_list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sensor_list = findViewById(R.id.sensor_list); mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); ListmList = mSensorManager.getSensorList(Sensor.TYPE_ALL); sensor_list.setText("Sensors: "); for(int i=1; i It is important to note that in this code a line must be replaced: package your.package.name.here; by the name of the package that we have chosen when creating the project. On the other hand, the code refers to a TextView called sensor_list, this will be responsible for showing the available sensors, on the device screen. This TextView is declared in the content_main.xml file <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context=".MainActivity" tools:showIn="@layout/activity_main"> <TextView android:id="@+id/sensor_list" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginEnd="8dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:text="TextView" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.174" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.077" /> </android.support.constraint.ConstraintLayout>