Android MediaProjectionManager in Service

fahad_sust picture fahad_sust · Sep 3, 2015 · Viewed 10.9k times · Source

I want to build an app where I have to use MediaProjectionManager in a Service. But I can not solve it as 'startActivityForResult' can't use in Service class.

Answer

netsplit picture netsplit · Sep 29, 2015

I really want to do this from a service, which is how I found this question. This is the closest I've came up, so just throwing this out there, till a better answer comes along. Here's a way to do it from an activity that's almost like doing it from a service:

import static your.package.YourClass.mediaProjectionManager;

public class MainActivity extends Activity {

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(null);
    mediaProjectionManager = (MediaProjectionManager)getContext().getSystemService(MEDIA_PROJECTION_SERVICE);
    startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(), 1);
    }

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1) {
        if (resultCode == Activity.RESULT_OK) {
            mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
            this.finish();
        }
    }
}

Then in your service when ever you need permission call

private void openMainActivity() {
    Intent mainIntent = new Intent(getContext(), MainActivity.class);
    mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(mainIntent);
    }

To make the activity invisible in your AndroidManifest.xml

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.NoDisplay"
        android:excludeFromRecents="true"
        android:screenOrientation="portrait">
    </activity>

Caveats:

For a brief second the application you're screenshooting will lose focus.

For a brief second your app will be the foreground app, so don't trip over your own shoelaces