public class RecordService extends Service {
public static MediaProjection mMediaProjection;
MediaProjectionManager mMediaProjectionManager;
boolean isMediaRecording;
VirtualDisplay virtualDisplay;
private MediaRecorder mediaRecorder;
int width ;
int height ;
int dpi ;
String filePathName;
public RecordService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
createNotificationChannel();
int mResultCode = intent.getIntExtra("code", -1);
Intent mResultData = intent.getParcelableExtra("data");
int action = intent.getIntExtra("action", 0);
width = intent.getIntExtra("width", 0);
height = intent.getIntExtra("height", 0);
dpi = intent.getIntExtra("dpi", 0);
Log.e("test",width +" "+height+" "+dpi);
//mResultData = intent.getSelector();
mMediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
mMediaProjection = mMediaProjectionManager.getMediaProjection(mResultCode, mResultData);
if(action == 0){
takePhoto();
}
else if(action ==1){
try {
recordScreen();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
stopRecording();
}
private void recordScreen() throws InterruptedException {
Log.e("test","recordScreen");
createMediaRecorder();
//@SuppressLint("WrongConstant") ImageReader imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 3);
if(virtualDisplay == null){
virtualDisplay = mMediaProjection.createVirtualDisplay("screen_shot",
width, height, dpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
mediaRecorder.getSurface(), null, null);
}
else {
virtualDisplay.setSurface(mediaRecorder.getSurface());
}
startRecording();
}
/**
* 开始 媒体录制
*
*
*/
public void startRecording() {
//createMediaRecorder();
mediaRecorder.start();
isMediaRecording = true;
}
/**
* 停止 媒体录制
*/
public void stopRecording() {
mediaRecorder.stop();
mediaRecorder.reset();
mediaRecorder.release();
mediaRecorder = null;
isMediaRecording = false;
filePathName = null;
}
private MediaRecorder createMediaRecorder() {
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String filePath=Environment.getExternalStorageDirectory()+"/ScreenVideo/";
if(!new File(filePath).exists()){
new File(filePath).mkdirs();
}
filePathName= filePath+simpleDateFormat.format(new Date())+".mp4";
mediaRecorder = new MediaRecorder();
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setOutputFile(filePathName);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mediaRecorder.setVideoSize(width, height);
mediaRecorder.setVideoFrameRate(60);
mediaRecorder.setVideoEncodingBitRate(5 * width * height);
try{
mediaRecorder.prepare();
}catch (Exception e){
e.printStackTrace();
}
return mediaRecorder;
}
public void takePhoto(){
@SuppressLint("WrongConstant") ImageReader imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 3);
mMediaProjection.createVirtualDisplay("screen_shot",
width, height, dpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
imageReader.getSurface(), null, null);
imageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader reader) {
Image image = reader.acquireNextImage();//获取下一帧截屏,这里可以控制你是否要单个或者直接录屏
int width = image.getWidth();
int height = image.getHeight();
final Image.Plane[] planes = image.getPlanes();
final ByteBuffer buffer = planes[0].getBuffer();
int pixelStride = planes[0].getPixelStride();
int rowStride = planes[0].getRowStride();
int rowPadding = rowStride - pixelStride * width;
Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(buffer);
if (bitmap != null) {
try {
// 获取内置SD卡路径
String sdCardPath = Environment.getExternalStorageDirectory().getPath();
Log.e("test",sdCardPath);
// 图片文件路径
String filePath = sdCardPath + File.separator + System.currentTimeMillis()+".png";
File file = new File(filePath);
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT).show();
Log.e("1111111","保存成功");
reader.close();
} catch (Exception e) {
Log.e("test",e.toString());
}
} else {
Toast.makeText(getApplicationContext(), "bitmap == null", Toast.LENGTH_SHORT).show();
}
image.close();
}
}, null);
}
private void createNotificationChannel() {
Notification.Builder builder = new Notification.Builder(this.getApplicationContext()); //获取一个Notification构造器
Intent nfIntent = new Intent(this, MainActivity.class); //点击后跳转的界面,可以设置跳转数据
builder.setContentIntent(PendingIntent.getActivity(this, 0, nfIntent, 0)) // 设置PendingIntent
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_launcher)) // 设置下拉列表中的图标(大图标)
//.setContentTitle("SMI InstantView") // 设置下拉列表里的标题
.setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
.setContentText("is running......") // 设置上下文内容
.setWhen(System.currentTimeMillis()); // 设置该通知发生的时间
/*以下是对Android 8.0的适配*/
//普通notification适配
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId("notification_id");
}
//前台服务notification适配
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel("notification_id", "notification_name", NotificationManager.IMPORTANCE_LOW);
notificationManager.createNotificationChannel(channel);
}
Notification notification = builder.build(); // 获取构建好的Notification
notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
startForeground(110, notification);
}
}