【问题标题】:Implementing onActivityResult() in a Service在服务中实现 onActivityResult()
【发布时间】:2019-01-03 12:14:16
【问题描述】:

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

问题是要使用它,我需要使用像: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();
    }
}

【问题讨论】:

  • @TimCastelijns:那你有什么推荐的?这对我来说非常重要。为了更好地了解我必须做什么,请从以下内容开始:stackoverflow.com/questions/54009658/… 我被建议使用这些服务。

标签: java android service onactivityresult startactivityforresult


【解决方案1】:

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

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

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

【讨论】:

【解决方案2】:

虽然服务可以参与屏幕录制,但必须从活动中获得许可。因此,请在开始服务之前征求许可。

例如,在this sample app 中,the RecorderService 是实际开始和停止屏幕录制的对象,the MainActivity 是在启动该服务之前请求权限的对象。该活动使用Theme.Translucent.NoTitleBar,因此它没有自己的 UI,除了系统权限对话框。

【讨论】:

  • 这似乎正是我正在寻找的,目前我只是快速浏览了一下。我的疑惑/建议如下: 1) 建议,你为什么不用这样的东西来保存文件名:public String getCurSysDate() { return new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss")。格式(新日期()); } 2) 没有录制外部音频,对吧? 3) 在你看来,我怎样才能把从录制开​​始到 setContentTitle 的时间,例如 0 秒、10 秒、1 分钟和 30 秒。
  • @Paul:“你为什么不用这样的东西来保存文件名”——因为这本书的例子已经足够复杂了。 “没有录制外部音频,对吧?” - 正确的。理论上,您可以通过MediaRecorder 记录它并尝试使用MediaMuxer 之类的东西来合并它们。我还没有尝试过。 “我怎样才能把从录制开​​始到 setContentTitle 的时间”——如果你的意思是 Notification,你应该能够使用 NotificationManager 和你的 ID 更新 NotificationstartForeground()一起使用。
  • 实际上,音频的事实非常简单,只需这样做:recorder = new MediaRecorder ();录音机.setAudioSource (MediaRecorder.AudioSource.MIC); recorder.setVideoSource (MediaRecorder.VideoSource.SURFACE); recorder.setOutputFormat (MediaRecorder.OutputFormat.MPEG_4); recorder.setVideoFrameRate (config.frameRate); recorder.setVideoEncoder (MediaRecorder.VideoEncoder.H264); recorder.setAudioEncoder (MediaRecorder.AudioEncoder.AMR_NB); recorder.setVideoSize (config.width, config.height); recorder.setVideoEncodingBitRate (config.bitRate); ....
  • 添加权限: 我不太确定的是如何为 7.0 版本请求运行时权限。我认为请求应该进入活动,你怎么看?
  • 对于通知的事实,我不确定哪种方式是正确的,考虑到我必须每秒更新通知的标题。
猜你喜欢
  • 2016-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-31
  • 2011-02-09
  • 2018-05-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多