Что делать с этой ошибкой, этот код предназначен для средства записи экрана, которое выдает ошибку после нажатия кнопки переключения, означает, что приложение закрывается без выполнения каких-либо дополнительных операций, но изначально приложение запускается очень хорошо. Но проблема возникает при нажатии кнопки
publi c Класс MainActivity расширяет AppCompatActivity {
private static final int REQUEST_CODE = 11;
private static final int MEDIA_CODE = 12;
private static final SparseIntArray ORIENTAIONS = new SparseIntArray();
private MediaProjectionManager mediaProjectionManager;
private MediaProjection mediaProjection;
private VirtualDisplay virtualDisplay;
private MediaRecorder mediaRecorder;
private MediaProjectionCallback mediaProjectionCallback;
private int mScreenDensity;
private static final int DISPLAY_WIDTH = 720;
private static final int DISPLAY_HEIGHT = 1280;
static
{
ORIENTAIONS.append(Surface.ROTATION_0, 90);
ORIENTAIONS.append(Surface.ROTATION_90, 0);
ORIENTAIONS.append(Surface.ROTATION_180, 270);
ORIENTAIONS.append(Surface.ROTATION_270, 180);
}
private ToggleButton btnToggle;
private VideoView videoView;
private String videoUri = "";
private RelativeLayout rootLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnToggle = findViewById(R.id.btnToggle);
videoView = findViewById(R.id.videoView);
rootLayout = findViewById(R.id.rootLayout);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mScreenDensity = metrics.densityDpi;
mediaRecorder = new MediaRecorder();
mediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
btnToggle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
+ ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.RECORD_AUDIO) !=
PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
|| ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.RECORD_AUDIO))
{
btnToggle.setChecked(false);
Snackbar.make(rootLayout, "Permissions", Snackbar.LENGTH_INDEFINITE)
.setAction("ENABLE", new View.OnClickListener() {
@Override
public void onClick(View v) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO}, REQUEST_CODE);
}
}).show();
}
else
{
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO}, REQUEST_CODE);
}
}
else
{
toggleScreenShare(v);
}
}
});
}
private void toggleScreenShare(View v) {
if (((ToggleButton)v).isChecked())
{
initRecorder();
screenRecord();
}
else
{
mediaRecorder.stop();
mediaRecorder.reset();
stopRecordScreen();
//Video View
videoView.setVisibility(View.VISIBLE);
videoView.setVideoURI(Uri.parse(videoUri));
videoView.start();
}
}
private void screenRecord() {
if (mediaRecorder == null)
{
startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(), MEDIA_CODE);
return;
}
virtualDisplay = createVirtualDisplay();
mediaRecorder.start();
}
private VirtualDisplay createVirtualDisplay() {
return mediaProjection.createVirtualDisplay("MainActivity", DISPLAY_WIDTH, DISPLAY_HEIGHT, mScreenDensity,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mediaRecorder.getSurface(), null, null);
}
private void initRecorder() {
try {
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
videoUri = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
+ new StringBuilder("/Video_Screen").append(new SimpleDateFormat("dd-MM-yyyy-hh_mm_ss")
.format(new Date())).append(".mp4").toString();
mediaRecorder.setOutputFile(videoUri);
mediaRecorder.setVideoSize(DISPLAY_WIDTH,DISPLAY_HEIGHT);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setVideoEncodingBitRate(512*1000);
mediaRecorder.setVideoFrameRate(30);
int rotation = getWindowManager().getDefaultDisplay().getRotation();
int orientation = ORIENTAIONS.get(rotation + 90);
mediaRecorder.setOrientationHint(orientation);
mediaRecorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode != REQUEST_CODE)
{
Toast.makeText(MainActivity.this, "Unknown error..", Toast.LENGTH_SHORT).show();
return;
}
if (requestCode != RESULT_OK) {
Toast.makeText(MainActivity.this, "Permission denied..", Toast.LENGTH_SHORT).show();
btnToggle.setChecked(false);
return;
}
mediaProjectionCallback = new MediaProjectionCallback();
mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
mediaProjection.registerCallback(mediaProjectionCallback, null);
virtualDisplay = createVirtualDisplay();
mediaRecorder.start();
}
private class MediaProjectionCallback extends MediaProjection.Callback {
@Override
public void onStop() {
if (btnToggle.isChecked())
{
btnToggle.setChecked(false);
mediaRecorder.stop();
mediaRecorder.reset();
}
mediaProjection = null;
stopRecordScreen();
super.onStop();
}
}
private void stopRecordScreen() {
if (virtualDisplay == null)
return;
virtualDisplay.release();
destroyMediaProjection();
}
private void destroyMediaProjection() {
if (mediaProjection != null)
{
mediaProjection.unregisterCallback(mediaProjectionCallback);
mediaProjection.stop();
mediaProjection = null;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case REQUEST_CODE:
if ((grantResults.length > 0) && (grantResults[0] + grantResults[1] == PackageManager.PERMISSION_GRANTED))
{
toggleScreenShare(btnToggle);
}
else
{
btnToggle.setChecked(false);
Snackbar.make(rootLayout, "Permissions", Snackbar.LENGTH_INDEFINITE)
.setAction("ENABLE", new View.OnClickListener() {
@Override
public void onClick(View v) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO}, REQUEST_CODE);
}
}).show();
}
return;
}
}
}
Ниже Log_cat
Process: com.aman.screenrecorderapp, PID: 32086
java.lang.NullPointerException: Attempt to invoke virtual method 'android.hardware.display.VirtualDisplay android.media.projection.MediaProjection.createVirtualDisplay(java.lang.String, int, int, int, int, android.view.Surface, android.hardware.display.VirtualDisplay$Callback, android.os.Handler)' on a null object reference
at com.aman.screenrecorderapp.MainActivity.createVirtualDisplay(MainActivity.java:146)
at com.aman.screenrecorderapp.MainActivity.screenRecord(MainActivity.java:140)
at com.aman.screenrecorderapp.MainActivity.toggleScreenShare(MainActivity.java:119)
at com.aman.screenrecorderapp.MainActivity.access$200(MainActivity.java:36)
at com.aman.screenrecorderapp.MainActivity$1.onClick(MainActivity.java:107)
at android.view.View.performClick(View.java:4799)
at android.widget.CompoundButton.performClick(CompoundButton.java:120)
at android.view.View$PerformClick.run(View.java:20042)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5422)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:914)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707)```