It is a ForegroundService where the OnCreate function is as follows:
public void onCreate() { super.onCreate(); final long RECORDING_INTERVAL = 30000; TimerTask recordingTask = new TimerTask() { public void run() { if (wakeLock == null) { Log.d("WakeLock", "WakeLock"); pm = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "FlexRat::Tag"); wakeLock.acquire(); } Log.i("Debug", "Recording Task"); stopRecording(); startRecording(); } }; Timer recordingTimer = new Timer(); recordingTimer.scheduleAtFixedRate(recordingTask, 0, RECORDING_INTERVAL); }
And the startRecording() method is as follows:
private void startRecording() { Log.i("Info", "NEW RECORDING"); try { recorder = new MediaRecorder(); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); Date today = Calendar.getInstance().getTime(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.ENGLISH); String reportDate = formatter.format(today); File instanceRecordDirectory = new File(getStoragePath()); File instanceRecord = new File(instanceRecordDirectory.getAbsolutePath() + File.separator + reportDate + ".mp4"); if (!instanceRecordDirectory.exists()) { instanceRecordDirectory.getParentFile().mkdirs(); instanceRecordDirectory.mkdirs(); } if (!instanceRecord.exists()) { instanceRecord.createNewFile(); } recorder.setOutputFile(instanceRecord.getAbsolutePath()); recorder.prepare(); recorder.start(); } catch (Exception e) { e.printStackTrace(); } }
The exception is thrown when i turn off the device, the stacktrace i get is:
I/MediaRecorderJNI: setAudioSource(1) W/System.err: java.lang.RuntimeException: setAudioSource failed. at android.media.MediaRecorder._setAudioSource(Native Method) at android.media.MediaRecorder.setAudioSource(MediaRecorder.java:797) at com.multimedia.flexrat.BackgroundService.startRecording(BackgroundService.java:125) at com.multimedia.flexrat.BackgroundService.access$300(BackgroundService.java:42) at com.multimedia.flexrat.BackgroundService$1.run(BackgroundService.java:70) at java.util.TimerThread.mainLoop(Timer.java:562) at java.util.TimerThread.run(Timer.java:512)
What i want is that the recordingTask keeps running even after the device is locked. I don’t care about battery usage at this point. I know it is a pretty heavy thread. I just want it to work for now. Can someone point me in the right direction? I searched all over the web but without results.
Advertisement
Answer
I found the solution! The problem was in my manifest file I didn’t know that I had to add android:foregroundServiceType="microphone"
to the service tag.