Intent的使用

利用Intent进行Activity之间的跳转有两种方式

  • 一种是显式Intent,直接在Java代码进行书写
  • 另外一种则是隐式Intent,需要配合AndroidManifest.xml文件实现

下面是截至API23版本前,Google官方文档中的Intent构造函数介绍:

构造函数 作用
Intent() Create an empty intent.
Intent(Intent intent) Copy constructor.
Intent(String action) Create an intent with a given action.
Intent(String action, Uri uri) Create an intent with a given action and for a given data url.
Intent(Context packageContext, Class<?> cls) Create an intent for a specific component.
Intent(String action, Uri uri, Context packageContext, Class<?> cls) Create an intent for a specific component with a specified action and data.

显式Intent的使用

首先新建两个Activity的Java文件,分别为FirstActivity.class和SecondActivity.class,然后新建两个对应的xml文件分别为activity_first.xml和activity.second.xml。在第一个页面创建一个Button,为点击跳转做准备。第二个页面则放置一个TextView。然后在FirstActivity.class中引入Button按钮并设置监听。

代码如下:

public class FirstActivity extends AppCompatActivity {

    private Button btn_first;

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

        btn_first = (Button) findViewById(R.id.btn_first);
        btn_first.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) { 
            }
        });
    }
}

接下来实例化一个Intent类,并在构造函数的第一个参数中传入程序的context,在这里是FirstActivity.this,第二个参数则是需要跳转的Activity类。然后直接调用startActivity(intent)方法进行跳转。

代码如下:

	@Override
	public void onClick(View v) {
		Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
		startActivity(intent);
	}

然后就可以点击按钮进行跳转了。

隐式Intent的使用

对于隐式Intent来说,则需要制定action,category等信息,然后通过系统查找合适的Activity去启动。

首先在AndroidManifest.xml文件中配置需要的目标Activity的数据。

        <activity android:name=".SecondActivity">
            <intent-filter>
                <action android:name="com.chao.intenttest.START_ACTIVITY" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="com.chao.intenttest.CATEGORY_TEST" />
            </intent-filter>
        </activity>

接着修改btn_first的监听器的匿名内部类内容。

            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.chao.intenttest.START_ACTIVITY");
                intent.addCategory("com.chao.intenttest.CATEGORY_TEST");
                startActivity(intent);
            }

然后就可以点击按钮进行跳转了。在这里的action的内容和category的内容都是可以自定义的。

注意:这里一定要加上默认的<category android:name="android.intent.category.DEFAULT" />,不然会报android.content.ActivityNotFoundException错误,因为这是系统的默认category。

传送数据

想要在Activity之间传送数据,只需要将数据存储在Intent中即可。

但是传送数据分为两种,一种是直接传送数据不需要回调,另外一种则是传送出去后需要回应的数据。

无回调传送

首先重新设计页面。

FirstActivity.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="chao.com.intenttest.FirstActivity">

    <EditText
        android:id="@+id/et_transMsg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btn_first"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TransMsg"/>

</LinearLayout>

SecondActivity:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_showMsg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

然后书写传送界面的代码,首先跟原来一样实例化一个Intent类,然后将数据放入其中,在这里我的数据是获取EditText控件的输入内容。

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

        btn_first = (Button) findViewById(R.id.btn_first);
        et_transMsg = (EditText) findViewById(R.id.et_transMsg);
        btn_first.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
                intent.putExtra("msg", et_transMsg.getText().toString());
                startActivity(intent);
            }
        });
    }

然后在第二个页面利用getIntent()方法获取传送来的intent,然后获取内容进行显示。

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        tv_showMsg = (TextView) findViewById(R.id.tv_showMsg);
        Intent intent = getIntent();
        tv_showMsg.setText(intent.getStringExtra("msg"));
    }

有回调传送

若需要在跳转之后返回数据,则需要重写onActivityResult()方法来获取第二个页面传回来的数据,而在第二个页面,需要使用setResult()方法来将数据传送回来,同时使用finish()方法结束本页面。

下面是两个界面文件:

FirstActivity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="chao.com.intenttest.FirstActivity">

    <TextView
        android:id="@+id/tv_getMsg"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:textAlignment="center"/>

    <Button
        android:id="@+id/btn_first"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TransMsg"/>

</LinearLayout>


SecondActivity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="chao.com.intenttest.SecondActivity">

    <EditText
        android:id="@+id/et_rtnMsg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

   <Button
       android:id="@+id/btn_rtnMsg"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Return Message"/>

</LinearLayout>

FirstActivity代码:

public class FirstActivity extends AppCompatActivity {

    private Button btn_first;
    private TextView tv_showMsg;
    private static int SENDMSG = 1;

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

        btn_first = (Button) findViewById(R.id.btn_first);
        tv_showMsg = (TextView) findViewById(R.id.tv_getMsg);
        btn_first.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
                startActivityForResult(intent, SENDMSG);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == SENDMSG && resultCode == RESULT_OK) {
            tv_showMsg.setText(data.getStringExtra("rtnMsg"));
        }
    }
}

SecondActivity代码:

public class SecondActivity extends Activity{

    private EditText et_rtnMsg;
    private Button btn_rtnMsg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        et_rtnMsg = (EditText) findViewById(R.id.et_rtnMsg);
        btn_rtnMsg = (Button) findViewById(R.id.btn_rtnMsg);
        btn_rtnMsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("rtnMsg", et_rtnMsg.getText().toString());
                setResult(RESULT_OK, intent);
                finish();
            }
        });
    }
}