如何解决如果应用程序在后台运行时前台服务正在运行,我该如何访问麦克风?
I followed the instructions。 在前台,通过与通知交互来启动服务和记录。 与通知交互后在后台:
java.lang.RuntimeException: setAudioSource failed.
at android.media.MediaRecorder.setAudioSource(Native Method)
at com.example.myapp.RecordTask.startRecord(RecordTask.java:23)
at com.example.myapp.MyService.lambda$record$0$MyService(MyService.java:46)
at com.example.myapp.-$$Lambda$MyService$7Gy9nIPi2Z0t8QdDE9_9i-fCMHQ.run(Unknown Source:2)
at java.lang.Thread.run(Thread.java:923)
2021-07-06 12:43:22.962 5284-5340/com.example.myapp E/MediaRecorder: setOutputFormat called in an invalid state: 32
通知意图:
Intent notificationIntent = new Intent(this,MyService.class);
PendingIntent pendingIntent = PendingIntent.getService(this,notificationIntent,0);
notification.setContentIntent(pendingIntent);
notification.setAutoCancel(true);
startForeground(Integer.parseInt(getString(R.string.record_notification_id)),notification.build());
我的服务:
public class MyService extends Service {
static final String TAG = "MyService";
String[] permissions = new String[]{
Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.FOREGROUND_SERVICE,};
@Override
public int onStartCommand(Intent intent,int flags,int startId) {
if (Permission.check(this,permissions)){
record();
}
return START_NOT_STICKY;
}
记录方法:
public void startRecord(String path){
if (createFile(path)) {
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setOutputFile(path);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
recorder.prepare();
} catch (IOException err){
Log.e(TAG,"Failed prepare voice record",err);
}
recorder.start();
Log.i(TAG,"Recording started");
}
}
前景到前景都很好:(
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。