Android是否按顺序执行任务?

搭便车者

Android Studio在我的项目中得到了一个非常有趣的行为。对不同活动的调用未按顺序执行!

我正在建立一个项目,其中的调用是这样的:

button.setOnClickListener()
{
    (1) call to cusom camera acivity
    (2) call to activity showing preview of latest captured image         
    (3) call to a doCrop() function
} 

但是执行后,实际流程为:

    (1) call to the doCrop() function
    (2) call to activity showing preview of image captured
    (3) call to cusom camera acivity

自定义相机活动处理所有必要SurfaceHolderSurfaceView操作。

随着SurfaceView布局的创建和销毁花费更多时间并且android首先切换到更简单的一项任务,会发生这种影响吗?

即使这样,它也应该跳至preview activity而不要doCrop()呼叫。

这是怎么回事 请给一些指点!

谢谢!

编辑:

命名为:

MainActivity - 主要活动

Preview -创建相机实例

CameraPreview -处理SurfaceView等

ImagePreview -显示指定的图像

Main activity 代码:

photo.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                File temp = new File(//path to store image);
                imageUri=Uri.fromFile(temp);

                 Intent intent = new Intent(MainActivity.this,Preview.class);

                startActivity(intent);

               // Image Preview Activity
                Intent intent1=new Intent(MainActivity.this,ImagePreview.class);
                startActivity(intent1);

                //Crop function
                doCrop();

            }

        });

preview activity代码:

public class Preview extends Activity {
    private static final String TAG = "CamTestActivity";
    CameraPreview preview;
    Button buttonClick;
    Camera camera;
    Activity act;
    Context ctx;
    Uri uri;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ctx = this;
        act = this;
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_preview);

        preview = new CameraPreview(this, (SurfaceView)findViewById(R.id.surfaceView));
        preview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        ((FrameLayout) findViewById(R.id.layout)).addView(preview);
        preview.setKeepScreenOn(true);

        buttonClick = (Button) findViewById(R.id.btnCapture);

        buttonClick.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v) {
                camera.takePicture(shutterCallback, rawCallback, pngCallback);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        int numCams = Camera.getNumberOfCameras();
        if(numCams > 0){
            try{
                camera = Camera.open(0);
                camera.startPreview();
                preview.setCamera(camera);
            } catch (RuntimeException ex){
                Toast.makeText(ctx, getString(R.string.camera_not_found), Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    protected void onPause() {
        if(camera != null) {
            camera.stopPreview();
            preview.setCamera(null);
            camera.release();
            camera = null;
        }
        super.onPause();
    }

    private void resetCam() {
        camera.startPreview();
        preview.setCamera(camera);
    }

    private void refreshGallery(File file) {
        Intent mediaScanIntent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        mediaScanIntent.setData(Uri.fromFile(file));
        sendBroadcast(mediaScanIntent);
    }

    ShutterCallback shutterCallback = new ShutterCallback() {
        public void onShutter() {

        }
    };

    PictureCallback rawCallback = new PictureCallback() {
        public void onPictureTaken(byte[] data, Camera camera) {

        }
    };

    PictureCallback pngCallback = new PictureCallback() {
        public void onPictureTaken(byte[] data, Camera camera) {
            new SaveImageTask().execute(data);
            resetCam();
            Log.d(TAG, "onPictureTaken - png");
        }
    };

    private class SaveImageTask extends AsyncTask<byte[], Void, Void> {
        @Override
        protected Void doInBackground(byte[]... data) {
              // save the image
            }
            catch (Exception e) { e.printStackTrace();}

            return null;
        }
    }
}

CameraPreview 代码:

class CameraPreview extends ViewGroup implements SurfaceHolder.Callback {
    private final String TAG = "Preview";

    SurfaceView mSurfaceView;
    SurfaceHolder mHolder;
    Size mPreviewSize;
    List<Size> mSupportedPreviewSizes;
    Camera mCamera;

    CameraPreview(Context context, SurfaceView sv) {
        super(context);

        mSurfaceView = sv;

        mHolder = mSurfaceView.getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void setCamera(Camera camera) {
        mCamera = camera;
        if (mCamera != null) {
            mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
            requestLayout();

            // get Camera parameters
            Camera.Parameters params = mCamera.getParameters();

            List<String> focusModes = params.getSupportedFocusModes();
            if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
                // set the focus mode
                params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);

                // set Camera parameters
                mCamera.setParameters(params);
            }
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
        final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
        setMeasuredDimension(width, height);

        if (mSupportedPreviewSizes != null) {
            mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (changed && getChildCount() > 0) {
            final View child = getChildAt(0);

            final int width = r - l;
            final int height = b - t;

            int previewWidth = width;
            int previewHeight = height;
            if (mPreviewSize != null) {
                previewWidth = mPreviewSize.width;
                previewHeight = mPreviewSize.height;
            }

            // Center the child SurfaceView within the parent.
            if (width * previewHeight > height * previewWidth) {
                final int scaledChildWidth = previewWidth * height / previewHeight;
                child.layout((width - scaledChildWidth) / 2, 0,
                        (width + scaledChildWidth) / 2, height);
            } else {
                final int scaledChildHeight = previewHeight * width / previewWidth;
                child.layout(0, (height - scaledChildHeight) / 2,
                        width, (height + scaledChildHeight) / 2);
            }
        }
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, acquire the camera and tell it where
        // to draw.
        try {
            if (mCamera != null) {
                mCamera.setPreviewDisplay(holder);
            }
        } catch (IOException exception) {
            Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // Surface will be destroyed when we return, so stop the preview.
        if (mCamera != null) {
            mCamera.stopPreview();
        }
    }


    private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
        final double ASPECT_TOLERANCE = 0.1;
        double targetRatio = (double) w / h;
        if (sizes == null) return null;
        Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        int targetHeight = h;

        // Try to find an size match aspect ratio and size
        for (Size size : sizes) {
            double ratio = (double) size.width / size.height;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }

        // Cannot find the one match the aspect ratio, ignore the requirement
        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Size size : sizes) {
                if (Math.abs(size.height - targetHeight) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }
        return optimalSize;
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        if(mCamera != null) {
            Camera.Parameters parameters = mCamera.getParameters();
            parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
            requestLayout();

            mCamera.setParameters(parameters);
            mCamera.startPreview();
        }
    }

}
麦克华莱士

我认为这更多是设计问题。您真的应该一次打开多个活动吗?

当一个活动开始时,它被放在历史堆栈的顶部,这可能给人以幻想它正在以相反的方式发生的幻觉。

但是,直到看到代码,我无法再发表评论。

更新:是的,设计问题。

这是它应该工作的方式:

  1. MainActivity中的Onclick操作仅应使用startActivityForResult()打开Preview活动。
  2. 用户拍照,触发setResult()并关闭相机活动。
  3. 结果返回到MainActivity,触发onActivityResult()
  4. onActivityResult中的代码启动ImagePreview活动。
  5. ImagePreview中的onCreate函数触发doCrop();

我建议您在这里阅读一下Android文档,网址为http : //developer.android.com/guide/components/activities.html

与其他平台相比,Android的灵活性较差(或更有用),因此必须对API有足够的了解。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

延迟然后执行任务

来自分类Dev

依次执行任务序列

来自分类Dev

Gulp监视-按顺序执行任务(同步)

来自分类Dev

让异步等待并执行任务

来自分类Dev

是否有必要在Hadoop DataNode上执行任务?

来自分类Dev

Android Studio执行失败,无法执行任务compilefreeDebugKotlin

来自分类Dev

Android-无法执行任务:任务已经执行

来自分类Dev

错误:-在Android Studio中执行任务':app:dexDebug'失败

来自分类Dev

Gradle:执行任务失败

来自分类Dev

在Android Studio上执行任务':app:dexDebug'执行失败

来自分类Dev

如何使用Google App Engine任务队列按(FIFO)顺序执行任务?

来自分类Dev

并行执行任务

来自分类Dev

SimGrid:如何检查主机是否正在执行任务?

来自分类Dev

AsyncTask android异常(无法执行任务:该任务已经执行)

来自分类Dev

是否可以在Namenode上执行任务?

来自分类Dev

快速合并-按给定顺序执行任务

来自分类Dev

Android Volley:在图像加载后执行任务

来自分类Dev

定期执行任务

来自分类Dev

如何在多个线程中执行任务比在主线程上顺序执行慢100倍?

来自分类Dev

是否有必要在Hadoop DataNode上执行任务?

来自分类Dev

JBPM多次执行任务

来自分类Dev

是否可以在Google App Engine任务队列中执行任务?

来自分类Dev

是否可以在Namenode上执行任务?

来自分类Dev

执行任务后绑定?

来自分类Dev

如何按顺序执行定时任务?

来自分类Dev

Android Studio 执行任务':app"dexDebug 失败

来自分类Dev

手动控制执行任务的顺序

来自分类Dev

是否可以从 doLast 中执行任务?

来自分类Dev

是否有一个普通的 Android SDK 动画器可以间隔执行任务?

Related 相关文章

热门标签

归档