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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With