提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
一、Intent是什么?
Android Intent是一种用于在应用程序及其组件之间进行通信的机制。它允许应用程序启动其他应用程序的活动或服务,并在应用程序及其组件之间传递数据。Intent可以被用于启动Activity、Service、Broadcast Receiver或者隐式地启动一个由其它应用程序(或者系统)提供的组件。通过使用Intent,可以轻松实现应用程序之间的无缝集成,这使得Android应用程序开发变得更加灵活。。
二、使用步骤
1. 显式intent(用于跳转到本应用的其他页面)
代码如下(示例):
主要代码展示(如果需要完整代码可以到我的github上地址在后面)
Intent intent3 = new Intent(MainActivity.this,MainActivity2.class);
startActivity(intent3);
展示:
点击本应用跳转会弹到如下页面
2.隐式跳转之本应用跳转
代码如下(示例):
Intent intent = new Intent();
// 注意这是在其他应用AndroidManifest.xml文件中自定义的一个名
intent.setAction("android.intent.action.NING");
// 通过添加Intent.CATEGORY_DEFAULT类别,可以确保该Intent能够被系统匹配到最适合的组件来处理
intent.addCategory(Intent.CATEGORY_DEFAULT);
startActivity(intent);
点击: 其他个人页面(表示你自己建立的android程序)
会产生一个弹出框是由于我的两个应用使用了如下配置(位于AndroidManifest.xml)文件
注意:这个地方要为true
android:exported="true"
且在你要跳转的app这个文件AndroidManifest.xml添加
android.intent.action.NING
这里的NING可以自定义
<intent-filter>
<action android:name="android.intent.action.NING" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
3.隐式跳转之系统应用跳转
//隐式跳转(到拨号页面)
Intent intent1 = new Intent();
// 使用该代码后,当这个意图被启动时,会自动打开手机拨号界面并填充指定的电话号码,用户可以直接点击拨号按钮呼叫该号码
intent1.setAction(Intent.ACTION_DIAL);
Uri uri = Uri.parse("tel:"+phoneNum);
intent1.setData(uri);
startActivity(intent1);
跳转拨号页面这里不在展示
//隐式跳转(到短信页面)
Intent intent2 = new Intent();
// 使用该代码后,当这个意图被启动时,会打开短信页面
intent2.setAction(Intent.ACTION_SENDTO);
Uri uri2 = Uri.parse("sms:"+phoneNum);
intent2.setData(uri2);
startActivity(intent2);
-
如果要跳到其他系统软件可以参考官方文档.
android官方文档
总结
Android Intent是一种重要的消息传递机制,可用于在应用程序之间进行通信。以下是一些intent的基础知识总结:
- Intent 可以分为显式 Intent 和隐式 Intent。显式 Intent 明确指定要启动的 Activity,而隐式 Intent 只指定 Action、Category、Data 等元素,由系统匹配合适的 Activity。
- Intent 可以传递数据,使用 putExtra() 方法添加键值对即可。数据类型可以是基本类型、字符串、Parcelable 对象等。
- Intent 还可以启动服务和发送广播。启动服务时,需要使用 startService() 方法,并指定服务的类名;发送广播时,需要指定 Action 并创建 Intent 对象,然后使用 sendBroadcast() 方法发送。
- Intent 还可以进行跨应用程序的通信。在发送 Intent 时,应指定目标应用程序的包名和类名,或者使用隐式 Intent。
- 如果有多个 Activity 响应同一个 Intent,系统会弹出一个选择器,让用户选择启动哪个 Activity。
总之,Intent 提供了一种非常灵活的应用程序间通信机制,为 Android 应用程序的开发带来了很大的便利性。