1.Activity,这个不用多说,直接上代码和图就能看懂。
代码展示:
public class ExampleActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//activity开始被创建.
}
@Override
protected void onStart() {
super.onStart();
// activity开始可见.
}
@Override
protected void onResume() {
super.onResume();
// activity可见
}
@Override
protected void onPause() {
super.onPause();
// 另外一个activity开始获取焦点(这个activity就开始暂停)
}
@Override
protected void onStop() {
super.onStop();
// activity不再可见
}
@Override
protected void onDestroy() {
super.onDestroy();
//activity被销毁 .
}
}
Activity整个生命周期:从onCreate()===》onDestroy()
Activity可见的生命周期:从 onStart()===》onStop()
Activity前台的生命周期:从onResume()===》onPause()
补充知识点:保存Activity的状态:销毁之前调用onSaveInstanceState(),从 onCreate()或是onRestoreInstanceState()取出bundle恢复之前Activity的状态。
2.Service:
public class ExampleService extends Service {
int mStartMode; // indicates how to behave if the service is killed
IBinder mBinder; // interface for clients that bind
boolean mAllowRebind; // indicates whether onRebind should be used
@Override
public void onCreate() {
// service 被创建
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 当调用startService()之后,service就启动了
return mStartMode;
}
@Override
public IBinder onBind(Intent intent) {
// 通过bindService(),绑定一个客户端
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
// 通过 unbindService(),所有客户端都被解绑
return mAllowRebind;
}
@Override
public void onRebind(Intent intent) {
//当调用onUnbind()之后,再调用bindService(),又通过bindService()绑定一个客户端
}
@Override
public void onDestroy() {
//service被销毁
}
}
服务有2种启动方式,所以也有2种生命周期形式:
3.BroadcastReceiver:
在调用 onReceive(Context, Intent)期间,BroadcastReceiver是有效的。一旦从这个方法中返回,就不再有效。
4.Fragment: 依赖于Activity
和Activity相对应的状态: