4

我面临一个与Activity. 我的情况如下:

我开始活动 A,单击一个按钮,然后从图库中选择一个图像,然后onActivityResult我调用了startActivity(B)

现在,在我的活动 B 中,在 A 中选择的图像已显示在ListView其上。

现在单击我调用的按钮startActivityforResult(Recorder class)打开了一个新活动,这是一个自定义录像机活动。

现在在活动记录器中单击停止按钮mediaRecorder停止,释放并保存视频,然后setResult再次进入活动 B 进入onActivityResult(). 但问题是:

我在这里发现了两个不同的案例:

  1. 第一个是当我将我的 Recorder 类声明为 Landscape 时:

    在 Recorder 类中单击停止按钮时,我的屏幕变黑,几秒钟后活动 A 开始。

  2. 第二个是当我将 Recorder 类的方向更改为纵向模式时:

    此处单击记录器类活动 B 中的停止按钮开始(无黑屏),但几秒钟后活动 A 再次开始。

我在这里观察到的另一件事:

  • 我在活动 B 中替换startActivityForResult()startActivity()记录器活动,我再次调用startActivity(B)它显示活动 B,但是在几秒钟后发生了一些新的事情,相同的活动 B 再次开始。
  • 我确信这只是因为MediaRecorder当我评论了我Recorder班上的所有媒体记录器代码时,一切都很好。

我的记录器类代码在这里:

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

2 回答 2

1

我没有看到任何可以保存和恢复 Activity 实例状态的代码。当 Android 将另一个 Activity 放在顶部时,它可能会销毁并重新创建 Activity,当您重新定位设备时它也会重新启动 Activity。在这两种情况下,您似乎确实遇到了问题。

然后,Android 会尝试恢复活动,但您需要通过存储和恢复您的状态来提供帮助。默认情况下不会恢复太多,尤其是您自己的字段只会获得空值。

实施onSavedInstanceState,放入对您的程序继续工作可能很重要的提供的包(地图)。然后检查 onCreate 参数 savedInstanceState 是否不为空,如果是,则从此包中恢复您认为重要的内容。另外,实现onRestoreInstanceState

这是演示问题的代码。这是一个简单的应用程序,具有一个字符串类型的状态变量。启动程序并尝试将设备从纵向重新定向为横向。您的消息文本将变为“我的状态为空但现在恢复为 13c140ff7e6”之类的内容。因此 create() 已被第二次调用,状态字段变为空,现在必须从传递的包中恢复。同时,静态字段中的值很可能会被保留(在某些情况下也可能会消失),这表明这不是应用程序的完全冷重启。这可以解释简单的重定向可能会使不知道这些事情的应用程序崩溃。为结果启动另一个活动可能会导致类似的效果。该代码还演示了应该如何解决问题。

package com.example.state;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

String myState;

static String staticString;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView sv = (TextView) findViewById(R.id.main);

    if (savedInstanceState != null) {
        String state = savedInstanceState.getString("myState");
        sv.setText("My state was " + myState + " but now restored to "
                + state+", static "+staticString);
        myState = state;
    } else {
        String state = Long.toHexString(System.currentTimeMillis());
        sv.setText("My state: " + myState + ", cold start, now set to "+state);
        myState = state;
        staticString = state;
    }
}

protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    myState = savedInstanceState.getString("myState");
}

protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("myState", myState);
}
}

带布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/main"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
     />

</RelativeLayout>
于 2013-01-06T11:30:47.833 回答
1

您的录音机类似乎有问题。请尝试使用此代码一次:

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
//      }
//  }
}

让我知道它是否有效。

谢谢

于 2013-01-08T08:53:15.827 回答