Intent 是 Android 中用于在组件之间传递信息的一种重要机制,它不仅可以启动组件(如 Activity、Service、BroadcastReceiver),还可以进行数据传递、启动其他应用等。以下是 Intent 的基本使用方式:

1. 创建和启动 Activity:
   - 通过 Intent 启动一个新的 Activity。
// 创建 Intent 对象
Intent intent = new Intent(this, SecondActivity.class);

// 启动新的 Activity
startActivity(intent);

2. 数据传递:
   - 通过 Intent 在组件之间传递数据。
// 创建 Intent 对象,并传递数据
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("key", "Hello, Second Activity!");

// 启动新的 Activity
startActivity(intent);

在接收端的 Activity 中获取传递的数据:
// 在 onCreate 方法中获取传递的数据
Intent intent = getIntent();
String data = intent.getStringExtra("key");

3. 启动服务:
   - 通过 Intent 启动服务。
// 创建 Intent 对象,指定要启动的服务
Intent intent = new Intent(this, MyService.class);

// 启动服务
startService(intent);

4. Broadcast 发送:
   - 通过 Intent 发送广播。
// 创建 Intent 对象,指定广播的 action
Intent intent = new Intent("com.example.myapp.CUSTOM_ACTION");

// 发送广播
sendBroadcast(intent);

5. 隐式 Intent 启动其他应用程序的 Activity:
   - 使用隐式 Intent 启动其他应用程序中声明的 Activity。
// 创建 Intent 对象,指定要执行的操作和数据
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.example.com"));

// 启动其他应用程序中的 Activity
startActivity(intent);

6. 指定 Component 启动:
   - 明确指定要启动的组件。
// 创建 Intent 对象,指定要启动的组件
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example.otherapp", "com.example.otherapp.MainActivity"));

// 启动指定组件
startActivity(intent);

7. 传递 Parcelable 对象:
   - 通过 Intent 传递自定义对象,对象需要实现 Parcelable 接口。
// 创建 Intent 对象,并传递 Parcelable 对象
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("user", myUserParcelable);

// 启动新的 Activity
startActivity(intent);

在接收端的 Activity 中获取传递的 Parcelable 对象:
// 在 onCreate 方法中获取传递的 Parcelable 对象
Intent intent = getIntent();
MyUserParcelable user = intent.getParcelableExtra("user");

以上是 Intent 的一些基本使用方式。Intent 是 Android 中实现组件间通信和操作的关键手段之一,了解其基本用法对 Android 开发至关重要。


转载请注明出处:http://www.pingtaimeng.com/article/detail/15179/Android