我制作了一个程序来监控加速度传感器,并在服务中使用 TTS 测量某个值时说些什么。设备开机时一切正常,但是当它进入睡眠状态时,有时它可以正常工作,有时它会在一段时间后工作,有时它就像我按下电源按钮唤醒设备一样工作,有时它根本不工作。有什么想法吗?
public class MyService extends Service implements SensorEventListener, OnInitListener {
private SensorManager SenMan;
private Sensor AccSen;
private TextToSpeech mTTS = null;
private PowerManager pm;
private WakeLock wl;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
SenMan = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
AccSen = SenMan.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
SenMan.registerListener(this, AccSen, SensorManager.SENSOR_DELAY_NORMAL);
pm = (PowerManager)getSystemService(POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TAG");
}
@Override
public void onDestroy() {
SenMan.unregisterListener(this);
super.onDestroy();
}
@Override
public final void onAccuracyChanged(Sensor sensor, int accuracy) {}
@Override
public final void onSensorChanged(SensorEvent event) {
double a = Math.sqrt(Math.pow(event.values[0], 2) + Math.pow(event.values[1], 2) + Math.pow(event.values[2], 2));
if (Math.abs(a - 9.8) / 0.98 > 25) Say();
}
private void Say() {
wl.acquire();
mTTS = new TextToSpeech(this, this);
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS)
mTTS.speak("Text to say", TextToSpeech.QUEUE_FLUSH, null);
wl.release();
}
}