서비스를 사용하여 특정 시간 동안 장치의 방향을 추적하는 응용 프로그램을 만들려고합니다. 방향이 바뀌면 장치에서 소리가납니다. 기기가 켜져있는 한 완벽하게 작동합니다. 내가 장치를 잠 그거나 화면이 꺼지 자마자 나는 소리를 듣지 못합니다.화면이 꺼져있을 때 센서 데이터 서비스를받는 방법은 무엇입니까?
내 서비스 코드는
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();
}
}
날이 문제를 해결 도와주세요입니다.
활동에서 데이터를 브로드 캐스트하고 WakefulBroadcastReceiver를 사용하여 사운드를 재생하려고 시도하십시오. –
센서 데이터를 다시 활동으로 보냅니다. –
예 서비스에서 활동으로 데이터를 전송합니다. –