1.intent介绍
Intent 是一个消息传递对象,主要用于组件之间的通讯,基本作用主要有三个:
启动activity:startActivity,startActivityForResult
启动服务:startService,bindService
发送广播:sendBroadCast,sendOrderedBroadCast,sendStickyBroadCast
2.intent类型
显式intent:明确指定要启动的组件名称,一般通过setClass,setClassName,setComponent去指定。例如:开发中常用的就是显式intent。
显式intent示例:
Intent downloadIntent = new Intent(this, DownloadService.class);
downloadIntent.setData(Uri.parse
(fileUrl));
startService(downloadIntent);
隐式intent:没有明确指定要启动的组件名称,而是声明要执行的操作,一帮通过setAction,setData,setType,setDataAndType,addCategory去声明。例如:调用系统相机。
隐式intent示例:
// Create the text message with a string
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);
sendIntent.setType("text/plain");
// Verify that the intent will resolve to an activity
if (sendIntent.resolveActivity(getPackageManager()) != null) {
startActivity(sendIntent);
}
隐式intent响应:activity通过设置intent-filter标签去响应;broadCastReciver可以通过设置intent-filter标签,也可以在 代码中设置intent-filter去响应;service一般通过显式intent去启动,通过隐式intent会有安全漏洞,因为为service没有可视化界面,用户不知道有哪些service会做出响应。
3.应用选择器
如果多个应用可以响应 Intent,且用户可能希望每次使用不同的应用,则应采用显式方式显示选择器对话框。
代码如下:
Intent sendIntent = new Intent(Intent.ACTION_SEND); ... // Always use string resources for UI text. // This says something like "Share this photo with" String title = getResources().getString(R.string.chooser_title); // Create intent to show the chooser dialog Intent chooser = Intent.createChooser(sendIntent, title); // Verify the original intent will resolve to at least one activity if (sendIntent.resolveActivity(getPackageManager()) != null) { startActivity(chooser); }
4.待定Intent(pedingIntent):
PendingIntent 的主要目的是授权外部应用使用包含的 Intent,就像是它从您应用本身的进程中执行的一样,主要用于通知点击事件。
PendingIntent实例获取:三种方式
PendingIntent.getActivity()
,适用于启动Activity
PendingIntent 的Intent
。PendingIntent.getService()
,适用于启动Service
的 PendingIntentIntent
。PendingIntent.getBroadcast()
,适用于启动BroadcastReceiver
的Intent
。