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

时间:2010-10-30 21:32:04

标签: android barcode-scanner zxing

所以现在我在我的应用程序中使用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时,我还想将contents传递给它。我该怎么做呢?

2 个答案:

答案 0 :(得分:6)

在意图内使用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

答案 1 :(得分:1)

"SCAN_MODE"传递给其他活动的方式与调用putExtra("some key", contents)前调用startActivity(),然后调用this.getIntent().getStringExtra("some key")

内部相同