本文介绍了关于Android的活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在面临一个很大的问题涉及到活动。我的情况如下:

我开始活动A,点击一个按钮,然后选择了一个形象的画廊则在 onActivityResult 我叫 startActivity(B)

现在在我的活动B,在选定的图像已被证明对的ListView 这是显示。

现在在点击一个按钮,我叫 startActivityforResult(录像机类)打开了一个新的活动,这是一个自定义视频录像机的活动。

现在在点击停止按钮活动记录 mediaRecorder 停止,释放和保存视频,然后在的setResult 不言而喻再次活动B插入 onActivityResult()。但现在的问题是:

有两种不同的情况下,我在这里找到:

  1. 第一个是,当我宣布我的录音机类景观:

    下面的点击记录类停止按钮,屏幕突然变成黑色和A开始几秒钟活动后。

  2. 第二个是,当我改变了录音机类的方向为纵向模式:

    下面的点击记录课堂活动B停止按钮启动(无黑屏),但之后又几秒钟活性的开始。

还有一件事,我发现在这里:

  • 在我替换 startActivityForResult() startActivity()的活动B和从记录的活动我再次呼吁 startActivity(B)这表明活动B,但几秒钟后,同样的b活动重新开始。
  • 在这里一些新的东西发生
  • 我相信这是只是因为 MediaRecorder ,当我评论从我的记录所有的媒体记录code 类则是罚款。

录音机类的我的code是在这里:

 公共类录音机延伸活动实现SurfaceHolder.Callback {

    / **第一次创建活动时调用。 * /
    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);

        mediaRecorder =新MediaRecorder();
        的setContentView(R.layout.recorde);
        initMediaRecorder();

        定时器=新的Timer();
        TimerTask的TimerTask的=新的TimerTask(){
            @覆盖
            公共无效的run(){
                如果(柜< = 10)
                    反++;
                // Android的UI获得continouly更新
                其他 {
                    //如果条件满打满计时器将停在这里
                    mediaRecorder.stop();
                    mediaRecorder.reset();
                    mediaRecorder.release();
                    timer.cancel();
                    Recorder.this.finish();
                    意图I =新的意图(Recorder.this,B.class);
                    的setResult(Activity.RESULT_OK,i.putExtra(returnedVideo,strPath中));
                }
            }
        };
        timer.schedule(TimerTask的,1000,1000);

        SurfaceView myVideoView =(SurfaceView)findViewById(R.id.videoview);
        surfaceHolder = myVideoView.getHolder();
        surfaceHolder.addCallback(本);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        为myButton =(按钮)findViewById(R.id.mybutton);
        myButton.setOnClickListener(myButtonOnClickListener);
    }

    私人Button.OnClickListener myButtonOnClickListener
    =新Button.OnClickListener(){

        公共无效的onClick(查看为arg0){
            // TODO自动生成方法存根
            mediaRecorder.stop();
            mediaRecorder.reset();
            mediaRecorder.release();
            timer.cancel();
            Recorder.this.finish();

            意图I =新的意图(Recorder.this,B.class);
            的setResult(Activity.RESULT_OK,i.putExtra(returnedVideo,strPath中));
        }};

        公共无效surfaceChanged(SurfaceHolder为arg0,诠释ARG1,诠释ARG2,诠释ARG3){
            // TODO自动生成方法存根

        }
        公共无效surfaceCreated(SurfaceHolder为arg0){
            // TODO自动生成方法存根
            prepareMediaRecorder();
        }
        公共无效surfaceDestroyed(SurfaceHolder为arg0){
            // TODO自动生成方法存根

            mediaRecorder.stop();
            mediaRecorder.release();
            //Recorder.this.finish();
        }

        @覆盖
        公共无效onBack pressed(){
            // TODO自动生成方法存根
            super.onBack pressed();

            mediaRecorder.stop();
            mediaRecorder.release();
        }

        私人无效initMediaRecorder(){
            随机genraotr =新的随机();
            INT N = 10000;
            N = genraotr.nextInt(N);

            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
            mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
            CamcorderProfile camcorderProfile_HQ = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
            mediaRecorder.setProfile(camcorderProfile_HQ);
            mediaRecorder.setOutputFile(/ SD卡/ my_video+ N +MP4。);
            strPath的=/sdcard/my_video"+n+".mp4;
            mediaRecorder.setMaxDuration(10000); //设置最大持续时间10秒。
            mediaRecorder.setMaxFileSize(5000000); //设置最大文件大小为5M
        }

        私人无效prepareMediaRecorder(){
            mediaRecorder.set previewDisplay(surfaceHolder.getSurface());
            尝试 {
                mediaRecorder prepare()。
                mediaRecorder.start();
            }赶上(IllegalStateException异常E){
                // TODO自动生成的catch块
                e.printStackTrace();
            }赶上(IOException异常E){
                // TODO自动生成的catch块
                e.printStackTrace();
            }
        }
}
 

解决方案

这似乎有一个与你的刻录机类的问题。使用这个code请再试一次:

 公共类AndroidVideoCapture延伸活动{

    私人相机myCamera;
    私人MyCameraSurfaceView myCameraSurfaceView;
    私人MediaRecorder mediaRecorder;

    按钮myButton的;
    SurfaceHolder surfaceHolder;
    布尔记录;
    公共静态字符串strPath的;

    / **第一次创建活动时调用。 * /
    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);

        记录= FALSE;

        的setContentView(R.layout.main);

        //获取相机为preVIEW
        myCamera = getCameraInstance();
        如果(myCamera == NULL){
            Toast.makeText(AndroidVideoCapture.this,
                    轮不到相机,
                    Toast.LENGTH_LONG).show();
        }

        myCameraSurfaceView =新MyCameraSurfaceView(这一点,myCamera);
        的FrameLayout myCamera preVIEW =(的FrameLayout)findViewById(R.id.videoview);
        myCamera preview.addView(myCameraSurfaceView);

        为myButton =(按钮)findViewById(R.id.mybutton);
        myButton.setOnClickListener(myButtonOnClickListener);
    }

    Button.OnClickListener myButtonOnClickListener
    =新Button.OnClickListener(){

        公共无效的onClick(视图v){
            // TODO自动生成方法存根
            如果(录音){
                //停止录制并发行摄像头
                mediaRecorder.stop(); //停止录制
                releaseMediaRecorder(); //释放MediaRecorder对象
                意图I =新的意图(AndroidVideoCapture.this,TakeAnotherPhoto.class);
                i.putExtra(returnedVideo,strPath的);
                的setResult(Activity.RESULT_OK,我);

                //保存退出后,
                完();
            }其他{

                //发布MediaRecorder开始前摄像头
                releaseCamera();

                如果(!prepareMediaRecorder()){
                    Toast.makeText(AndroidVideoCapture.this,
                            在失败prepareMediaRecorder()\ N  - !结束 - ,
                            Toast.LENGTH_LONG).show();
                    完();
                }

                mediaRecorder.start();
                记录= TRUE;
                myButton.setText(STOP);
            }
        }};

    私人摄像机getCameraInstance(){
        // TODO自动生成方法存根
        相机C = NULL;
        尝试 {
            C = Camera.open(); //尝试获取摄像头实例
        }
        赶上(例外五){
            //相机无法使用(使用或不存在)
        }
        返回℃; //如果相机是不可用,则返回null
    }

    私人布尔prepareMediaRecorder(){

        随机genraotr =新的随机();
        INT N = 10000;
        N = genraotr.nextInt(N);

        myCamera = getCameraInstance();
        mediaRecorder =新MediaRecorder();

        myCamera.unlock();
        mediaRecorder.setCamera(myCamera);

        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));

        mediaRecorder.setOutputFile(/ SD卡/ auction_video+ N +MP4。);
        strPath的=/sdcard/auction_video"+n+".mp4;
        mediaRecorder.setMaxDuration(10000); //设置最大持续时间10秒。
        mediaRecorder.setMaxFileSize(5000000); //设置最大文件大小为5M

        mediaRecorder.set previewDisplay(myCameraSurfaceView.getHolder()getSurface());

        尝试 {
            mediaRecorder prepare()。
        }赶上(IllegalStateException异常E){
            releaseMediaRecorder();
            返回false;
        }赶上(IOException异常E){
            releaseMediaRecorder();
            返回false;
        }
        返回true;

    }

    保护无效的onPause(){
        super.onPause();
        releaseMediaRecorder(); //如果您使用的是MediaRecorder,先将它
        releaseCamera(); //在暂停时立即松开相机
    }

    私人无效releaseMediaRecorder(){
        如果(mediaRecorder!= NULL){
            mediaRecorder.reset(); //清晰的记录配置
            mediaRecorder.release(); //释放录像机对象
            mediaRecorder = NULL;
            myCamera.lock(); //锁定相机以备后用
        }
    }

    私人无效releaseCamera(){
        如果(myCamera!= NULL){
            myCamera.release(); //释放相机用于其它应用
            myCamera = NULL;
        }
    }

    公共类MyCameraSurfaceView扩展了SurfaceView实现SurfaceHolder.Callback {

        私人SurfaceHolder mHolder;
        私人相机mCamera;

        公共MyCameraSurfaceView(上下文的背景下,相机摄像头){
            超(上下文);
            mCamera =摄像头;

            //安装SurfaceHolder.Callback所以我们得到通知时,该
            //下垫面创建和销毁。
            mHolder = getHolder();
            mHolder.addCallback(本);
            //德precated设置,但在Android上之前的版本3.0所需
            mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }

        公共无效surfaceChanged(SurfaceHolder持有人,INT格式,诠释权重,
                INT高度){
            //如果你的preVIEW可以改变或旋转,把这些事件的关心在这里。
            //确保调整或重新格式化之前停止preVIEW。

            如果(mHolder.getSurface()== NULL){
              // preVIEW表面不存在
              返回;
            }

            在进行更改之前//停止preVIEW
            尝试 {
                mCamera.stop preVIEW();
            }赶上(例外五){
              //忽略:试图阻止一个不存在的preVIEW
            }

            //做任何调整大小,旋转或重新格式化这里的变化

            //启动preVIEW使用新设置
            尝试 {
                mCamera.set previewDisplay(mHolder);
                mCamera.start preVIEW();

            }赶上(例外五){
            }
        }

        公共无效surfaceCreated(SurfaceHolder持有者){
            // TODO自动生成方法存根
            //表面有被创建,现在告诉相机在哪里画preVIEW。
            尝试 {
                mCamera.set previewDisplay(保持器);
                mCamera.start preVIEW();
            }赶上(IOException异常E){
            }
        }

        公共无效surfaceDestroyed(SurfaceHolder持有者){
            // TODO自动生成方法存根

        }
    }

    @覆盖
    公共无效onBack pressed(){
        // TODO自动生成方法存根
        super.onBack pressed();

        mediaRecorder.stop(); //停止录制
        releaseMediaRecorder(); //释放MediaRecorder对象
        //保存退出后,
        完();
    }

//公共无效showMessage(标题字符串,字符串的消息,最终的上下文语境){
//      尝试
// {
// AlertDialog.Builder alt_bld =新AlertDialog.Builder(上下文);
// alt_bld.setTitle(职称);
// alt_bld.setMessage(消息);
// alt_bld.setCancelable(假);
// alt_bld.setNeutralButton(OK,新DialogInterface.OnClickListener(){
//
//公共无效的onClick(DialogInterface对话,诠释它){
// // TODO自动生成方法存根
// dialog.dismiss();
//
//意图I =新的意图(AndroidVideoCapture.this,TakeAnotherPhoto.class);
// i.putExtra(returnedVideo,strPath的);
//的setResult(Activity.RESULT_OK,我);
//}
//});
// alt_bld.show();
//}
//赶上(例外五){
// // TODO:处理异常
//}
//}
}
 

让我知道,如果它的工作原理。

感谢

I'm facing a big problem related to Activity. My scenario is as follows:

I starts activity A,clicked on a button then picked an image from the gallery then in onActivityResult I called startActivity(B).

Now in my Activity B that image selected in A has been shown on ListView which is showing.

Now on click of a button I called startActivityforResult(Recorder class) opened a new activity which is a custom video recorder activity.

Now in activity Recorder on clicking stop button mediaRecorder stops, release and save video and then after setResult it goes to again activity B into onActivityResult().But here is the problem:

Two different cases I found here:

  1. First one is when I declared my Recorder class as Landscape:

    Here on clicking stop button in Recorder class my screen goes black and after few seconds activity A starts.

  2. Second one is when I changed orientation of Recorder class to Portrait mode:

    Here on clicking stop button in Recorder class activity B starts (no black screen) but again after few seconds activity A starts.

One more thing which I observed here:

  • I replaced startActivityForResult() with startActivity() in activity B and from Recorder Activity i again called startActivity(B) which shows activity B,but here something new happens after few seconds the same activity B starts again.
  • I am sure this is just because of MediaRecorder as when I commented all media recorder code from my Recorder class then it was fine.

My Code of Recorder class is here:

public class Recorder extends Activity implements SurfaceHolder.Callback{

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mediaRecorder = new MediaRecorder();
        setContentView(R.layout.recorde);
        initMediaRecorder();

        timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                if(counter<=10)
                    counter++;
                //Android UI get Updated continouly
                else {
                    // If condition full filled the timer will stop here
                    mediaRecorder.stop();
                    mediaRecorder.reset();
                    mediaRecorder.release();
                    timer.cancel();
                    Recorder.this.finish();
                    Intent i = new Intent(Recorder.this,B.class);
                    setResult(Activity.RESULT_OK, i.putExtra("returnedVideo", strPath));
                }
            }
        };
        timer.schedule(timerTask, 1000, 1000);

        SurfaceView myVideoView = (SurfaceView)findViewById(R.id.videoview);
        surfaceHolder = myVideoView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        myButton = (Button)findViewById(R.id.mybutton);
        myButton.setOnClickListener(myButtonOnClickListener);
    }

    private Button.OnClickListener myButtonOnClickListener
    = new Button.OnClickListener(){

        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            mediaRecorder.stop();
            mediaRecorder.reset();
            mediaRecorder.release();
            timer.cancel();
            Recorder.this.finish();

            Intent i = new Intent(Recorder.this,B.class);
            setResult(Activity.RESULT_OK, i.putExtra("returnedVideo", strPath));
        }};

        public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
            // TODO Auto-generated method stub

        }
        public void surfaceCreated(SurfaceHolder arg0) {
            // TODO Auto-generated method stub
            prepareMediaRecorder();
        }
        public void surfaceDestroyed(SurfaceHolder arg0) {
            // TODO Auto-generated method stub

            mediaRecorder.stop();
            mediaRecorder.release();
            //Recorder.this.finish();
        }

        @Override
        public void onBackPressed() {
            // TODO Auto-generated method stub
            super.onBackPressed();

            mediaRecorder.stop();
            mediaRecorder.release();
        }

        private void initMediaRecorder(){
            Random genraotr = new Random();
            int n = 10000;
            n = genraotr.nextInt(n);

            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
            mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
            CamcorderProfile camcorderProfile_HQ = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
            mediaRecorder.setProfile(camcorderProfile_HQ);
            mediaRecorder.setOutputFile("/sdcard/my_video"+n+".mp4");
            strPath = "/sdcard/my_video"+n+".mp4";
            mediaRecorder.setMaxDuration(10000); // Set max duration 10 sec.
            mediaRecorder.setMaxFileSize(5000000); // Set max file size 5M
        }

        private void prepareMediaRecorder(){
            mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
            try {
                mediaRecorder.prepare();
                mediaRecorder.start();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
}
解决方案

It seems there is a problem with your recorder class. Please try once using this code:

public class AndroidVideoCapture extends Activity{

    private Camera myCamera;
    private MyCameraSurfaceView myCameraSurfaceView;
    private MediaRecorder mediaRecorder;

    Button myButton;
    SurfaceHolder surfaceHolder;
    boolean recording;
    public static String strPath;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        recording = false;

        setContentView(R.layout.main);

        //Get Camera for preview
        myCamera = getCameraInstance();
        if(myCamera == null){
            Toast.makeText(AndroidVideoCapture.this,
                    "Fail to get Camera",
                    Toast.LENGTH_LONG).show();
        }

        myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
        FrameLayout myCameraPreview = (FrameLayout)findViewById(R.id.videoview);
        myCameraPreview.addView(myCameraSurfaceView);

        myButton = (Button)findViewById(R.id.mybutton);
        myButton.setOnClickListener(myButtonOnClickListener);
    }

    Button.OnClickListener myButtonOnClickListener
    = new Button.OnClickListener(){

        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(recording){
                // stop recording and release camera
                mediaRecorder.stop();  // stop the recording
                releaseMediaRecorder(); // release the MediaRecorder object
                Intent i = new Intent(AndroidVideoCapture.this,TakeAnotherPhoto.class);
                i.putExtra("returnedVideo", strPath);
                setResult(Activity.RESULT_OK, i);

                //Exit after saved
                finish();
            }else{

                //Release Camera before MediaRecorder start
                releaseCamera();

                if(!prepareMediaRecorder()){
                    Toast.makeText(AndroidVideoCapture.this,
                            "Fail in prepareMediaRecorder()!\n - Ended -",
                            Toast.LENGTH_LONG).show();
                    finish();
                }

                mediaRecorder.start();
                recording = true;
                myButton.setText("STOP");
            }
        }};

    private Camera getCameraInstance(){
        // TODO Auto-generated method stub
        Camera c = null;
        try {
            c = Camera.open(); // attempt to get a Camera instance
        }
        catch (Exception e){
            // Camera is not available (in use or does not exist)
        }
        return c; // returns null if camera is unavailable
    }

    private boolean prepareMediaRecorder(){

        Random genraotr = new Random();
        int n = 10000;
        n = genraotr.nextInt(n);

        myCamera = getCameraInstance();
        mediaRecorder = new MediaRecorder();

        myCamera.unlock();
        mediaRecorder.setCamera(myCamera);

        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));

        mediaRecorder.setOutputFile("/sdcard/auction_video"+n+".mp4");
        strPath = "/sdcard/auction_video"+n+".mp4";
        mediaRecorder.setMaxDuration(10000); // Set max duration 10 sec.
        mediaRecorder.setMaxFileSize(5000000); // Set max file size 5M

        mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder().getSurface());

        try {
            mediaRecorder.prepare();
        } catch (IllegalStateException e) {
            releaseMediaRecorder();
            return false;
        } catch (IOException e) {
            releaseMediaRecorder();
            return false;
        }
        return true;

    }

    protected void onPause() {
        super.onPause();
        releaseMediaRecorder();       // if you are using MediaRecorder, release it first
        releaseCamera();              // release the camera immediately on pause event
    }

    private void releaseMediaRecorder(){
        if (mediaRecorder != null) {
            mediaRecorder.reset();   // clear recorder configuration
            mediaRecorder.release(); // release the recorder object
            mediaRecorder = null;
            myCamera.lock();           // lock camera for later use
        }
    }

    private void releaseCamera(){
        if (myCamera != null){
            myCamera.release();        // release the camera for other applications
            myCamera = null;
        }
    }

    public class MyCameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{

        private SurfaceHolder mHolder;
        private Camera mCamera;

        public MyCameraSurfaceView(Context context, Camera camera) {
            super(context);
            mCamera = camera;

            // Install a SurfaceHolder.Callback so we get notified when the
            // underlying surface is created and destroyed.
            mHolder = getHolder();
            mHolder.addCallback(this);
            // deprecated setting, but required on Android versions prior to 3.0
            mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }

        public void surfaceChanged(SurfaceHolder holder, int format, int weight,
                int height) {
            // If your preview can change or rotate, take care of those events here.
            // Make sure to stop the preview before resizing or reformatting it.

            if (mHolder.getSurface() == null){
              // preview surface does not exist
              return;
            }

            // stop preview before making changes
            try {
                mCamera.stopPreview();
            } catch (Exception e){
              // ignore: tried to stop a non-existent preview
            }

            // make any resize, rotate or reformatting changes here

            // start preview with new settings
            try {
                mCamera.setPreviewDisplay(mHolder);
                mCamera.startPreview();

            } catch (Exception e){
            }
        }

        public void surfaceCreated(SurfaceHolder holder) {
            // TODO Auto-generated method stub
            // The Surface has been created, now tell the camera where to draw the preview.
            try {
                mCamera.setPreviewDisplay(holder);
                mCamera.startPreview();
            } catch (IOException e) {
            }
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            // TODO Auto-generated method stub

        }
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();

        mediaRecorder.stop();  // stop the recording
        releaseMediaRecorder(); // release the MediaRecorder object
        //Exit after saved
        finish();
    }

//  public void showMessage(String title, String message, final Context context){
//      try
//      {
//          AlertDialog.Builder alt_bld = new AlertDialog.Builder(context);
//          alt_bld.setTitle(title);
//          alt_bld.setMessage(message);
//          alt_bld.setCancelable(false);
//          alt_bld.setNeutralButton("OK", new DialogInterface.OnClickListener() {
//
//              public void onClick(DialogInterface dialog, int which) {
//                  // TODO Auto-generated method stub
//                  dialog.dismiss();
//
//                  Intent i = new Intent(AndroidVideoCapture.this,TakeAnotherPhoto.class);
//                  i.putExtra("returnedVideo", strPath);
//                  setResult(Activity.RESULT_OK, i);
//              }
//          });
//          alt_bld.show();
//      }
//      catch (Exception e) {
//          // TODO: handle exception
//      }
//  }
}

and let me know if it works.

Thanks

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

07-08 22:30