Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start and stop recording from a button in a notification

I have a notification with a "Record" button. The desired functionality is that the app will start recording with the device's microphone when the button is clicked, and stop when it is clicked again. It should behave similarly to a Play/Pause button of a music app.

There are also other ways to start and stop recording, inside the app itself.

I tried to implement this in several ways, but I'm quite confused. The button itself receives a PendingIntent, so at first I gave it the intent of the activity that records sound in my app. This, of course, put the app itself into focus, so it's no good.

Next, I tried to create an IntentService that handles two kinds of intents - "Start Recording" and "Stop Recording". I managed to make it start recording, but it seems that as soon as it handled the "Start Recording" intent, it shut itself off, so my MediaRecorder object was lost.

I tried making my IntentService bindable by implementing onBind, but I got really mixed up with .aidl files and the like.

What is the correct approach here?

like image 900
Amir Rachum Avatar asked Jun 12 '15 17:06

Amir Rachum


1 Answers

You could try starting the recording in a plain old Service in the onStartCommand(...) callback, and making your PendingIntent to start recording start this service.

To stop the service, you can't make a PendingIntent that stops a service, so you'd have to get creative, and could use a BroadcastReceiver to receive an intent to stop the service.

So you'd make your service:

public class RecordingService extends Service {
    MediaRecorder mRecorder;
    ...
    public int onStartCommand(Intent intent, int flags, int startId) {
        // initialize your recorder and start recording
    }

    public void onDestroy() {
        // stop your recording and release your recorder
    }
}

and your broadcast receiver:

public class StopRecordingReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        context.stopService(new Intent(context, RecordingService.class));
    }
}

PendingIntent to start recording:

Intent i = new Intent(context, RecordingService.class);
PendingIntent pi = PendingIntent.getService(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

PendingIntent to stop recording:

Intent i = new Intent(context, StopRecordingReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
like image 70
Jazzer Avatar answered Nov 14 '22 23:11

Jazzer