Android应用开发之intent速查笔记

date: 2016.08.30; modification:2016.08.30

目录:

1 intent启动activity

1.1 基本使用


    // 在 MainActivity 启动 TestIntentActivity
    Intent intent = new Intent(MainActivity.this, TestIntentActivity.class);
    startActivity(intent);

1.2 添加简单参数

发送的activity中:


    Intent intent = new Intent(MainActivity.this, TestIntentActivity.class);

    intent.putExtra("name", "Mike");
    intent.putExtra("age", 32);
    startActivity(intent);

接收的activity中(在被启动的onCreate中):


    Intent intent = getIntent();

    String name = intent.getStringExtra("name");
    int age     = intent.getIntExtra("age", 0);

1.3 添加bundle参数

发送的activity中:


    Intent intent = new Intent(MainActivity.this, TestIntentActivity.class);

    Bundle bundle = new Bundle();
    bundle.putString("sex", "Male");
    intent.putExtra("bundle", bundle);
    startActivity(intent);

接收的activity中(在被启动的onCreate中):


    Intent intent = getIntent();

    Bundle bundle = intent.getBundleExtra("bundle");
    String sex = bundle.getString("sex");

1.4 带返回值的启动activity

有时候, 新启动activity运行后, 当它返回后, 需要它返回给原activity. 此时, 需要将 startActivity 改为 startActivityForResult:

发送的activity中:

    
    // 在 MainActivity 启动 TestIntentActivity
    Intent intent = new Intent(MainActivity.this, TestIntentActivity.class);
    intent.putExtra("age", 32);
    // 这里的1000为requestCode, 随便设置, 可以递增, 表示请求码, 该码会在onActivityResult时原样返回, 用来区分是那一次请求对应的返回值.
    startActivityForResult(intent, 1000);

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 这里的requestCode即上面设置的1000. resultCode为新activity的返回值. data为附加intent信息, 如果新activity不添加该值, 则为null.
        Log.d("TAG", "onActivityResult. requestCode = " + requestCode + ", resultCode = " + resultCode + ", data: " + data);
        if (data != null) {
            int ageNextYear = data.getIntExtra("ageNextYear", 0);
            Log.d("TAG", "ageNextYear = " + ageNextYear);
        }
    }

这里将age设置为32, 在新启动的TestIntentActivity中会将其+1并通过intent传回来, data中收到的数据即为33.

接收的activity中, 返回时加入:


    Intent requestIntent = getIntent();
    int age = requestIntent.getIntExtra("age", 0);

    Intent resultIntent = new Intent();
    resultIntent.putExtra("ageNextYear", age + 1);
    setResult(Activity.RESULT_OK, resultIntent); // Activity.RESULT_OK可以设置为随意值, 该值即为返回给原activity的resultCode.