OnActivityResult method is deprecated, what is the alternative?

前端 未结 5 560
情话喂你
情话喂你 2021-01-01 10:33

Recently I faced the onActivtyResult is deprecated. what should we do for handle it?

any alternative introduced for that?

5条回答
  •  春和景丽
    2021-01-01 11:01

    A basic training is available at developer.android.com.

    Here is an example on how to convert the existing code with the new one:

    The old way:

        public void openSomeActivityForResult() {
            Intent intent = new Intent(this, SomeActivity.class);
            startActivityForResult(intent, 123);
        }
    
        @Override
        protected void onActivityResult (int requestCode, int resultCode, Intent data) {
            if (resultCode == Activity.RESULT_OK && requestCode == 123) {
                doSomeOperations();
            }
        }
    

    The new way (Java):

        // You can do the assignment inside onAttach or onCreate, i.e, before the activity is displayed
        ActivityResultLauncher someActivityResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == Activity.RESULT_OK) {
                            // There are no request codes
                            Intent data = result.getData();
                            doSomeOperations();
                        }
                    }
                });
    
        public void openSomeActivityForResult() {
            Intent intent = new Intent(this, SomeActivity.class);
            someActivityResultLauncher.launch(intent);
        }
    

    The new way (Kotlin):

    var resultLauncher = registerForActivityResult(StartActivityForResult()) { result ->
        if (result.resultCode === Activity.RESULT_OK) {
            // There are no request codes
            val data: Intent? = result.data
            doSomeOperations()
        }
    }
    
    fun openSomeActivityForResult() {
        val intent = Intent(this, SomeActivity::class.java)
        resultLauncher.launch(intent)
    }
    

提交回复
热议问题