服务中的 Android MediaProjectionManager [英] Android MediaProjectionManager in Service

查看:63
本文介绍了服务中的 Android MediaProjectionManager的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建一个必须在服务中使用 MediaProjectionManager 的应用程序.但我无法解决它,因为 'startActivityForResult' 不能在 Service 类中使用.

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.

推荐答案

我真的很想从服务中做到这一点,这就是我发现这个问题的方式.这是我想到的最接近的,所以把它扔在那里,直到出现更好的答案.这是一种从 Activity 中执行此操作的方法,几乎​​就像在服务中执行此操作一样:

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);
    }

使 Activity 在您的 AndroidManifest.xml 中不可见

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>

注意事项:

您正在截屏的应用程序将在短时间内失去焦点.

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

这篇关于服务中的 Android MediaProjectionManager的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆