How do I access the microphone if the foreground service is running while the app is running in the background?

Viewed 323

I followed the instructions. In foreground the service and record is started by interacting with a notification. In background after interacting with a notification:

java.lang.RuntimeException: setAudioSource failed.
        at android.media.MediaRecorder.setAudioSource(Native Method)
        at com.example.myapp.RecordTask.startRecord(RecordTask.java:23)
        at com.example.myapp.MyService.lambda$record$0$MyService(MyService.java:46)
        at com.example.myapp.-$$Lambda$MyService$7Gy9nIPi2Z0t8QdDE9_9i-fCMHQ.run(Unknown Source:2)
        at java.lang.Thread.run(Thread.java:923)
2021-07-06 12:43:22.962 5284-5340/com.example.myapp E/MediaRecorder: setOutputFormat called in an invalid state: 32

notification intent:

Intent notificationIntent = new Intent(this, MyService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, notificationIntent, 0);
notification.setContentIntent(pendingIntent);
notification.setAutoCancel(true);
startForeground(Integer.parseInt(getString(R.string.record_notification_id)), notification.build());

My service:

public class MyService extends Service {
    static final String TAG = "MyService";
    String[] permissions = new String[]{
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.FOREGROUND_SERVICE,
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (Permission.check(this, permissions)){
            record();
        }
        return START_NOT_STICKY;
    }

record method:

    public void startRecord(String path){
        if (createFile(path)) {
            recorder = new MediaRecorder();
            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            recorder.setOutputFile(path);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            try {
                recorder.prepare();
            } catch (IOException err){
                Log.e(TAG, "Failed prepare voice record", err);
            }
            recorder.start();
            Log.i(TAG, "Recording started");
        }
    }

it's fine in the foreground to foreground :(

0 Answers
Related