我正在尝试创建一个应用程序,该应用程序使用服务在一定时间内跟踪设备的方向。当方向改变时,设备会发出声音。只要设备开启,它就可以完美运行。一旦我锁定设备或屏幕关闭,我就听不到声音(我想听到)。
我的服务代码是
public class RakatTrackingService extends Service implements SensorEventListener {
private SharedPreferences sharedPref;
private long[] sessionComposition = new long[4];
private String position="none", lastPosition ="none";
private SensorManager sensorManager;
private Sensor accelerometer;
private PowerManager.WakeLock wakeLock;
public RakatTrackingService()
{
}
public RakatTrackingService(long[] sessionComposition) {
this.sessionComposition = sessionComposition;
}
@Override
public void onCreate() {
super.onCreate();
SharedPreferences sharedPref = getSharedPreferences("rakatData",Context.MODE_PRIVATE);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null)
{
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
Toast.makeText(this, "sensor registered", Toast.LENGTH_LONG).show();
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onSensorChanged(SensorEvent event) {
lastPosition = position;
if(Math.abs(event.values[0]) > Math.abs(event.values[1]) && Math.abs(event.values[0]) > Math.abs(event.values[2]))
{
position="horizontal-side";
}
if(Math.abs(event.values[1]) > Math.abs(event.values[0]) && Math.abs(event.values[1]) > Math.abs(event.values[2]))
{
position="vertical";
}
if(Math.abs(event.values[2]) > Math.abs(event.values[0]) && Math.abs(event.values[2]) > Math.abs(event.values[1]))
{
position="horizontal";
}
System.out.println(position);
if(!lastPosition.equalsIgnoreCase(position))
{
MediaPlayer mp = MediaPlayer.create(this, R.raw.click);
mp.start();
mp.setLooping(false);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
PowerManager mgr = (PowerManager)getApplicationContext().getSystemService(Context.POWER_SERVICE);
wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
wakeLock.acquire();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
wakeLock.release();
}
}
请帮我解决这个问题。
最佳答案
你根本做不到。传感器监听器不起作用,然后您的屏幕关闭。您需要激活该应用程序才能使用它。您可以尝试获取 PARTIAL_WAKE_LOCK
或 SCREEN_DIM_WAKE_LOCK
关于android - 屏幕关闭时如何获取服务中的传感器数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46805637/