获取活动实例 [英] Get activity instance

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

问题描述

对不起简单的问题,我是初学java和android开发者。当调用surfaceChanged时,如何在setCameraDisplayOrientation中获取Activity的实例?

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


推荐答案

这是一种使用静态变量来避免内存泄漏的方法:对将在onCreate(Bundle)方法中设置的Activity实例进行静态弱引用。

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. 在您的二级课程中写下如下内容:

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


  • 然后在Activity类的onCreate(Bundle)方法中:

  • Then in onCreate(Bundle) method of your Activity class:

    @Override
    onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SecondClass.updateActivity(this);
        ...
    }
    


  • 以这种方式使用活动实例:

  • Use activity instance this way:

    mActivityRef.get()
    


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

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆