Chinaunix首页 | 论坛 | 博客
  • 博客访问: 121066
  • 博文数量: 29
  • 博客积分: 652
  • 博客等级: 上士
  • 技术积分: 340
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-03 21:26
文章分类

全部博文(29)

文章存档

2013年(8)

2012年(21)

分类: 嵌入式

2012-03-01 10:45:44

1,如何判断Activity退出是因为orientation变化?

几种Activity启动和退出过程中,系统的调用函数
第一次新启动:
onCreate(), onStart(), onResume()
按BACK键退出:
onPause(),onStop(), onDestroy().

启动后,按HOME退出
onSaveInstanceState(), onPause(), onStop()
启动从HOME键退出的应用:
onRestart(),onStart(),onResume()

启动后,change orientation:
onSaveInstanceState(), onPause(), onStop(), onRetainNonConfigurationInstance(), onDestroy()onCreate(), onStart(), onResume()

启动后,按HOME退出,
onSaveInstanceState(), onPause(), onStop()
然后change orientation,再启动:
onRetainNonConfigurationInstance(), onDestroy(),onCreate(), onStart(), onResume()

当创建一个新的Activity,调onCreate();
当一个Activity显视在屏幕前,调onResume();
当一个Activity不再显视在屏幕上时,调onPause();
这些跟SDK文档一样,注意onRetainNonConfigurationInstance()只在orientation变化中调用。onSaveInstanceState()在orientation变化和HOME退出中调用。

2,当activty销毁的时候如何让它启动的service继续运行?

一般用bindservice启动的service,在activity::onDestroy()或onStop()时要unbindService(),这样service就destroy了。而有时Activity并不是真正地退出,而只是orientation change或用户按HOME键。service重启的代价很大。这时可以在onStart()中这样:
  1. public void onStart() {
  2.         Log.d(TAG, "onStart()");
  3.         super.onStart();
  4.         
  5.         Intent serviceIntent=new Intent(getApplicationContext(), com.xxx.xxbService.class);
  6.         startService(serviceIntent);
  7.         
  8.         mServiceConnection = new ServiceConnection();
  9.         mGrabServiceRunning = bindService(serviceIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
  10.         Log.d(TAG, "Launch GrabService:" + mGrabServiceRunning);
  11.     }
startService()启动的service,如果在Service的onStartCommand()中返回START_STICKY,那Service必须显式地调用stopService()或stopSelf(),才可以终止。
  1. public int onStartCommand(final Intent intent, int flags, final int startId) {
  2.         Log.d(TAG, "onStartCommand");
  3.         return START_STICKY;
  4.     }
这样当检测到orientation change或用户按BACK键时,在onStop()中,只unbindService():
  1. public void onStop() {
  2.         Log.d(TAG, "onStop()");
  3.         super.onStop();
  4.         
  5.         unbindService(mServiceConnection);
  6.     }
这样由于没有调用stopService(),service会继续运行。

阅读(1756) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~