我正在开发一个应用程序,它在背景中记录视频,但是在录制过程中,当我按停止按钮停止录制时,它会抛出一个错误,说 java.lang.RuntimeException:Unable停止服务
以下是我的服务类代码: -
@Override
public void onCreate() {
// Start foreground service to avoid unexpected kill
Notification notification = new Notification.Builder(this)
.setContentTitle("Background Video Recorder")
.setContentText("Background video recording started...")
.setSmallIcon(R.mipmap.ic_launcher)
.build();
startForeground(1234, notification);
// Create new SurfaceView, set its size to 1x1, move it to the top left corner and set this service as a callback
windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
surfaceView = new SurfaceView(this);
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(1, 1,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT
);
layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
windowManager.addView(surfaceView, layoutParams);
surfaceView.getHolder().addCallback(this);
pref= getApplicationContext().getSharedPreferences("Recorder",0);
editor = pref.edit();
}
// Method called right after Surface created (initializing and starting MediaRecorder)
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
camera = Camera.open();
mediaRecorder = new MediaRecorder();
camera.unlock();
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.setCamera(camera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
String file = Environment.getExternalStorageDirectory()+"/:"+DateFormat.format("yyyy-MM-dd_kk-mm-ss", new Date().getTime())+".mp4";
mediaRecorder.setOutputFile(Environment.getExternalStorageDirectory()+"/:"+DateFormat.format("yyyy-MM-dd_kk-mm-ss", new Date().getTime())+".mp4");
editor.putString("file_path",file);
editor.commit();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onDestroy() {
mediaRecorder.stop();
mediaRecorder.reset();
mediaRecorder.release();
camera.lock();
camera.release();
windowManager.removeView(surfaceView);
}
停止按钮代码: -
public void stopVideo(View view){
Toast.makeText(this, "Video Recording stopped", Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this, CameraService.class);
stopService(intent);
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
}
它出了什么问题?