Android11停止在前台服务中录制音频,如果应用程序进入后台或被杀死。
创始人
2024-08-20 12:00:07
0

在Android 11中,应用程序在后台运行时无法使用前台服务中的录音功能。解决此问题的一种方法是使用MediaRecorder API并执行后台录音。以下是示例代码:

1.添加适当的权限到AndroidManifest.xml文件中:

2.在服务(Service)类中实例化MediaRecorder并设置相应的录音属性:

private MediaRecorder recorder; private static String outputFile = null;

public void startRecording() { recorder = new MediaRecorder(); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); recorder.setOutputFile(getOutputFile()); try { recorder.prepare(); } catch (IOException e) { Log.e("TAG", "prepare() failed"); } recorder.start(); } public void stopRecording() { recorder.stop(); recorder.release(); recorder = null; }

private String getOutputFile() { if (outputFile == null) { File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyApp/"); if (!dir.exists()) { dir.mkdirs(); } outputFile = dir.getAbsolutePath() + "/" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".mp4"; } return outputFile; }

3.在服务类中添加以下代码:

private NotificationManager notificationManager;

@Override public void onCreate() { super.onCreate(); notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); }

@Override public int onStartCommand(Intent intent, int flags, int startId) { Notification notification = new Notification.Builder(this, YOUR_CHANNEL_ID) .setContentTitle("My Recording Service") .setContentText("Recording...") .setSmallIcon(R.drawable.ic_launcher) .build(); startForeground(1, notification); startRecording(); return START_STICKY;

相关内容

热门资讯

备受关注的!拱趴大菠萝系统规律... 备受关注的!拱趴大菠萝系统规律!确实是真的辅助修改器(有挂技巧)-哔哩哔哩1、用户打开应用后不用登录...
突发!战皇大厅辅助那个可靠!原... 突发!战皇大厅辅助那个可靠!原来真的是有辅助挂(有挂头条)-哔哩哔哩所有人都在同一条线上,像星星一样...
近年来!手机科乐辅助!原来真的... 您好,手机科乐辅助这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩家在...
据报道!南宁友乐辅助!切实真的... 据报道!南宁友乐辅助!切实真的有辅助神器(有挂教程)-哔哩哔哩1)南宁友乐辅助免费钻石:进一步探索南...
据监测!佛手十三道辅助!果然是... 据监测!佛手十三道辅助!果然是有辅助挂(有挂讲解)-哔哩哔哩1、每一步都需要思考,不同水平的挑战会更...
今天下午!奇迹陕西游戏辅助器!... 今天下午!奇迹陕西游戏辅助器!其实是真的辅助挂(存在有挂)-哔哩哔哩1、上手简单,内置详细流程视频教...
做出回应!衢州多莱辅助器!切实... 做出回应!衢州多莱辅助器!切实真的是有辅助安装(真的有挂)-哔哩哔哩1、全新机制【衢州多莱辅助器ai...
昨日!微信小程序破解内购!一直... 昨日!微信小程序破解内购!一直存在有辅助平台(详细教程)-哔哩哔哩1.微信小程序破解内购 选牌创建新...
一直以来!随意玩最新跳转链接有... 一直以来!随意玩最新跳转链接有辅助吗!切实是有辅助安装(有挂工具)-哔哩哔哩1、随意玩最新跳转链接有...
现有关情况通报如下!河洛杠次怎... 现有关情况通报如下!河洛杠次怎么提高胜率!一贯真的是有辅助器(有挂技术)-哔哩哔哩所有人都在同一条线...