Answer the question
In order to leave comments, you need to log in
Screen stops turning on using Service and WakeLock?
I am writing an application with a foreground service that records sounds when they are detected.
The problem is that after ~10 minutes the phone's screen only turns on with a delay of ~20 seconds (sometimes more) after I press the power (or home) button. When I manage to unlock the phone, it starts to lag. In some cases, it simply reboots while the service is running.
The service works fine even when I can't turn on the screen. You just need to deal with the problem that the phone starts to fail when the screen does not turn on for a long time.
Service code. How could I shorten it.
recorderservice:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(START_ACTION)) {
isActive = true;
/* создание уведомления */
startForeground(1, notification);
startListening();
} else if (intent.getAction().equals(STOP_ACTION)) {
isActive = false;
stopForeground(true);
stopSelf();
}
return START_STICKY;
}
public void startListening() {
Thread streamThread = new Thread(() -> {
int bufferSizeInBytes = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE, RECORDER_CHANNELS,
RECORDER_AUDIO_ENCODING);
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO);
// Initialize Audio Recorder.
AudioRecord audioRecorder = new AudioRecord(MediaRecorder.AudioSource.MIC, RECORDER_SAMPLERATE,
RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING, bufferSizeInBytes);
audioRecorder.startRecording();
long silentSeconds = 0;
int numberOfReadBytes = 0;
byte[] audioBuffer = new byte[bufferSizeInBytes];
boolean recording = false;
float[] tempFloatBuffer = new float[3];
int tempIndex = 0;
int totalReadBytes = 0;
byte[] totalByteBuffer = new byte[60 * 6 * 44100 * 2];
// Creating WakeLock
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (pm != null) {
wakelock= pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getCanonicalName());
}
wakelock.acquire();
// While data come from microphone.
while (isActive) {
float totalAbsValue = 0.0f;
short sample = 0;
numberOfReadBytes = audioRecorder.read(audioBuffer, 0, bufferSizeInBytes);
// Analyze Sound.
for (int i = 0; i < bufferSizeInBytes; i += 2) {
sample = (short) ((audioBuffer[i]) | audioBuffer[i + 1] << 8);
totalAbsValue += Math.abs(sample) / (numberOfReadBytes / 2);
}
tempFloatBuffer[tempIndex % 3] = totalAbsValue;
float temp = 0.0f;
for (int i = 0; i < 3; ++i)
temp += tempFloatBuffer[i];
if ((temp >= 0 && temp <= minVolumeLevel) && !recording && !isSaving) {
tempIndex++;
continue;
}
if (temp > minVolumeLevel && !recording && !isSaving) {
Log.d(TAG, "got sound");
if (sleepingStore.getUseAntiSnore() && sleepingStore.getMinimalTimeReached() && signalCompleted) {
resID = getApplicationContext().getResources()
.getIdentifier(selectedSignal.getFileName(), "raw",
getApplicationContext().getPackageName());
player = MediaPlayer.create(getApplicationContext(), resID);
player.setLooping(true);
player.start();
signalHandler.postDelayed(stopPlayerTask, sleepingStore.getAntiSnoreDuration() * 1000);
signalCompleted = false;
} else {
recording = true;
}
}
if (totalReadBytes >= (THREE_MIN_BYTES)) forceSave = true;
if (temp > minVolumeLevel && recording) silentSeconds = 0;
if (((temp >= 0 && temp <= minVolumeLevel) && recording && !isSaving) || forceSave) {
silentSeconds++;
if (silentSeconds >= 160 || forceSave) {
isSaving = true;
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath, "AudioRecorder");
if (!file.exists())
file.mkdirs();
String fn = file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".wav";
long totalAudioLen = 0;
long totalDataLen = totalAudioLen + 36;
long longSampleRate = RECORDER_SAMPLERATE;
int channels = 1;
long byteRate = RECORDER_BPP * RECORDER_SAMPLERATE * channels / 8;
totalAudioLen = totalReadBytes;
totalDataLen = totalAudioLen + 36;
byte[] finalBuffer = new byte[totalReadBytes + 44];
totalDataLen -= 420000;
totalAudioLen -= 420000;
totalReadBytes -= 420000;
finalBuffer[0] = 'R';
finalBuffer[1] = 'I';
finalBuffer[2] = 'F';
finalBuffer[3] = 'F';
finalBuffer[4] = (byte) (totalDataLen & 0xff);
finalBuffer[5] = (byte) ((totalDataLen >> 8) & 0xff);
finalBuffer[6] = (byte) ((totalDataLen >> 16) & 0xff);
finalBuffer[7] = (byte) ((totalDataLen >> 24) & 0xff);
finalBuffer[8] = 'W';
finalBuffer[9] = 'A';
finalBuffer[10] = 'V';
finalBuffer[11] = 'E';
finalBuffer[12] = 'f';
finalBuffer[13] = 'm';
finalBuffer[14] = 't';
finalBuffer[15] = ' ';
finalBuffer[16] = 16;
finalBuffer[17] = 0;
finalBuffer[18] = 0;
finalBuffer[19] = 0;
finalBuffer[20] = 1;
finalBuffer[21] = 0;
finalBuffer[22] = (byte) channels;
finalBuffer[23] = 0;
finalBuffer[24] = (byte) (longSampleRate & 0xff);
finalBuffer[25] = (byte) ((longSampleRate >> 8) & 0xff);
finalBuffer[26] = (byte) ((longSampleRate >> 16) & 0xff);
finalBuffer[27] = (byte) ((longSampleRate >> 24) & 0xff);
finalBuffer[28] = (byte) (byteRate & 0xff);
finalBuffer[29] = (byte) ((byteRate >> 8) & 0xff);
finalBuffer[30] = (byte) ((byteRate >> 16) & 0xff);
finalBuffer[31] = (byte) ((byteRate >> 24) & 0xff);
finalBuffer[32] = (byte) (2 * 16 / 8);
finalBuffer[33] = 0;
finalBuffer[34] = RECORDER_BPP;
finalBuffer[35] = 0;
finalBuffer[36] = 'd';
finalBuffer[37] = 'a';
finalBuffer[38] = 't';
finalBuffer[39] = 'a';
finalBuffer[40] = (byte) (totalAudioLen & 0xff);
finalBuffer[41] = (byte) ((totalAudioLen >> 8) & 0xff);
finalBuffer[42] = (byte) ((totalAudioLen >> 16) & 0xff);
finalBuffer[43] = (byte) ((totalAudioLen >> 24) & 0xff);
for (int i = 0; i < totalReadBytes; ++i)
finalBuffer[44 + i] = totalByteBuffer[i];
FileOutputStream out;
try {
out = new FileOutputStream(fn);
try {
out.write(finalBuffer);
out.close();
forceSave = false;
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
// */
isSaving = false;
recording = false;
silentSeconds = 0;
numberOfReadBytes = 0;
tempIndex = 0;
totalReadBytes = 0;
}
}
// Recording sound
if (!sleepingStore.getUseAntiSnore()) {
Log.d("qwwe", "Recording Sound.");
for (int i = 0; i < numberOfReadBytes; i++)
totalByteBuffer[totalReadBytes + i] = audioBuffer[i];
totalReadBytes += numberOfReadBytes;
}
tempIndex++;
}
});
streamThread.start();
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question