First time when i run this code it runs fine but when i pause and play it again mainthread stop for more than or equal to 20 second and then show ANR dialog and after that it didn't start again.Reviewed this code many time but not able to debug.I also comment startRecording() and stopRecording() but after that it runs okay i.e, the problem is in starting and stopping the service.
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());
}
}