我最近(几天前)开始学习JAVA,所以我相信我在犯一些基本错误。我创建了一个活动,通过按钮启动记录音频的服务。我加入了一个计时器来停止录音,并通过stopself()退出服务,希望这是正确关闭的方式。
但是,当我运行应用程序时,它会为录制期间(我将其设置为90分钟)生成多个音频文件,并且它们被无理地裁剪掉(其中一些是30分钟,一些是20分钟等),有时服务似乎也无法停止。
我的服务类:
@SuppressLint("SimpleDateFormat")
public class myservice extends Service {
private MediaRecorder myRecorder;
private String outputFile = null;
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
// super.onCreate(); (not sure about this one)
SimpleDateFormat s = new SimpleDateFormat("ddMMyyyy_hhmmss");
String format = s.format(new Date());
outputFile = Environment.getExternalStorageDirectory().
getAbsolutePath() + "/" + format + ".3gpp";
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile);
try {
myRecorder.prepare();
myRecorder.start();
} catch (IllegalStateException e) {
// start:it is called before prepare()
// prepare: it is called after start() or before setOutputFormat()
e.printStackTrace();
} catch (IOException e) {
// prepare() fails
e.printStackTrace();
}
Timer myTimer;
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
try {
myRecorder.stop();
myRecorder.reset();
myRecorder.release();
myRecorder = null;
stopSelf();
//onDestroy(); I added this one to test it out. not sure.
} catch (IllegalStateException e) {
// it is called before start()
e.printStackTrace();
} catch (RuntimeException e) {
// no valid audio/video data has been received
e.printStackTrace();
}
}
}, 60000 * 90); //90 minutes timer to stop the recording after 90 minutes
}
public int onStartCommand(Intent intent, int flags, int startId) {
//onCreate();
// return 1;
return START_STICKY; //not sure about this one
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
//what about this one ?
// @Override
// public void onDestroy() {
// myRecorder.stop();
// myRecorder.reset();
// myRecorder.release();
//}
}
我的主要活动:
public class MainActivity extends Activity {
private Button startBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startBtn = (Button)findViewById(R.id.start);
startBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent svc=new Intent(getBaseContext(), myservice.class);
startService(svc);
finish(); //because I want to close the UI after service started
}
});
}
}
在使用安卓服务之前,我使用线程编写了这个应用。它能工作,但计时器只能工作很短的时间,10分钟或更少。录音在某些时刻停止(通常为30分钟或更短),而且这个长度是不固定的(尽管计时器被设置为90分钟)。我仍然不知道原因,但我认为安卓操作系统会由于资源不足而关闭线程。非常感谢您提供帮助。