Start and stop recording using the button in the notification

I have a notification with a "Record" button. The desired functionality is that the application starts recording from the deviceโ€™s microphone when you press the button and stops when you press it again. It should behave similarly to the Play / Pause button of a music application.

There are other ways to start and stop recording within the application itself.

I tried to implement this in several ways, but I am very confused. The button itself receives a PendingIntent , so first I gave it an activity target that records sound in my application. This, of course, put the application in focus, so it's not good.

Then I tried to create an IntentService that handles two types of intentions - Start Recording and Stop Recording. I managed to get him to start recording, but it seems that as soon as he processes the โ€œStart recordingโ€ intent, he disconnected, so my MediaRecorder object was lost.

I tried to create an IntentService binding by doing onBind , but I really messed up with .aidl files, etc.

What is the right approach?

+6
source share
1 answer

You can try to start recording in the regular old Service in the onStartCommand(...) PendingIntent and make your PendingIntent to start recording by starting this service.

To stop the service, you cannot make a PendingIntent that stops the service, so you will need to make an announcement and use BroadcastReceiver to get the intention to stop the service.

So, you will do 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); 
+1
source

Source: https://habr.com/ru/post/989024/


All Articles