java - 在服务中实现 onActivityResult()

标签 java android service onactivityresult startactivityforresult

我有以下代码,它应该使用服务记录设备屏幕。

问题是,要使用它,我需要使用如下调用:startActivityForResult/onActivityResult,以获得能够录制屏幕的权限。

但是在 Android Service 上没有这样的调用。

我必须开始这样的事情:

startActivityForResult (mProjectionManager.createScreenCaptureIntent (), CAST_PERMISSION_CODE);

代码:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode != CAST_PERMISSION_CODE) {
            Log.w("class:", "Unknown request code: " + requestCode);
            return;
        }
        Log.w("class:", "onActivityResult:resultCode");
        if (resultCode != RESULT_OK) {
            startRec = false;
            Toast.makeText(this, "Screen Cast Permission Denied :(", Toast.LENGTH_SHORT).show();
            return;
        }
        prepareRecording("start");
        mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);

        Log.w("class:", "onActivityResult:mMediaProjection");

        // TODO Register a callback that will listen onStop and release & prepare the recorder for next WidgetProvider
        // mMediaProjection.registerCallback(callback, null);
        mVirtualDisplay = getVirtualDisplay();
        mMediaRecorder.start();
    } 

我如何提出建议?

完整代码:

package com.unkinstagram;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Environment;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import static android.app.Activity.RESULT_OK;

class Constants {
    public interface ACTION {
        public static String MAIN_ACTION = "com.unkinstagram.action.main";
        public static String STARTFOREGROUND_ACTION = "com.unkinstagram.action.startforeground";
        public static String STOPFOREGROUND_ACTION = "com.unkinstagram.action.stopforeground";
        public static String REC_ACTION = "com.unkinstagram.action.rec";
        public static String STOP_ACTION = "com.unkinstagram.action.stop";
    }

    public interface NOTIFICATION_ID {
        public static int FOREGROUND_SERVICE = 101;
    }
}

public class ForegroundService extends Service {
    private static final String LOG_TAG = "class:";

    private static final int CAST_PERMISSION_CODE = 22;
    private DisplayMetrics mDisplayMetrics;
    private MediaProjection mMediaProjection;
    private VirtualDisplay mVirtualDisplay;
    private MediaRecorder mMediaRecorder;
    private MediaProjectionManager mProjectionManager;

    private boolean startRec = false;

    @Override
    public void onCreate() {
        super.onCreate();
        mDisplayMetrics = new DisplayMetrics();
        mMediaRecorder = new MediaRecorder();
        mProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        WindowManager window = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        window.getDefaultDisplay().getMetrics(mDisplayMetrics);
        Log.v(LOG_TAG,"create");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
            Log.i(LOG_TAG, "Received Start Foreground Intent ");
            Intent notificationIntent = new Intent(this, MainActivity2.class);
            notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

            Intent recIntent = new Intent(this, ForegroundService.class);
            recIntent.setAction(Constants.ACTION.REC_ACTION);
            PendingIntent pRecIntent = PendingIntent.getService(this, 0, recIntent, 0);

            Intent stopIntent = new Intent(this, ForegroundService.class);
            stopIntent.setAction(Constants.ACTION.STOP_ACTION);
            PendingIntent pStopIntent = PendingIntent.getService(this, 0, stopIntent, 0);

            Notification notification = new NotificationCompat.Builder(this)
                    .setContentTitle("Stai per registrare lo schermo del device.")
                    .setSmallIcon(R.drawable.ic_videocam_off)
                    .setContentIntent(pendingIntent)
                    .setOngoing(true)
                    .addAction(0, "Rec", pRecIntent)
                    .addAction(0, "Stop", pStopIntent)
                    .build();
            startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE, notification);

        } else if (intent.getAction().equals(Constants.ACTION.REC_ACTION)) {
            Log.i(LOG_TAG, "Clicked Rec");
            startRecording();
        } else if (intent.getAction().equals(Constants.ACTION.STOP_ACTION)) {
            Log.i(LOG_TAG, "Clicked Stop");
            stopRecording();
            stopForeground(true);
            stopSelf();
        } else if (intent.getAction().equals(Constants.ACTION.STOPFOREGROUND_ACTION)) {
            Log.i(LOG_TAG, "Received Stop Foreground Intent");
            stopForeground(true);
            stopSelf();
        }
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(LOG_TAG, "In onDestroy");
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void startRecording() {
        startRec = true;
        // If mMediaProjection is null that means we didn't get a context, lets ask the user
        Log.w("class:", "startRecording:start");
        if (mMediaProjection == null) {
            // This asks for user permissions to capture the screen
            Log.w("class:", "startRecording:startResult");
            startActivityForResult(mProjectionManager.createScreenCaptureIntent(), CAST_PERMISSION_CODE);
            Log.w("class:", "startRecording:endResult");
            return;
        }
        Log.w("class:", "startRecording:end");
        mVirtualDisplay = getVirtualDisplay();
        mMediaRecorder.start();
    }

    private void stopRecording() {
        startRec = false;
        Log.w("class:", "stopRecording:start");
        if (mMediaRecorder != null) {
            mMediaRecorder.stop();
            mMediaRecorder.reset();
            //mMediaRecorder = null;
        }
        if (mVirtualDisplay != null) {
            mVirtualDisplay.release();
            //mVirtualDisplay = null;
        }
        if (mMediaProjection != null) {
            mMediaProjection.stop();
            //mMediaProjection = null;
        }
        Log.w("class:", "stopRecording:end");
    }

    public String getCurSysDate() {
        return new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
    }

    private void prepareRecording(String name) {
        if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            Toast.makeText(this, "Failed to get External Storage", Toast.LENGTH_SHORT).show();
            return;
        }
        final String directory = Environment.getExternalStorageDirectory() + File.separator + "Recordings";
        final File folder = new File(directory);
        boolean success = true;
        if (!folder.exists()) {
            success = folder.mkdir();
        }
        if (!success) {
            Toast.makeText(this, "Failed to create Recordings directory", Toast.LENGTH_SHORT).show();
            return;
        }

        String videoName = (name + "_" + getCurSysDate() + ".mp4");
        String filePath = directory + File.separator + videoName;

        int width = mDisplayMetrics.widthPixels;
        int height = mDisplayMetrics.heightPixels;

        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mMediaRecorder.setVideoEncodingBitRate(8000 * 1000);
        mMediaRecorder.setVideoFrameRate(24);
        mMediaRecorder.setVideoSize(width, height);
        mMediaRecorder.setOutputFile(filePath);

        try {
            mMediaRecorder.prepare();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

    }

    private VirtualDisplay getVirtualDisplay() {
        int screenDensity = mDisplayMetrics.densityDpi;
        int width = mDisplayMetrics.widthPixels;
        int height = mDisplayMetrics.heightPixels;
        return mMediaProjection.createVirtualDisplay(this.getClass().getSimpleName(),
                width, height, screenDensity,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                mMediaRecorder.getSurface(), null, null);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode != CAST_PERMISSION_CODE) {
            Log.w("class:", "Unknown request code: " + requestCode);
            return;
        }
        Log.w("class:", "onActivityResult:resultCode");
        if (resultCode != RESULT_OK) {
            startRec = false;
            Toast.makeText(this, "Screen Cast Permission Denied :(", Toast.LENGTH_SHORT).show();
            return;
        }
        prepareRecording("start");
        mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);

        Log.w("class:", "onActivityResult:mMediaProjection");

        // TODO Register a callback that will listen onStop and release & prepare the recorder for next WidgetProvider
        // mMediaProjection.registerCallback(callback, null);
        mVirtualDisplay = getVirtualDisplay();
        mMediaRecorder.start();
    }
}

最佳答案

所以您想在服务中使用 MediaProjection。要使用MediaProjection,需要用户授予权限,然后使用onActivityResult中返回的Intent创建MediaProjection。但是,您正在使用服务,并且没有可用的 onActivityResult。

这是一个有用的 github 问题:https://github.com/mtsahakis/MediaProjectionDemo/issues/7 。还有一些您可以使用的要点。

基本思想是使用 Activity 来请求权限,然后使用包装结果 Intent 的 Intent 启动服务(Intent 也是一个 parceable,因此可以将其放入另一个 Intent 中)。

关于java - 在服务中实现 onActivityResult(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54022097/

相关文章:

java - 我的代码抛出 ArrayIndexOutOfBoundsException

java - 按钮闪光

android-如何检查本地 Sqlite 数据库中的新数据并持续推送通知?

android - 通话录音/处理服务! - 安卓

web-services - 服务是否应在每次请求时要求提供凭据?

java - Swing Jbutton : showing border and background only when it is hovered

java - neo4j:用一个节点替换具有相同属性的多个节点

java - 如何将值从一个jsp页面发送到另一个页面但重定向到其他页面?

java - 广播接收器,在启动时检查复选框首选项状态,然后发送通知

android - 从 WebView html 在手机中创建联系人 - Android 应用程序