Search code examples
androidandroid-serviceaudio-recording

control Service while recording audio


I want to start a service and record the audio and then close the activity, but keeps recording, and then open the activity and stop recording.

this is my service :

public class RecorderService extends Service {

private Thread mThread;

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    mThread = new Thread(new Runnable() {
        @Override
        public void run() {
            startRecording();
        }
    });
    mThread.start();
    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    mThread = null;
    super.onDestroy();
}
}

this is my code to start and stop the service:

 Button recordAudioButton = (Button) findViewById(R.id.recordAudioButton);
    recordAudioButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            startService(new Intent(getApplicationContext(), RecorderService.class));

        }
    });

    Button buttonPLay = (Button) findViewById(R.id.buttonPLay);
    buttonPLay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            stopService(new Intent(getApplicationContext(), RecorderService.class));

        }
    });

it starts but when I stop the service it doesn't stop . What I'm doing wrong?


Solution

  • The issue is that although you set the mThread = null; you also need to stop it first.

    See android best and safe way to stop thread for more details on stopping a thread.

    For you example try changing the onStartCommand and onDestory to:

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    
        mThread = new Thread(new Runnable() {
            @Override
            public void run() {
                if (Thread.currentThread().isInterrupted()) {
                    return;
                }
    
                startRecording();
            }
        });
        mThread.start();
        return super.onStartCommand(intent, flags, startId);
    }
    
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        mThread.interrupt();
        mThread = null;
        super.onDestroy();
    }