android四大组件的运用
Activity
Activity的生命周期:当Acitivity创建时,执行onCreate()方法,其次是onStrart();
当Activity显示时,即用户可见时,出现在前台,执行onResume()方法,当用户不可见时,转为后台,执行onPause()方法;
当从一个ActivityB返回到上一个ActivityA时,ActivityB执行onStop方法。
当Activity销毁时,执行onDestroy方法;
启动一个ActivityA时:
onCreate()–>onStart()–>onResume();
跳转到另外一个ActivityB时:
ActivityA onPause()–> ActivityB ( onCreate()–>onStart()–>onResume() ) –>ActivityA onStop();
从ActivityB返回到ActivityA时:
ActivityB onPause() –>ActivityA ( onRestart() –>onStart() —>onResume() ) –> ActivityB ( onStop() –> onDestroy() );
onCreate(): 当Activity第一次启动时,出发该方法,可以在此时完成活动的初始化工作。onCreate 方法有一个参数,该参数可以为空( null ),也可以是之前调用onSaveInstanceState ()方法保存的状态信息。
onStart:该方法的出发表示所属Activity将被展现给用户。
onResume : 当一个Activity和用户发生交互的时候,出发该方法。
onPause :当一个正在前台运行的Activity因为其他的活动需要前台运行而转入后台运行的时候出发该方法,这个时候需要将活动的状态持久化,比如正在编辑的数据库操作记录。
onStop : 当一个Activity不需要展示给用户看的时候,触发该方法。当内存紧张时,系统会直接结束掉这个Activity,而不会触发onStop方法,所以保存状态信息应该在onPause时做,而不是在onStop时做,Activity如果没有在前台运行,都将被停止或者Linux管理进程为了给新的Activity预留足够的存储空间而随时结束这些Activity,因为对于开发者来说,在设计应用程序的时候,必须时刻牢记这一原则,在一些情况下,onPause方法或许是活动触发的最后的方法,因此需要在这个时候保存需要保存的信息。
onRestart :当处于停止状态的Activity需要再次展现给用户的时候,触发该方法。
onDestory : 当Activity销毁的时候,触发该方法。和onStop方法一样,如果内存紧张,系统会直接结束这个Activity而不会触发该方法。
onSaveInstanceState :系统调用该方法,允许anctivity保存之前的状态,比如说在一串字符串中的光标所处的位置等。通常情况下,不需要重写覆盖该方法,在默认的实现中,已经提供了自动保存活动所涉及到的用户界面的所有状态信息。
Activity栈
每一个Activity的状态是由它在Activity栈(是一个后进先出,包含所有正在运行Activity的队列)中的位置决定的。
当一个新的Activity启动时,该Activity会到Activity栈的顶部
如果用户使用后退按钮返回是,或者前台的Activity结束,活动的Actvity就会被移出栈消亡,而在栈上的上一个活动的Activity将会一上来将变为活动状态。
一个应用程序的优先级是受高优先级的Activity影响的。当决定某个应用程序是否要终结去释放资源,Android内存管理使用栈来决定基于Activity的应用程序的优先级。
Activity的状态:
(一) 活动的:当一个Activity在栈顶,他是可视的,有焦点,可接受用户输入的。Android试图尽最大可能保持它活动状态,杀死其他Activity来确保当前活动Activity有足够的资源可使用。当另外一个Activity被激活,这个将会被暂停。
(二)暂停:在很多情况下,Activity可视,但是它没有焦点,换句话说它被暂停了,有可能是一个透明,或者非全屏的Activity被激活。当被暂停,一个Activity仍会当成活动状态,只不过是不可以接受用户输入。在及特殊的情况下,Android将会杀死一个暂停的Activity来为活动的Activity提供充足的资源。当一个Activity变为完全隐藏,它将会变成停止。
(三)停止:当一个Activity不是可视的,它“停止”了。这个Activity将仍然在内存中保存它所有的状态和会员信息。尽管如此,当其它地方需要内存时,它将是最有可能被释放资源的。当一个Activity停止后,一个很重要的步骤是要保存数据和当前UI状态。一旦一个Activity退出或者关闭了,它将变为待用状态。
(四)待用:在一个Activity被杀死后和被装载前,它是待用状态的。待用Activity被移除Activity栈,并且需要在显示和可用之前重新启动它。
Activity的四种启动模式
Acitivity的跳转有很多种。在android里,有四种启动模式:
(一)默认即 standard :标准模式,每一次调用startActivity()就会产生一个新的实例。例如:现在栈的情况为:A B C D,在D这个Activity中通过Intent跳转到D,那么现在的栈情况为: A B C D D 。此时如果栈顶的D通过Intent跳转到B,则栈情况为:A B C D D B。此时如果依次按返回键,D D C B A将会依次弹出栈而显示在界面上。
(二)singleTop:栈顶单例,如果已经有一个实例位于Activity栈的顶部时,就不产生新的实例,而止调用Activity中的newInstance()方法。如果部位与栈顶,会产生一个新的实例。例如:现在栈的情况为:A B C D。D的Launch mode设置成了singleTop,那么在D中启动Intent跳转到D,那么将不会新创建一个D的实例压入栈中,此时栈的情况依然为:A B C D。但是如果此时B的模式也是singleTop,D跳转到B,那么则会新建一个B的实例压入栈中,因为此时B不是位于栈顶,此时栈的情况就变成了:A B C D B。
(三)singleTask:singleTask模式的Activity不管是位于栈顶还是栈底,再次运行这个Activity时,都会destory掉它上面的Activity来保证整个栈中只有一个自己
(四)singleInstance:将Activity压入一个新建的任务栈中。例如:Task栈1的情况为:A B C。C通过Intent跳转到D,而D的Launch mode为singleInstance,则将会新建一个Task栈2。此时Task栈1的情况还是为:A B C。Task栈2的情况为:D。此时屏幕界面显示D的内容,如果这时D又通过Intent跳转到D,则Task栈2中也不会新建一个D的实例,所以两个栈的情况也不会变化。而如果D跳转到C,则栈1的情况变成了:A B C C,因为C的Launch mode为standard,此时如果再按返回键,则栈1变成:A B C。也就是说现在界面还显示C的内容,不是D。
好了,现在有一个问题就是这时这种情况下如果用户点击了Home键,则再也回不到D的即时界面了。如果想解决这个问题,可以为D在Manifest.xml文件中的声明加上:
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
加上这段之后,也就是说该程序中有两个这种声明,另一个就是那个正常的根activity,在打成apk包安装之后,在程序列表中能看到两个图标,但是如果都运行的话,在任务管理器中其实也只有一个。上面的情况点击D的那个图标就能回到它的即时界面(比如一个EditText,以前输入的内容,现在回到之后依然存在)。
PS:intent-filter中 <action android:name="android.intent.action.MAIN" />和 <category android:name="android.intent.category.LAUNCHER" />
两个过滤条件缺一不可才会在程序列表中添加一个图标,图标下的显示文字是android:label设定的字符串。
这些启动模式可以在功能清单文件AndroidManifest.xml中进行设置其中的launchMode属性。
也可以使用设置FLAG标志,如Intent.FLAG_ACTIVITY_REOREDER_TO__FRONT 标志,这个标志表示如果该Activity启动了,就不产生新的Activity,而只是把这个Activity实例加到栈顶来。
Flag标志有:
FLAG_ACTIVITY_NEW_TASK
FLAG_ACTIVITY_CLEAR_TOP
FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
FLAG_ACTIVITY_SINGLE_TOP
一般情况下,“standard”和“singleTop”的Activity的栈和收到的Intent的发送者在同一个栈内。除非Intent包括FLAG_ACTIVITY_NEW_TASK ,如果提供了FLAG_ACTIVITY_NEW_TASK 参数,会启动到别的栈里去。可以被实例化多次,并且可以存在不同的栈中,这种实例化时,一个栈可以包括一个Activity的多个实例。singleTop 要求如果该Activity的实例已经在栈顶,则不创建新的实例
“singleTask”和“singleInstance”总是要把启动的Activity作为一个栈的根元素,他们不会被启动到其他栈里。只能生成一个Activity的实例。
singleInstance 独占一个栈,其他的Activity都不能存在该栈中。
Service
service可以在多场合的应用中使用,比如播放多媒体的时候,用户启动了其他的Activity,这个时候程序要在后台继续播放,比如检测SD卡上文件的变化,再或者在后台记录你地理位置的改变等等,总之服务是在后台的。
Service是在一段不定的时间运行在后台,不和用户交互应用组件。每个Service必须在AndroidManifest中通过来声明。可以通过contect.startservice和contect.bindserverice来启动。
Service和其他应用组件一样,运行在进程的主线程中。这就是说,如果Service需要很多耗时或者阻塞的操作,需要在其子线程中实现。
Service的两种模式,1、startService()。2、bindService();
本地服务Local Service 用于应用程序内部,可以启动并运行,直到有人停止了它或者它自己停止,在这种方式下,它以调用Context.startService()启动而以调用Context.stopSerVice()结束。它可以调用Service.stopSelf()或者Service.stopResult()来自己停止。无论调用了多少次startService()方法,只需要调用一次stopService()来停止服务。该种服务用于实现应用程序自己的一些耗时任务,比如查询升级信息,并不占用应用程序比如Activity所属线程,而是单开线程后台执行。
远程服务Remote Service 用于android系统内部的应用程序之间。
它可以通过自己定义并暴露出来的接口进行程序操作。客户端建立一个到服务对象的连接,并通过那个连接来调用服务。连接以调用Context.bindService()方法建立,以调用Context.unbindService()关闭,多个客户端可以绑定至同一个服务,如果服务此时还没有加载,bindService()会先加载它。
可以被其他应用程序复用,比如天气预报服务,其他应用程序不需要再写这样的服务,调用已有的即可。
生命周期
startService()启动时:onCreate()–>onStrat()–>running–>stopService()–>onDestroy()–>service stop
如果Service还没有运行,则android先调用onCreate()然后调用onStart();如果Service已经运行,则只调用onStrat(),所以一个Service的onStrat方法可能会重复调用多次。
stopService的时候直接onDestroy,如果是调用者自己直接退出而没有调用stopService的话,Service会一直在后台运行,该Service的调用者在启动起来后可以通过stopService关闭service。
所以调用startService的生命周期为:onCreate –> onStart(可多次调用)–>onDestroy
使用bindService()启动Service时:
bindService()–>onCreate()–>onBind()(只一次,不可多次绑定)–>onUnbind–>onDestroy –>Service stop。
onBind将返回给客户端一个IBind接口实例,IBind允许客户端回调服务的方法,比如得到Service运行的状态或其他操作。这个时候把调用者(Context,例如Activity)会和Service绑定在一起,Context退出了,Service就会调用onUnbind–>onDestroy相应退出。
所以调用bindService的生命周期为:onCreate –> onBind(只一次,不可多次绑定)–>onUnbind –> onDestory。
在Service每一次的开启关闭过程中,只有onStrat可被多次调用(通过多次startService调用),其他onCreate,onBind,onUnBind,onDestory在一个生命周期中只能被调用一次。
而启动Service,根据onStratCommend的返回值不同,有两个附加的模式:
- START_STICKY 用于显示启动和停止Service;
- START_NOT_STICKY或START_REDELIVER_INTENT用于有命令需要处理时才运行的模式。
服务不能自己运行,需要通过调用Context.startService()或者Context.bindService()方法启动服务。这两个方法都可以启动Service,但是他们的使用场合有所不同。
使用startService()方法启动服务,调用者与服务之间没有关联,即使调用者退出了,服务让然运行。
如果打算采用Context.startService()启动服务,在服务未被创建时,系统会先调用服务的onCreate()方法,接着调用onStart()方法。
如果调用startService()方法前服务已经被创建,多次调用startService()方法并不会导致多次创建服务,但会导致多次调用onStart()方法。
采用startService方法启动的服务,只能通过stopService()方法结束服务,服务结束时会调用onDestroy()方法。使用bindService方法启动的服务,调用者与服务绑定在了一起,调用者一旦退出,服务也就终止,即“不求同生,但求同死”的特点。
onBind()只有采用bindService方法启动服务时才会回调该方法。该方法在调用者与服务绑定时被调用,当调用者与服务已经绑定,多次调用bindService方法并不会导致该方法被多次调用。
采用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可以使用StratForeground(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.mark.SERVICE_TEST"));
}
});
((Button) findViewById(R.id.stopLocalService)).setOnClickListener(
new View.OnClickListener(){
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
stopService(new Intent("com.mark.SERVICE_TEST"));
}
});
}
}
在AndroidManifest.xml添加:
<service android:name=".LocalService">
<intent-filter>
<action android:name="com.mark.SERVICE_TEST" />
<category android:name="android.intent.category.default" />
</intent-filter>
</service>
否则启动服务是会提示 new Intent 找不到“com.mark.SERVICE_TEST”。
对于这类不需要和Activity交互的本地服务,是使用startService/stopservcie的最好例子。
运行时可以发现第一次startService是,会调用onCreate和onStart,在没有stopservcie前,无论点击多少次startService,都只会调用onStart。而stopservcie时调用onDestroy,再次点击stopservcie,会发现不会进入Service的生命周期的,即不会再调用onCreate,onStart和onDestroy。
而onBind在startService/stopservcie中没有调用。
2.本地服务和Activity交互
对于这种例子,官方的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对象。
Actvity:
/**
* <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(setService to null)。
而bindService和unBindServcie方法都是操作这个ServiceConnection对象的。
AndroidManifest.xml里添加:
<service android:name=".app.LocalService" />
这里没什么特别的,因为Servcie没有需要什么特别的action,所以只是生命service而已,而Actvity和普通的没差别
运行时,调用顺序为:
bindService:
1.LocalService:onCreate
2.LocalService:onBind
3.Activity:onServiceConnected
unbindService:只是调用onDestroy
可见,onStart是不会被调用的,而onServiceDisconnected没有调用的原因在上面代码的注释有说明。
三、Broadcast Receiver详解
Broadcast Receiver 用于异步接收广播Intent。主要有两大类,用于接收广播:
正常广播 Normal broadcasts(用Context.sendBroadcast()发送)是完全异步的。它们都运行在一个未定义的顺序,通常是在同一时间。这样会更有效,但意味着receiver不能包含所要使用的结果或终止的API.
有序广播Ordered broadcasts(用Context.sendOrderdBroadcast()发送)每次被发送到一个receiver。所谓有序,就是每个receiver执行后可以传播到下一个receiver,也可以完全中止传播--不传播给其他receiver。而receiver运行的顺序可以通过matched intent-filter里面的android:priority来控制,当priority优先级相同的时候,Receiver以任意的顺序运行。
要注意的是,即使是Normal broadcasts,系统在某些情况下可能会恢复到一次传播给一个Receiver。特别是Receiver可能需要创建一个进程,为了避免系统超载,只能一次运行一个Receiver。
Broadcast Receiver 并没有提供可视化的界面来显示广播信息。可以使用Notification和Notification Manager 来实现可视化的信息的界面,显示广播信息的内容,图标及震动信息。
生命周期
一个BroadcasetReceiver 对象只有在被调用onReceive(Context,Intent)的才有效,当从该函数返回后,该对象就是无效的了,结束生命周期。
因此从这个特征可以看出,在所调用的onReceive(Context,Intent)函数里,不能有过于耗时的操作,布恩那个使用线程来执行。对于耗时的操作,请startIntentService来完成,因为当得到其他异步操作返回的结果时,BroadcastReceiver可能已经无效了。
发送广播
事件的广播比较简单,构建Intent对象,可调用sendBroadcast(Intent)方法将广播发出。另外还有sendOrderedBroadcast(),sendStickyBroadcast()等方法。
1 new Intent with action name;
Intent intent = new Intent(String action);
或者 只是new Intent,然后intent.setAction(String action);
2 set data 等准备好了后,in activity,sendBroacast(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的onStrart()里面进行注册,onStop()里进行注销。如果在onResume()里面注册了,就必须在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去处理。
四、Content Provider详解
Content Provider(内容提供者)是Android中的四大组件之一。主要用于对外共享数据,也就是通过ContentProvider把应用中的数据共享给其他应用访问,其他应用可以通过ContentProvider对指定应用中的数据进行操作。ContentProvider分为系统的和自定义的,系统的也就是例如联系人,图片等数据。
android中对数据操作包含有:file,sqlite,Preferences,ContentResolver与ContentProvider前三种数据操作方式都只是针对本应用内数据,程序不能通过这三种方法去操作别的应用内的数据。
android中提供ContentResolver与ContentProvider来操作别的应用程序的数据。
使用方式:
一个应用实现ContentProvider来提供内容给别的应用来操作,一个应用通过ContentResolver来操作别的应用数据,当然在自己的应用中也可以。
内容提供者将一些特定的应用程序数据提供给其他应用程序使用。内容提供者继承与ContentProvider基类,为其他应用程序取用和存储它管理的数据实现了一套标准方法。然而应用程序并不直接调用这些方法,而是使用一个ContentResolver对象,调用它的方法作为替代。ContentResolver可以与任意内容提供者进行会话,与其合作来对所有相关交互通讯进行管理。
1.ContentProvider
Android提供了一些主要数据类型的ContentProvider,比如音频,视频,图片和私人通讯录等。可在android.provider包下面找到一些Android提供的ContentProvider。通过活的这些ContetnProvider可以查询它们包含的数据,当然前提是已获得适当的读取权限。
主要方法:
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为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.youkuaiyun.com”。
第三部分是路径名,用来表示将要操作的数据。可以看作网址中细分的内容路径。