第一次运行此代码时,它运行正常,但是当我暂停并再次播放时,mainthread停止超过或等于20秒然后显示ANR对话框,之后它再也没有开始。回顾这个代码很多时间但不能调试。我还注释startRecording()和stopRecording()但是之后它运行正常,即问题在于启动和停止服务。
public class RecordingService extends Service {
private String filePath = null;
private String dateSuffix = null;
private MediaRecorder mediaRecorder = null;
private DatabaseHelperClass databaseHelperClass;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
databaseHelperClass = new DatabaseHelperClass(getApplicationContext());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startRecording();
return START_STICKY;
}
@Override
public void onDestroy() {
stopRecording();
super.onDestroy();
}
private void stopRecording() {
try {
if (mediaRecorder != null) {
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
}
}
catch (IllegalStateException e){
}
}
private void startRecording() {
if (mediaRecorder != null)
mediaRecorder.release();
pathCreater();
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mediaRecorder.setAudioChannels(1);
mediaRecorder.setOutputFile(filePath);
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
private void pathCreater() {
String fileName;
File file;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM MM dd, yyyy h:mm a");
long date = System.currentTimeMillis();
dateSuffix = simpleDateFormat.format(date);
do {
fileName = getString(R.string.file_name_suffix) + "_" + dateSuffix + ".mp3";
filePath = Environment.getExternalStorageDirectory().getAbsolutePath();
filePath += "/" + fileName;
file = new File(filePath);
} while (file.exists() && !file.isDirectory());
}
}