简体   繁体   中英

How to properly implement a sensor with SensorManager in a thread?

I've got this command on my thread, but it doesn't work: sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

I want to make sensor background listener without my app being opened.

public class myThread extends Thread implements SensorEventListener{
    public SensorManager sensorManager;
    @Override
    public void run()
    {
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);

I've got an error Cannot resolve method 'getSystemService(?)' .

Outside of an Activity, getSystemService() requires Context. Pass through a Context when initialising your thread and use context.getSystemService().

class MyThread extends Thread {

private Context context;
public SensorManager sensorManager;

public MyThread(Context context) {
    this.context = context;
}

@Override
public void run()
{
    sensorManager = (SensorManager) context.getSystemService(SENSOR_SERVICE);
    sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
/** In Activity **/ 
public static void main(String[] args) {
    new MyThread(getContext()).start();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM