开始一项活动

这个例子将从 OriginActivity 开始 DestinationActivity

这里,Intent 构造函数有两个参数:

  1. Context 作为其第一个参数(因为 Activity 类是 Context 的子类,所以使用它)
  2. 系统应向其传递 Intent 的应用程序组件的类(在本例中,应该启动的活动)
public class OriginActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_origin);

        Intent intent = new Intent(this, DestinationActivity.class);
        
        startActivity(intent);
        finish(); // Optionally, you can close OriginActivity. In this way when the user press back from DestinationActivity he/she won't land on OriginActivity again.
    }
}

创建 Intent 以打开 DestinationActivity 的另一种方法是使用 Intent 的默认构造函数,并使用 setClass() 方法告诉它打开哪个 Activity:

Intent i=new Intent();
i.setClass(this, DestinationActivity.class);
startActivity(intent);
finish(); // Optionally, you can close OriginActivity. In this way when the user press back from DestinationActivity he/she won't land on OriginActivity