AndroidAPS/app/src/main/java/info/nightscout/androidaps/services/AlarmSoundService.java

85 lines
2.4 KiB
Java
Raw Normal View History

2018-07-29 00:00:48 +02:00
package info.nightscout.androidaps.services;
2017-06-11 17:22:54 +02:00
import android.app.Service;
import android.content.Context;
2017-06-11 17:22:54 +02:00
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
2017-06-11 17:22:54 +02:00
import android.media.MediaPlayer;
import android.os.IBinder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
2018-07-28 13:55:16 +02:00
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
2017-06-11 17:22:54 +02:00
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
public class AlarmSoundService extends Service {
2018-07-28 13:55:16 +02:00
private static Logger log = LoggerFactory.getLogger(Constants.ALARM);
2017-06-11 17:22:54 +02:00
MediaPlayer player;
2017-06-21 07:28:04 +02:00
int resourceId = R.raw.error;
2017-06-11 17:22:54 +02:00
public AlarmSoundService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
2018-07-28 13:55:16 +02:00
if (Config.logAlarm)
log.debug("onCreate");
2017-06-11 17:22:54 +02:00
}
public int onStartCommand(Intent intent, int flags, int startId) {
2017-06-21 07:28:04 +02:00
if (player != null && player.isPlaying())
player.stop();
2018-07-28 13:55:16 +02:00
if (Config.logAlarm)
log.debug("onStartCommand");
2017-06-11 17:22:54 +02:00
if (intent != null && intent.hasExtra("soundid"))
2017-06-21 07:28:04 +02:00
resourceId = intent.getIntExtra("soundid", R.raw.error);
2017-06-11 17:22:54 +02:00
player = new MediaPlayer();
AssetFileDescriptor afd = MainApp.sResources.openRawResourceFd(resourceId);
if (afd == null)
return START_STICKY;
try {
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
} catch (IOException e) {
log.error("Unhandled exception", e);
2017-06-11 17:22:54 +02:00
}
player.setLooping(true); // Set looping
2018-07-28 13:55:16 +02:00
AudioManager manager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
if (manager == null || !manager.isMusicActive()) {
player.setVolume(100, 100);
}
2017-06-11 17:22:54 +02:00
try {
player.prepare();
player.start();
} catch (IOException e) {
log.error("Unhandled exception", e);
2017-06-11 17:22:54 +02:00
}
return START_STICKY;
}
@Override
public void onDestroy() {
player.stop();
player.release();
2018-07-28 13:55:16 +02:00
if (Config.logAlarm)
log.debug("onDestroy");
2017-06-11 17:22:54 +02:00
}
}