java - 如何在单个 Activity 中添加多个 onActivityResult() 而不转到其他 Activity?

标签 java android android-studio android-camera onactivityresult

我在单个 Activity 中同时使用 ImagePicker 和条形码读取器。主要问题是这两个都需要 onActivityResult() 来显示结果。众所周知,单个 Activity 只能有一个 onActivityResult() 方法。我怎样才能同时显示它们?

我尝试使用 switch case 在 onActivityResult() 中分配多个 requestCode,但似乎无法找出解决方案。

这是我尝试过的方法。

public class MainActivity extends AppCompatActivity{

private TextView mIdentificationNumber;
private IntentIntegrator scanQR;

//Authentication For Firebase.
private FirebaseAuth mAuth;

//Toolbar
private Toolbar mToolBar;

private DatabaseReference mUserRef;

private ImageView mAssetImg;
private EditText massetName, massetModel, massetBarcode, massetArea, massetDescription;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Getting the Present instance of the FireBase Authentication
    mAuth = FirebaseAuth.getInstance();

    //Finding The Toolbar with it's unique Id.
    mToolBar = (Toolbar) findViewById(R.id.main_page_toolbar);

    //Setting Up the ToolBar in The ActionBar.
    setSupportActionBar(mToolBar);

    if (mAuth.getCurrentUser() != null){

        mUserRef = FirebaseDatabase.getInstance().getReference().child("Users")
                .child(mAuth.getCurrentUser().getUid());
        mUserRef.keepSynced(true);

    }

    massetBarcode = (EditText) findViewById(R.id.BarcodeAsset);
    scanQR = new IntentIntegrator(this);
    massetBarcode.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            scanQR.initiateScan();

        }
    });

    mAssetImg = (ImageView) findViewById(R.id.asset_img);
    mAssetImg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            getImage();
        }
    });

}

//OnStart Method is started when the Authentication Starts.
@Override
public void onStart() {
    super.onStart();
    // Check if user is signed in (non-null).
    FirebaseUser currentUser = mAuth.getCurrentUser();

    if (currentUser == null){

        startUser();

    } else {

        mUserRef.child("online").setValue("true");
        Log.d("STARTING THE ACTIVITY" , "TRUE");

    }
}

@Override
protected void onPause() {
    super.onPause();

    FirebaseUser currentUser = mAuth.getCurrentUser();

    if (currentUser != null){

        mUserRef.child("online").setValue(ServerValue.TIMESTAMP);
        Log.d("STOPPING THE ACTIVITY" , "TRUE");

    }

}

private void startUser() {

    //Sending the user in the StartActivity If the User Is Not Logged In.
    Intent startIntent = new Intent(MainActivity.this , AuthenticationActivity.class);
    startActivity(startIntent);
    //Finishing Up The Intent So the User Can't Go Back To MainActivity Without LoggingIn.
    finish();

}

//Setting The Menu Options In The AppBarLayout.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    //Inflating the Menu with the Unique R.menu.Id.
    getMenuInflater().inflate(R.menu.main_menu , menu);

    return true;
}

//Setting the Individual Item In The Menu.(Logout Button)
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);

    if (item.getItemId() == R.id.main_logout_btn){

        FirebaseAuth.getInstance().signOut();
        startUser();

    }

    return true;
}

private void getImage() {

    ImagePicker.Companion.with(this)
            .crop()                 //Crop image(Optional), Check Customization for more option
            .compress(1024)         //Final image size will be less than 1 MB(Optional)
            .maxResultSize(1080, 1080)  //Final image resolution will be less than 1080 x 1080(Optional)
            .start();

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case 0:
            IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (result != null) {
                if (result.getContents() == null) {
                    Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
                } else {

                    massetBarcode.setText(result.getContents());

                    Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
                }
            }
            break;

        case 1:
            if (resultCode == Activity.RESULT_OK) {

                assert data != null;
                Uri imageURI = data.getData();
                mAssetImg.setImageURI(imageURI);

            }
            break;
    }

}

}

其余答案告诉我们使用 startActivityForResult(),但该方法需要 Intent 从一个 Activity 转到另一个 Activity ,但我不想这样做。

最佳答案

在这两种情况下,您使用的库都提供了一种指定请求代码的方法,以便您可以区分 onActivityResult 中的结果。

您的 scanQR 对象应设置请求代码 per the source code:

massetBarcode.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        scanQR.setRequestCode(123).initiateScan();
    }
});

您的 getImage() 方法还应该指定一个请求代码,同样是 per the library's source code

private void getImage() {
    ImagePicker.Companion.with(this)
        .crop()                 //Crop image(Optional), Check Customization for more option
        .compress(1024)         //Final image size will be less than 1 MB(Optional)
        .maxResultSize(1080, 1080)  //Final image resolution will be less than 1080 x 1080(Optional)
        .start(456); // Start with request code
}

现在,您可以根据需要处理每个请求代码:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case 123:
            // HANDLE BARCODE
            break;

        case 456:
            // HANDLE IMAGE
            break;
    }
}

结束语:我从未使用过这两个库。我找到了解决方案:1)假设任何提供您应该为结果调用的 Activity 的库将允许您为其指定请求代码,2)查看他们的文档和源代码以了解如何做到这一点。

我鼓励您彻底研究您打算使用的任何开源库的文档和源代码,因为一旦您这样做,他们的代码就会成为您的代码,他们的错误也会成为您的错误,所以您更好地知道如何修复或解决它们。

希望有帮助!

关于java - 如何在单个 Activity 中添加多个 onActivityResult() 而不转到其他 Activity?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59811008/

相关文章:

android - 不支持 loadContainerPreferNonDefault JSONArray 的 Google 跟踪代码管理器错误

java - 如何部署和运行表盘服务

java - 如何在lucene中使用tf idf相似度对文档进行排名

java - 在 NativeScript 中使用 Android 原生代码 (JAVA)

java - 从数据库获取日期并在 Java 中进行比较

java - Appium 选择了错误的定位器

android - isDialog() 与 Espresso 中的对话框 fragment 不匹配

java - 每次执行辅助类时代码都会崩溃

java - 为什么它说 "Cannot refer to a non-final variable i inside an inner class defined in a different method"?

java - 为什么事件在我的小程序中不起作用? (它们在原始应用程序中工作)