其他分享
首页 > 其他分享> > android – 如何使用Intent启动活动并在新活动中传递变量?

android – 如何使用Intent启动活动并在新活动中传递变量?

作者:互联网

所以现在我在我的应用程序中使用zxing条形码扫描仪.这是示例代码(通用):

if(position == 0){
            Intent intent = new Intent("com.google.zxing.client.android.SCAN");
            intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
            startActivityForResult(intent, 0);


        }

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 0) {
            if (resultCode == RESULT_OK) {
                contents = intent.getStringExtra("SCAN_RESULT");
                format = intent.getStringExtra("SCAN_RESULT_FORMAT");
                // Handle successful scan
                Intent i = new Intent(Main.this, BarcodeScanner.class);
                startActivity(i);
            } else if (resultCode == RESULT_CANCELED) {
                // Handle cancel
            }
        }
    }

因此,在启动BarcodeScanner.class时,我还想将内容传递给它.我该怎么做呢?

解决方法:

使用Bundle内部意图将数据从一个活动传递到另一个活动.在你的情况下,你必须做类似的事情 –

        Intent intent = new Intent(Main.this,BarcodeScanner.class);

        //load the intent with a key "content" and assign it's value to content            
        intent.putExtra("content",contents);

        //launch the BarcodeScanner activity and send the intent along with it
        //note that content  is passed in as well             
        startActivity(intent);

信息存储在Intent内部的“Bundle”对象中 – 当您调用Intent对象的putExtras()方法时会创建Bundle

标签:barcode-scanner,android,zxing
来源: https://codeday.me/bug/20190730/1580975.html