What is the meaning of requestCode in startActivityForResult

后端 未结 4 1794
不知归路
不知归路 2021-01-30 16:21

I\'m wondering if I am understanding the concepts of requestCode correectly. What is this integer for and does it matter what integer I set it to in:

         


        
4条回答
  •  你的背包
    2021-01-30 16:50

    The requestCode helps you to identify from which Intent you came back. For example, imagine your Activity A (Main Activity) could call Activity B (Camera Request), Activity C (Audio Recording), Activity D (Select a Contact).

    Whenever the subsequently called activities B, C or D finish and need to pass data back to A, now you need to identify in your onActivityResult from which Activity you are returning from and put your handling logic accordingly.

    
    
        public static final int CAMERA_REQUEST = 1;
        public static final int CONTACT_VIEW = 2;
    
        @Override
        public void onCreate(Bundle savedState)
        {
            super.onCreate(savedState);
            // For CameraRequest you would most likely do
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_REQUEST);
    
            // For ContactReqeuest you would most likely do
            Intent contactIntent = new Intent(ACTION_VIEW, Uri.parse("content://contacts/people/1"));
            startActivityForResult(contactIntent, CONTACT_VIEW);
        }
    
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data)
        {
            if (resultCode == Activity.RESULT_CANCELED) {
                // code to handle cancelled state
            }
            else if (requestCode == CAMERA_REQUEST) {
                // code to handle data from CAMERA_REQUEST
            }
            else if (requestCode == CONTACT_VIEW) {
                // code to handle data from CONTACT_VIEW
            }
        }
    
    
    

    I hope this clarifies the use of the parameter.

提交回复
热议问题