简体   繁体   中英

Android - how safe is calling startActivityForResult within onActivityResult?

I am designing an app which calls one of a number of child activities based on the return value of a previously called activity. For example, activity A might lead to B or C, and B might lead to A, B again, or D.

The obvious way is for a child activity to set a value indicating the next child activity to call, which is passed back to the parent, then, in the parent's onActivityReturn method, call another child activity with startActivityForResult based on that value. I am assuming that startActivityForResult is asynchronous, so the onActivityReturn method would, or at least can, continue (and finish) before the child activity returns.

Is this necessarily safe? What happens if, somehow, the called activity returns before the onActivityReturn that called it finishes?

如果您的流程受到适当条件的控制,则不会产生任何问题,即使是出于安全考虑,您也可以通过定义以下内容来创建单个实例

android:launchMode="singleInstance"

you can also finish(destroy) any child before send to parent

also you can :

android:launchMode="singleInstance"

Actually, you should predict the situation if there are no such apps that can accept your intent, so if there are no such apps your app will crash. Take a look at this example:

    // Actions for change cover button
    Button setImageButton = (Button)   rootView.findViewById(R.id.set_image_button);

    setImageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);

            ComponentName activity = photoPickerIntent.resolveActivity(getActivity().getPackageManager());
            photoPickerIntent.setType("image/*");

            if (activity != null) {
                startActivityForResult(photoPickerIntent, SELECT_PHOTO);
            } else {
                Toast.makeText(getActivity().getBaseContext(), "There are no activities for such intent",
                        Toast.LENGTH_SHORT).show();
            }
        }
    });

So with help of ComponentName activity = photoPickerIntent.resolveActivity(getActivity().getPackageManager()); you can check that everything is ok.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM