Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Excuse me for simple question,I'm completely beginner java and android developer. How I can get the instance of Activity in setCameraDisplayOrientation when surfaceChanged is called?

public class MyActivity extends Activity
{
    private Camera mCamera;
    private CameraPreview mPreview;
    public final int cameraId = 0;
    public Activity activity = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

    activity = this; 

        // Create an instance of Camera
        mCamera = getCameraInstance();

        // Create our Preview view and set it as the content of our activity.
        mPreview = new CameraPreview(this, mCamera);
        FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
        preview.addView(mPreview);
    }

    public void setCameraDisplayOrientation(Activity activity,
                        int cameraId, android.hardware.Camera camera) {

    }

    public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    private SurfaceHolder mHolder;
    private Camera mCamera;
    ...
    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        ...
        setCameraDisplayOrientation(activity, cameraId, mCamera);
        ....
    }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
113 views
Welcome To Ask or Share your Answers For Others

1 Answer

Here is a way to avoid memory leaks using static variable: make static weak reference to Activity instance that will be set in onCreate(Bundle) method.

  1. Write in your secondary class something like below:

    public Class SecondClass {
        private static WeakReference<Activity> mActivityRef;
        public static void updateActivity(Activity activity) {
            mActivityRef = new WeakReference<Activity>(activity);
        }
    
  2. Then in onCreate(Bundle) method of your Activity class:

    @Override
    onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SecondClass.updateActivity(this);
        ...
    }
    
  3. Use activity instance this way:

    mActivityRef.get()
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...