I am using MediaProjection to take screenshot.This is what I am doing.I created an overlay icon using service.On clicking the overlay icon a screenshot is taken.The problem is that whenever the Application is killed either by pressing back button or manually by swiping it the MediaProjection object is lost.Is there a way to maintain the MediaProjection and avoiding requesting for MediaProjection each time application is killed. I have already seen this but I am still unable to do it.
In my Mainactivity Onclick contains startActivityForResult and the resulting onActivityResult is as follows:
@Override
protected void onActivityResult(final int requestCode,final int resultCode,final Intent data)
{
if (requestCode == requestcode)
{
if (resultCode == RESULT_OK)
{
Singelton.setScreenshotPermission((Intent) data.clone());
Singelton.putmanger(mediaProjectionManager);
}else if (resultCode==RESULT_CANCELED) {
Singelton.setScreenshotPermission(null);
}
}
}
The Singelton class is as follows:
protected static void setScreenshotPermission(final Intent permissionIntent)
{
screenshotPermission = permissionIntent;
//screenshotPermission becomes null once the application is killed
}
public static MediaProjection getData()
{
return (mediaProjection);
}
public static void getScreenshotPermission()
{
if (screenshotPermission != null)
{
Log.d("screenshotpermisson", "screenshotPermission != null ");
if(mediaProjection!=null)
{
Log.d("mediaprojection", "mediaprojection != null ");
mediaProjection.stop();
mediaProjection = null;
}
mediaProjection = mediaProjectionManager.getMediaProjection(Activity.RESULT_OK, (Intent) screenshotPermission.clone());
}
else
{
//Here I need to request for media projection again without starting activity
}
}
My Service class for overlay icon handles click as follows:
public void createDisplay()
{
if (mediaProjection == null)
{
Singelton.getScreenshotPermission();
mediaProjection = Singelton.getData();
}
mImageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 1);
vd = mediaProjection.createVirtualDisplay("screen-mirror", width, height, mDensity, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mImageReader.getSurface(), null, null);
mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener(){..}
}
I am new to android and having a hard time figuring this out.Any help will be appreciated.