1

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?

unos baghaii
  • 2,539
  • 4
  • 25
  • 42

1 Answers1

1

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();
}
Community
  • 1
  • 1
Isaac
  • 1,442
  • 17
  • 26
  • That check `if (Thread.currentThread().isInterrupted())` - almost senseless in that place of code – Divers Jan 08 '17 at 22:15