获取活动实例

2022-09-01 20:26:49

请原谅我简单的问题,我完全是Java和Android开发人员的初学者。如何获取 setCameraDisplay 在调用 surfaceChanged 时的活动实例?

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);
        ....
    }
    }
}

答案 1

以下是使用静态变量避免内存泄漏的方法:对将在 onCreate(Bundle) 方法中设置的活动实例进行静态弱引用。

  1. 在你的中学课堂上写下如下内容:

    public Class SecondClass {
        private static WeakReference<Activity> mActivityRef;
        public static void updateActivity(Activity activity) {
            mActivityRef = new WeakReference<Activity>(activity);
        }
    
  2. 然后在活动类的 onCreate(Bundle) 方法中:

    @Override
    onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SecondClass.updateActivity(this);
        ...
    }
    
  3. 以这种方式使用活动实例:

    mActivityRef.get()
    

答案 2
Activity a = (Activity) getContext();

只要您将当前活动作为构造函数中的上下文传递,就像您已经在做的那样。


推荐