Android学习笔记(六)——深入Intent和Service
2011-03-16 16:01 shy.ang 阅读(1495) 评论(0) 编辑 收藏 举报深入Intent
Intent有三种形式:
startActivity(intent)
broadcast Intent机制可以将一个Intent发送给任何一个对这个Intent感兴趣的BroadcastReceiver
通过startService(intent)或者
bindService(intent,ServiceConnection,int)来和后台的Service进行交互
连接Activity有两种——或者指定一个Activity,或者只包含选定Activity的信息,但具体启动哪个由系统决定最满足条件的。
启动未指明的Activity:Intent intent = new
Intent(Intent.ACTION_DIAL,Uri.parse(“115-1345”));
Intent详细讲解
Intent对某操作的抽象描述包含有:
1. 对执行动作的描述:Action
2. 对相关数据的描述:data
3. 数据类型:type
4. 执行动作的附加信息:category
5. 其他一切附加信息:extras
6. 目标组件:component
Android系统自带的Action有:
ACTION_MAIN:标记当前Activity作为一个程序的入口
在AndroidManifest.xml中”android.intent.action.MAIN”
ACTION_VIEW:将数据显示给用户,通常和特定的data相配合
ACTION_DIAL:描述用户打电话的动作,和data配合使用将会触发特定
data的用户打电话
ACTION_PICK:从特定一组数据中进行选择数据操作
与Action相关联的data:
Android采用指向数据的一个URI来表示data,通过ContentURI这个类来描述,具体参考android.net.ContentURI类的文档
如以下action/data对:
VIEW_ACTION content://contacts/1
EDIT_ACTION content://contacts/1
VIEW_ACTION content://contacts/
Android解析Intent
Android需要解析的是间接Intent(没有指定component属性的Intent)
通过解析,将Intent映射给可以处理此Intent的Activity、Receiver或Service。Intent解析机制主要通过查找已注册在AndroidManifest.xml中的所有IntentFilter及其中定义的Intent,最终找到匹配的Intent。
解析通过Intent的action、type、category这3个属性来进行判断:
1. 若指明action,则目标组件的IntentFilter的action列表必须包含这个action否则不匹配
2. 若没提供type,则从data中得到数据类型,同上,目标组件的数据类型列表必须包含Intent的数据类型,否则不匹配
3. 若Intent中的数据不是具体内容而是URI形式的话,则将根据Intent中数据的scheme(如http:或者mailto:)进行匹配
4. 如果指定了一个或多个category,这些类别必须都出现在组件的类别列表中。
比如<activity android:name=”.Activity_Auth”
Android:label=”@string/app_name”>
<intent-filter>
<action android:name=”android.intent.action.VIEW”/>
<category android:name=
”android.intent.category.DEFAULT”/>
<category android:name=
“android.intent.category.BROWSABLE”/>
<data android:scheme= “shy” />
</intent-filter>
</activity>
此Activity动作是”...VIEW”,类型表示可以通过浏览器启动,而这里定义了匹配模式为scheme=”shy”,说明当链接为”shy://”模式的时候触发这个activity
通过Intent广播事件
程序主动广播Intent比较简单:sendBroadcast(intent);
接收被广播的Intent,需要注册一个Broadcast Receiver,给它设置一个Intent Filter来过滤目标Intent:
继承BroadcastReceiver类,并重写类中的onReceive方法,在其中最好不
要执行超过5s的代码,以免系统弹出超时对话框,如果有耗时操作,建议写入线程单
独执行。
注册BroadcastReceiver:在AndroidManifest.xml中注册
<receiver android:name=”xx”>
<intent-filter>
<action android:name=”xxx.action.NEW_BROADCAST”/>
</intent-filter>
</receiver>
注销:unregisterReceiver(xxx);
Service
在后台运行,不可交互,不能自己运行,需要通过Activity或者其他Context对象来调用,有Context.startService()和Context.bindService()两种方式启动
不要在Service中作很耗时的动作,最好启动一个新线程来运行这个Service,因为如果Service运行在主线程,会影响程序的UI操作或者堵塞主线程的其他事情。
使用Service时需要添加<Service android:enabled=”true”
android:name=”.xxx”/>来声明该服务即可。
Service的生命周期:onCreate、onStart、onDestroy
1. 通过startService启动Service
Service启动的时候会经历onCreate->onStart过程,Service停止时直接进入onDestroy,如果调用者直接退出而没有调用stopService,Service会一直后台运行。
2. 通过bindService
Service只会运行onCreate,这时将调用者和该Service绑定在一起,如果调用者退出,则Service就会调用onUnbind->onDestroyed,所谓绑定,就是共存亡。
Activity是应用的“眼睛”,其展示给用户,可以用来交互;而BroadcastReceiver是“耳朵”,接收发生的Intent;Service相当于“手”,把事情做完
//为什么Activity不直接跳转到欲启动的Service,而由
BroadcastReceiver在中间? 可以直接跳转!