注:本文来自“友盟杯”,仅在此阅读,学习android
这个文章主要是讲Android开发的四大组件,本文主要分为sql
1、Activity详解
2、Service详解
3、Broadcast Receiver详解
4、Content Provider详解
外加一个重要组件 intent的详解。
1、Activity详解
Activty的生命周期的也就是它所在进程的生命周期。数据库
一个Activity的启动顺序:
onCreate()——>onStart()——>onResume()
当另外一个Activity启动时:
第一个Activity onPause()——>第二个Activity onCreate()——>onStart()——>onResume()
——>第一个Activity onStop()
当返回到第一个Activity时:
第二个Activity onPause() ——> 第一个Activity onRestart()——>onStart()——>onResume()
——>第二个Activity onStop()——>onDestroy()
一个Activity的销毁顺序:
(状况一)onPause()——><Process Killed>
(状况二)onPause()——>onStop()——><Process Killed>
(状况三)onPause()——>onStop()——>onDestroy()
每个活动( Activity )都处于某一个状态,对于开发者来讲,是没法控制其应用程序处于某一个状态的,这些均由系统来完成。
可是当一个活动的状态发生改变的时候,开发者能够经过调用 onXX() 的方法获取到相关的通知信息。
在实现 Activity 类的时候,经过覆盖( override )这些方法便可在你须要处理的时候来调用。app
1、 onCreate :当活动第一次启动的时候,触发该方法,能够在此时完成活动的初始化工做。
onCreate 方法有一个参数,该参数能够为空( null ),也能够是以前调用 onSaveInstanceState ()方法保存的状态信息。异步
Activity栈ide
一个应用程序的优先级是受最高优先级的Activity影响的。当决定某个应用程序是否要终结去释放资源,Android内存管理使用栈来决定基于Activity的应用程序的优先级。
Activity状态
通常认为Activity有如下四种状态:
活动的:当一个Activity在栈顶,它是可视的、有焦点、可接受用户输入的。Android试图尽最大可能保持它活动状态,杀死其它Activity来确保当前活动Activity有足够的资源可以使用。当另一个Activity被激活,这个将会被暂停。
暂停:在不少状况下,你的Activity可视可是它没有焦点,换句话说它被暂停了。有可能缘由是一个透明或者非全屏的Activity被激活。
当被暂停,一个Activity仍会当成活动状态,只不过是不能够接受用户输入。在极特殊的状况下,Android将会杀死一个暂停的Activity来为活动的Activity提供充足的资源。当一个Activity变为彻底隐藏,它将会变成中止。
中止:当一个Activity不是可视的,它“中止”了。这个Activity将仍然在内存中保存它全部的状态和会员信息。尽管如此,当其它地方须要内存时,它将是最有可能被释放资源的。当一个Activity中止后,一个很重要的步骤是要保存数据和当前UI状态。一旦一个Activity退出或关闭了,它将变为待用状态。
待用: 在一个Activity被杀死后和被装在前,它是待用状态的。待用Acitivity被移除Activity栈,而且须要在显示和可用以前从新启动它。
activity的四种加载模式
在android的多activity开发中,activity之间的跳转可能须要有多种方式,有时是普通的生成一个新实例,有时但愿跳转到原来某个activity实例,而不是生成大量的重复的activity。加载模式即是决定以哪一种方式启动一个跳转到原来某个Activity实例。
在android里,有4种activity的启动模式,分别为:
·standard: 标准模式,一调用startActivity()方法就会产生一个新的实例。
·singleTop: 若是已经有一个实例位于Activity栈的顶部时,就不产生新的实例,而只是调用Activity中的newInstance()方法。若是不位于栈顶,会产生一个新的实例。
·singleTask: 会在一个新的task中产生这个实例,之后每次调用都会使用这个,不会去产生新的实例了。
·singleInstance: 这个跟singleTask基本上是同样,只有一个区别:在这个模式下的Activity实例所处的task中,只能有这个activity实例,不能有其余的实例。
这些启动模式能够在功能清单文件AndroidManifest.xml中进行设置,中的launchMode属性。
相关的代码中也有一些标志可使用,好比咱们想只启用一个实例,则可使用 Intent.FLAG_ACTIVITY_REORDER_TO_FRONT 标志,这个标志表示:若是这个activity已经启动了,就不产生新的activity,而只是把这个activity实例加到栈顶来就能够了。函数
Intent intent = new Intent(ReorderFour.this, ReorderTwo.class); intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivity(intent);
Activity的加载模式受启动Activity的Intent对象中设置的Flag和manifest文件中Activity的元素的特性值交互控制。
下面是影响加载模式的一些特性
核心的Intent Flag有:学习
FLAG_ACTIVITY_NEW_TASK
FLAG_ACTIVITY_CLEAR_TOP
FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
FLAG_ACTIVITY_SINGLE_TOP
核心的特性有:ui
taskAffinity
launchMode
allowTaskReparenting
clearTaskOnLaunch
alwaysRetainTaskState
finishOnTaskLaunch
四种加载模式的区别
所属task的区别
通常状况下,“standard”和”singleTop”的activity的目标task,和收到的Intent的发送者在同一个task内,就至关于谁调用它,它就跟谁在同一个Task中。
除非Intent包括参数FLAG_ACTIVITY_NEW_TASK。若是提供了FLAG_ACTIVITY_NEW_TASK参数,会启动到别的task里。
“singleTask”和”singleInstance” 老是把要启动的activity做为一个task的根元素,他们不会被启动到一个其余task里。
是否容许多个实例
“standard”和”singleTop”能够被实例化屡次,而且是能够存在于不一样的task中;这种实例化时一个task能够包括一个activity的多个实例;
“singleTask”和”singleInstance”则限制只生成一个实例,而且是task的根元素。
singleTop 要求若是建立intent的时候栈顶已经有要建立的Activity的实例,则将intent发送给该实例,而不建立新的实例。
是否容许其它activity存在于本task内
“singleInstance”独占一个task,其它activity不能存在那个task里;
若是它启动了一个新的activity,无论新的activity的launch mode 如何,新的activity都将会到别的task里运行(如同加了FLAG_ACTIVITY_NEW_TASK参数)。
而另外三种模式,则能够和其它activity共存。
是否每次都生成新实例
“standard”对于每个启动Intent都会生成一个activity的新实例;
“singleTop”的activity若是在task的栈顶的话,则不生成新的该activity的实例,直接使用栈顶的实例,不然,生成该activity的实例。
好比:
如今task栈元素为A-B-C-D(D在栈顶),这时候给D发一个启动intent,若是D是 “standard”的,则生成D的一个新实例,栈变为A-B-C-D-D。
若是D是singleTop的话,则不会生产D的新实例,栈状态仍为A-B-C-D
若是这时候给B发Intent的话,无论B的launchmode是”standard” 仍是 “singleTop” ,都会生成B的新实例,栈状态变为A-B-C-D-B。
“singleInstance”是其所在栈的惟一activity,它会每次都被重用。
“singleTask” 若是在栈顶,则接受intent,不然,该intent会被丢弃,可是该task仍会回到前台。 当已经存在的activity实例处理新的intent时候,会调用onNewIntent()方法,若是收到intent生成一个activity实例,那么用户能够经过back键回到上一个状态;若是是已经存在的一个activity来处理这个intent的话,用户不能经过按back键返回到这以前的状态。
-----------------------------------
2、Service详解
service能够在和多场合的应用中使用,好比播放多媒体的时候用户启动了其余Activity这个时候程序要在后台继续播放,好比检测SD卡上文件的变化,再或者在后台记录你地理信息位置的改变等等,总之服务嘛,老是藏在后头的。
Service是在一段不定的时间运行在后台,不和用户交互应用组件。每一个Service必须在manifest中 经过<service>来声明。能够经过contect.startservice和contect.bindserverice来启动。
Service和其余的应用组件同样,运行在进程的主线程中。这就是说若是service须要不少耗时或者阻塞的操做,须要在其子线程中实现。
service的两种模式(startService()/bindService()不是彻底分离的):
this
本地服务 Local Service 用于应用程序内部。
它能够启动并运行,直至有人中止了它或它本身中止。在这种方式下,它以调用Context.startService()启动,而以调用Context.stopService()结束。它能够调用Service.stopSelf() 或 Service.stopSelfResult()来本身中止。不论调用了多少次startService()方法,你只须要调用一次stopService()来中止服务。
用于实现应用程序本身的一些耗时任务,好比查询升级信息,并不占用应用程序好比Activity所属线程,而是单开线程后台执行,这样用户体验比较好。
远程服务 Remote Service 用于android系统内部的应用程序之间。
它能够经过本身定义并暴露出来的接口进行程序操做。客户端创建一个到服务对象的链接,并经过那个链接来调用服务。链接以调用Context.bindService()方法创建,以调用 Context.unbindService()关闭。多个客户端能够绑定至同一个服务。若是服务此时尚未加载,bindService()会先加载它。
可被其余应用程序复用,好比天气预报服务,其余应用程序不须要再写这样的服务,调用已有的便可。
使用context.startService() 启动Service是会会经历:
context.startService() ->onCreate()- >onStart()->Service running
context.stopService() | ->onDestroy() ->Service stop
若是Service尚未运行,则android先调用onCreate()而后调用onStart();若是Service已经运行,则只调用onStart(),因此一个Service的onStart方法可能会重复调用屡次。
stopService的时候直接onDestroy,若是是调用者本身直接退出而没有调用stopService的话,Service会一直在后台运行。该Service的调用者再启动起来后能够经过stopService关闭Service。
因此调用startService的生命周期为:onCreate --> onStart(可屡次调用) --> onDestroy
使用使用context.bindService()启动Service会经历:
context.bindService()->onCreate()->onBind()->Service running
onUnbind() -> onDestroy() ->Service stop
onBind将返回给客户端一个IBind接口实例,IBind容许客户端回调服务的方法,好比获得Service运行的状态或其余操做。这个时候把调用者(Context,例如Activity)会和Service绑定在一块儿,Context退出了,Srevice就会调用onUnbind->onDestroy相应退出。
因此调用bindService的生命周期为:onCreate --> onBind(只一次,不可屡次绑定) --> onUnbind --> onDestory。
在Service每一次的开启关闭过程当中,只有onStart可被屡次调用(经过屡次startService调用),其余onCreate,onBind,onUnbind,onDestory在一个生命周期中只能被调用一次。
而启动service,根据onStartCommand的返回值不一样,有两个附加的模式:
1. START_STICKY 用于显示启动和中止service。
2. START_NOT_STICKY或START_REDELIVER_INTENT用于有命令须要处理时才运行的模式。
服务不能本身运行,须要经过调用Context.startService()或Context.bindService()方法启动服务。这两个方法均可以启动Service,可是它们的使用场合有所不一样。
1. 使用startService()方法启用服务,调用者与服务之间没有关连,即便调用者退出了,服务仍然运行。
若是打算采用Context.startService()方法启动服务,在服务未被建立时,系统会先调用服务的onCreate()方法,接着调用onStart()方法。
若是调用startService()方法前服务已经被建立,屡次调用startService()方法并不会致使屡次建立服务,但会致使屡次调用onStart()方法。
采用startService()方法启动的服务,只能调用Context.stopService()方法结束服务,服务结束时会调用onDestroy()方法。
2. 使用bindService()方法启用服务,调用者与服务绑定在了一块儿,调用者一旦退出,服务也就终止,大有“不求同时生,必须同时死”的特色。
onBind()只有采用Context.bindService()方法启动服务时才会回调该方法。该方法在调用者与服务绑定时被调用,当调用者与服务已经绑定,屡次调用Context.bindService()方法并不会致使该方法被屡次调用。
采用Context.bindService()方法启动服务时只能调用onUnbind()方法解除调用者与服务解除,服务结束时会调用onDestroy()方法。
看看官方给出的比较流程示意图:
官方文档告诉咱们,一个service能够同时start而且bind,在这样的状况,系统会一直保持service的运行状态若是service已经start了或者BIND_AUTO_CREATE标志被设置。若是没有一个条件知足,那么系统将会调用onDestory方法来终止service.全部的清理工做(终止线程,反注册接收器)都在onDestory中完成。
拥有service的进程具备较高的优先级
官方文档告诉咱们,Android系统会尽可能保持拥有service的进程运行,只要在该service已经被启动(start)或者客户端链接(bindService)到它。当内存不足时,须要保持,拥有service的进程具备较高的优先级。
1. 若是service正在调用onCreate,onStartCommand或者onDestory方法,那么用于当前service的进程则变为前台进程以免被killed。
2. 若是当前service已经被启动(start),拥有它的进程则比那些用户可见的进程优先级低一些,可是比那些不可见的进程更重要,这就意味着service通常不会被killed.
3. 若是客户端已经链接到service (bindService),那么拥有Service的进程则拥有最高的优先级,能够认为service是可见的。
4. 若是service可使用startForeground(int, Notification)方法来将service设置为前台状态,那么系统就认为是对用户可见的,并不会在内存不足时killed。
若是有其余的应用组件做为Service,Activity等运行在相同的进程中,那么将会增长该进程的重要性。
本地service
1.不需和Activity交互的本地服务
public class LocalService extends Service { private static final String TAG = "LocalService"; @Override public IBinder onBind(Intent intent) { Log.i(TAG, "onBind"); return null; } @Override public void onCreate() { Log.i(TAG, "onCreate"); super.onCreate(); } @Override public void onDestroy() { Log.i(TAG, "onDestroy"); super.onDestroy(); } @Override public void onStart(Intent intent, int startId) { Log.i(TAG, "onStart"); super.onStart(intent, startId); } }
Activity:
public class ServiceActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.servicedemo); ((Button) findViewById(R.id.startLocalService)).setOnClickListener( new View.OnClickListener(){ @Override public void onClick(View view) { // TODO Auto-generated method stub startService(new Intent("com.demo.SERVICE_DEMO")); } }); ((Button) findViewById(R.id.stopLocalService)).setOnClickListener( new View.OnClickListener(){ @Override public void onClick(View view) { // TODO Auto-generated method stub stopService(new Intent("com.demo.SERVICE_DEMO")); } }); } }
在AndroidManifest.xml添加:
<service android:name=".LocalService"> <intent-filter> <action android:name="com.demo.SERVICE_DEMO" /> <category android:name="android.intent.category.default" /> </intent-filter> </service>
不然启动服务时会提示new Intent找不到"com.demo.SERVICE_DEMO"。
对于这类不需和Activity交互的本地服务,是使用startService/stopService的最好例子。
运行时能够发现第一次startService时,会调用onCreate和onStart,在没有stopService前,不管点击多少次startService,都只会调用onStart。而stopService时调用onDestroy。再次点击stopService,会发现不会进入service的生命周期的,即不会再调用onCreate,onStart和onDestroy。
而onBind在startService/stopService中没有调用。
2.本地服务和Activity交互
对于这种case,官方的sample(APIDemo\app.LocalService)是最好的例子:
/** * This is an example of implementing an application service that runs locally * in the same process as the application. The {@link LocalServiceController} * and {@link LocalServiceBinding} classes show how to interact with the * service. * * <p>Notice the use of the {@link NotificationManager} when interesting things * happen in the service. This is generally how background services should * interact with the user, rather than doing something more disruptive such as * calling startActivity(). */ public class LocalService extends Service { private NotificationManager mNM; /** * Class for clients to access. Because we know this service always * runs in the same process as its clients, we don't need to deal with * IPC. */ public class LocalBinder extends Binder { LocalService getService() { return LocalService.this; } } @Override public void onCreate() { mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); // Display a notification about us starting. We put an icon in the status bar. showNotification(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i("LocalService", "Received start id " + startId + ": " + intent); // We want this service to continue running until it is explicitly // stopped, so return sticky. return START_STICKY; } @Override public void onDestroy() { // Cancel the persistent notification. mNM.cancel(R.string.local_service_started); // Tell the user we stopped. Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show(); } @Override public IBinder onBind(Intent intent) { return mBinder; } // This is the object that receives interactions from clients. See // RemoteService for a more complete example. private final IBinder mBinder = new LocalBinder(); /** * Show a notification while this service is running. */ private void showNotification() { // In this sample, we'll use the same text for the ticker and the expanded notification CharSequence text = getText(R.string.local_service_started); // Set the icon, scrolling text and timestamp Notification notification = new Notification(R.drawable.stat_sample, text, System.currentTimeMillis()); // The PendingIntent to launch our activity if the user selects this notification PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, LocalServiceController.class), 0); // Set the info for the views that show in the notification panel. notification.setLatestEventInfo(this, getText(R.string.local_service_label), text, contentIntent); // Send the notification. // We use a layout id because it is a unique number. We use it later to cancel. mNM.notify(R.string.local_service_started, notification); } }
这里能够发现onBind须要返回一个IBinder对象。也就是说和上一例子LocalService不一样的是,
1. 添加了一个public内部类继承Binder,并添加getService方法来返回当前的Service对象;
2. 新建一个IBinder对象--new那个Binder内部类;
3. onBind方法返还那个IBinder对象。
Activity:
/** * <p>Example of binding and unbinding to the {@link LocalService}. * This demonstrates the implementation of a service which the client will * bind to, receiving an object through which it can communicate with the service.</p> */ public class LocalServiceBinding extends Activity { private boolean mIsBound; private LocalService mBoundService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.local_service_binding); // Watch for button clicks. Button button = (Button)findViewById(R.id.bind); button.setOnClickListener(mBindListener); button = (Button)findViewById(R.id.unbind); button.setOnClickListener(mUnbindListener); } private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { // This is called when the connection with the service has been // established, giving us the service object we can use to // interact with the service. Because we have bound to a explicit // service that we know is running in our own process, we can // cast its IBinder to a concrete class and directly access it. mBoundService = ((LocalService.LocalBinder)service).getService(); // Tell the user about this for our demo. Toast.makeText(LocalServiceBinding.this, R.string.local_service_connected, Toast.LENGTH_SHORT).show(); } public void onServiceDisconnected(ComponentName className) { // This is called when the connection with the service has been // unexpectedly disconnected -- that is, its process crashed. // Because it is running in our same process, we should never // see this happen. mBoundService = null; Toast.makeText(LocalServiceBinding.this, R.string.local_service_disconnected, Toast.LENGTH_SHORT).show(); } }; private OnClickListener mBindListener = new OnClickListener() { public void onClick(View v) { // Establish a connection with the service. We use an explicit // class name because we want a specific service implementation that // we know will be running in our own process (and thus won't be // supporting component replacement by other applications). bindService(new Intent(LocalServiceBinding.this, LocalService.class), mConnection, Context.BIND_AUTO_CREATE); mIsBound = true; } }; private OnClickListener mUnbindListener = new OnClickListener() { public void onClick(View v) { if (mIsBound) { // Detach our existing connection. unbindService(mConnection); mIsBound = false; } } }; }
明显看出这里面添加了一个名为ServiceConnection类,并实现了onServiceConnected(从IBinder获取Service对象)和onServiceDisconnected(set Service to null)。
而bindService和unbindService方法都是操做这个ServiceConnection对象的。
AndroidManifest.xml里添加:
<service android:name=".app.LocalService" />
这里没什么特别的,由于service没有须要什么特别的action,因此只是声明service而已,而activity和普通的没差异。
运行时,发现调用次序是这样的:
bindService:
1.LocalService : onCreate
2.LocalService : onBind
3.Activity: onServiceConnected
unbindService: 只是调用onDestroy
可见,onStart是不会被调用的,而onServiceDisconnected没有调用的缘由在上面代码的注释有说明。
------------------------
3、Broadcast Receiver详解
BroadcastReceiver 用于异步接收广播Intent。主要有两大类,用于接收广播的:
·正常广播 Normal broadcasts(用 Context.sendBroadcast()发送)是彻底异步的。它们都运行在一个未定义的顺序,一般是在同一时间。这样会更有效,但意味着receiver不能包含所要使用的结果或停止的API。
·有序广播 Ordered broadcasts(用 Context.sendOrderedBroadcast()发送)每次被发送到一个receiver。所谓有序,就是每一个receiver执行后能够传播到下一个receiver,也能够彻底停止传播--不传播给其余receiver。 而receiver运行的顺序能够经过matched intent-filter 里面的android:priority来控制,当priority优先级相同的时候,Receiver以任意的顺序运行。
要注意的是,即便是Normal broadcasts,系统在某些状况下可能会恢复到一次传播给一个receiver。 特别是receiver可能须要建立一个进程,为了不系统超载,只能一次运行一个receiver。
Broadcast Receiver 并无提供可视化的界面来显示广播信息。可使用Notification和Notification Manager来实现可视化的信息的界面,显示广播信息的内容,图标及震动信息。
生命周期
一个BroadcastReceiver 对象只有在被调用onReceive(Context, Intent)的才有效的,当从该函数返回后,该对象就无效的了,结束生命周期。
所以从这个特征能够看出,在所调用的onReceive(Context, Intent)函数里,不能有过于耗时的操做,不能使用线程来执行。对于耗时的操做,请start service来完成。由于当获得其余异步操做所返回的结果时,BroadcastReceiver 可能已经无效了。
发送广播
事件的广播比较简单,构建Intent对象,可调用sendBroadcast(Intent)方法将广播发出。另外还有sendOrderedBroadcast(),sendStickyBroadcast()等方法,请查阅API Doc。
1.new Intent with action name
Intent intent = new Intent(String action);
或者 只是new Intent, 而后
intent.setAction(String action);
2.set data等准备好了后,in activity,
sendBroadcast(Intent); // 发送广播
接收广播
经过定义一个继承BroadcastReceiver类来实现,继承该类后覆盖其onReceiver方法,并在该方法中响应事件。
public class SMSReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // get data from SMS intent Bundle bundle = intent.getExtras(); if (bundle != null){ // get message by "pdus" Object[] objArray = (Object[]) bundle.get("pdus"); // rebuild SMS SmsMessage[] messages = new SmsMessage[objArray.length]; for (int i=0; i < objArray.length; i++){ messages[i] = SmsMessage.createFromPdu((byte[])objArray[i]); StringBuilder str = new StringBuilder("from: "); str.append(messages[i].getDisplayOriginatingAddress()); str.append("\nmessage:\n"); str.append(messages[i].getDisplayMessageBody()); Toast.makeText(context, str.toString(), Toast.LENGTH_LONG) .show(); } } } }
注册Receiver
注册有两种方式:
1. 静态方式,在AndroidManifest.xml的application里面定义receiver并设置要接收的action。
<receiver android:name=".SMSReceiver"> <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver>
2. 动态方式, 在activity里面调用函数来注册,和静态的内容差很少。一个形参是receiver,另外一个是IntentFilter,其中里面是要接收的action。
public class HelloDemo extends Activity { private BroadcastReceiver receiver; @Override protected void onStart() { super.onStart(); receiver = new CallReceiver(); registerReceiver(receiver, new IntentFilter("android.intent.action.PHONE_STATE")); } @Override protected void onStop() { unregisterReceiver(receiver); super.onStop(); } }
一个receiver能够接收多个action的,便可以有多个intent-filter,须要在onReceive里面对intent.getAction(action name)进行判断。
我的推荐使用静态注册方式,由系统来管理receiver,并且程序里的全部receiver,能够在xml里面一目了然。而动态注册方式,隐藏在代码中,比较难发现。
并且动态注册,须要特别注意的是,在退出程序前要记得调用Context.unregisterReceiver()方法。通常在activity的onStart()里面进行注册, onStop()里面进行注销。官方提醒,若是在Activity.onResume()里面注册了,就必须在Activity.onPause()注销。
Permission权限
要接收某些action,须要在AndroidManifest.xml里面添加相应的permission。例如接收SMS:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
下面给出动态注册的接收来电的广播处理的CallReceiver的代码:
一种方式是直接读取intent.getStringExtra("incoming_number")来获取来电号码:
public class CallReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { TelephonyManager teleManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); switch(teleManager.getCallState()){ case TelephonyManager.CALL_STATE_RINGING: //响铃 Toast.makeText(context, "Ringing: " + intent.getStringExtra("incoming_number"), Toast.LENGTH_LONG).show(); break; case TelephonyManager.CALL_STATE_OFFHOOK: //接听 Toast.makeText(context, "OffHook: " + intent.getStringExtra("incoming_number"), Toast.LENGTH_LONG).show(); break; case TelephonyManager.CALL_STATE_IDLE: //挂断 Toast.makeText(m_context, "Idle: " + incomingNumber, Toast.LENGTH_LONG).show(); break; } } }
在运行时,发现除了响铃时能够获取来电号码,接听和挂断都不能成功获取的,显示为null。
另外一种方式是经过PhoneStateListener的onCallStateChanged来监听状态的变化:
public class CallReceiver extends BroadcastReceiver { private Context m_context; @Override public void onReceive(Context context, Intent intent) { m_context = context; TelephonyManager teleManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); teleManager.listen(new PhoneStateListener(){ @Override public void onCallStateChanged(int state, String incomingNumber) { switch(state){ case TelephonyManager.CALL_STATE_RINGING: //响铃 Toast.makeText(m_context, "Ringing: " + incomingNumber, Toast.LENGTH_LONG) .show(); break; case TelephonyManager.CALL_STATE_OFFHOOK: //接听 Toast.makeText(m_context, "OffHook: " + incomingNumber, Toast.LENGTH_LONG) .show(); break; case TelephonyManager.CALL_STATE_IDLE: //挂断 Toast.makeText(m_context, "Idle: " + incomingNumber, Toast.LENGTH_LONG) .show(); break; } }}, PhoneStateListener.LISTEN_CALL_STATE); } }
运行时也发现incomingNumber在接听和挂断时获取为blank。
由于这里监听的是通话的状态变化,因此这个receiver会被调用3次。
监听通话状态须要加上权限:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
===========
小结:
1. 对于sendBroadCast的intent对象,须要设置其action name;
2. 推荐使用显式指明receiver,在配置文件AndroidManifest.xml指明;
3. 一个receiver能够接收多个action;
4. 每次接收广播都会从新生成一个接收广播的对象,再次调用onReceive;
5. 在BroadCast 中尽可能不要处理太多逻辑问题,建议复杂的逻辑交给Activity 或者 Service 去处理。
--------------------------------------------
4、Content Provider详解
ContentProvider(内容提供者)是Android中的四大组件之一。主要用于对外共享数据,也就是经过ContentProvider把应用中的数据共享给其余应用访问,其余应用能够经过ContentProvider对指定应用中的数据进行操做。ContentProvider分为系统的和自定义的,系统的也就是例如联系人,图片等数据。
android中对数据操做包含有:
file, sqlite3, Preferences, ContectResolver与ContentProvider前三种数据操做方式都只是针对本应用内数据,程序不能经过这三种方法去操道别的应用内的数据。
android中提供ContectResolver与ContentProvider来操道别的应用程序的数据。
使用方式:
一个应用实现ContentProvider来提供内容给别的应用来操做,
一个应用经过ContentResolver来操道别的应用数据,固然在本身的应用中也能够。
如下这段是Google Doc中对ContentProvider的大体概述:
内容提供者将一些特定的应用程序数据供给其它应用程序使用。内容提供者继承于ContentProvider 基类,为其它应用程序取用和存储它管理的数据实现了一套标准方法。然而,应用程序并不直接调用这些方法,而是使用一个 ContentResolver 对象,调用它的方法做为替代。ContentResolver能够与任意内容提供者进行会话,与其合做来对全部相关交互通信进行管理。
1.ContentProvider
Android提供了一些主要数据类型的ContentProvider,好比音频、视频、图片和私人通信录等。可在android.provider包下面找到一些Android提供的ContentProvider。经过得到这些ContentProvider能够查询它们包含的数据,固然前提是已得到适当的读取权限。
主要方法:
public boolean onCreate() 在建立ContentProvider时调用
public Cursor query(Uri, String[], String, String[], String) 用于查询指定Uri的ContentProvider,返回一个Cursor
public Uri insert(Uri, ContentValues) 用于添加数据到指定Uri的ContentProvider中
public int update(Uri, ContentValues, String, String[]) 用于更新指定Uri的ContentProvider中的数据
public int delete(Uri, String, String[]) 用于从指定Uri的ContentProvider中删除数据
public String getType(Uri) 用于返回指定的Uri中的数据的MIME类型
*若是操做的数据属于集合类型,那么MIME类型字符串应该以vnd.android.cursor.dir/开头。
例如:要获得全部person记录的Uri为content://contacts/person,那么返回的MIME类型字符串为"vnd.android.cursor.dir/person"。
*若是要操做的数据属于非集合类型数据,那么MIME类型字符串应该以vnd.android.cursor.item/开头。
例如:要获得id为10的person记录的Uri为content://contacts/person/10,那么返回的MIME类型字符串应为"vnd.android.cursor.item/person"。
2.ContentResolver
当外部应用须要对ContentProvider中的数据进行添加、删除、修改和查询操做时,可使用ContentResolver类来完成,要获取ContentResolver对象,可使用Context提供的getContentResolver()方法。
ContentResolver cr = getContentResolver();
ContentResolver提供的方法和ContentProvider提供的方法对应的有如下几个方法。
public Uri insert(Uri uri, ContentValues values) 用于添加数据到指定Uri的ContentProvider中。
public int delete(Uri uri, String selection, String[] selectionArgs) 用于从指定Uri的ContentProvider中删除数据。
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) 用于更新指定Uri的ContentProvider中的数据。
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) 用于查询指定Uri的ContentProvider。
3.Uri
Uri指定了将要操做的ContentProvider,其实能够把一个Uri看做是一个网址,咱们把Uri分为三部分。
第一部分是"content://"。能够看做是网址中的"http://"。
第二部分是主机名或authority,用于惟一标识这个ContentProvider,外部应用须要根据这个标识来找到它。能够看做是网址中的主机名,好比"blog.csdn.net"。
第三部分是路径名,用来表示将要操做的数据。能够看做网址中细分的内容路径。