Android中Activity要考虑的生命周期

来源:互联网 发布:nginx并发数 编辑:程序博客网 时间:2024/06/09 22:19

今天在测试Mediaplay播放器的时候,发现了一个有趣的事情,其中是涉及到Activity的生命周期的,因为在Acitvity中的生命周期我写了如下代码:

一般我会和大多数人一样喜欢这样写Oncreate代码,判断横竖屏和获取组件。

关于横竖屏的在xml中的设置:

In some special cases, you may want to bypassrestarting of your activity based on one or more types of configurationchanges. This is done with the android:configChanges attributein its manifest. For any types of configuration changes you say that you handlethere, you will receive a call to your current activity's onConfigurationChanged(Configuration) methodinstead of being restarted. If a configuration change involves any that you donot handle, however, the activity will still be restarted and onConfigurationChanged(Configuration) willnot be called.

  publicvoid onCreate(Bundle savedInstanceState){

     super.onCreate(savedInstanceState);

     setContentView(R.layout.activity_main);

 

     try {

       init();

     } catch (Exception e) {

       //TODOAuto-generated catch block

       e.printStackTrace();

     }

     setView();

     setListener();

  }

然后在OnStart()中显示绑定广播,和绑定服务 

  protectedvoid onStart() {

     super.onStart();

     Intent in = new Intent(MainActivity.this, MusicPlayerService.class);

     bindService(in, conn, Activity.BIND_AUTO_CREATE);

     resignerServiceBrocase();//注册广播

  }

然后在onResume()中显示重要的组件,每次切屏的时候都要显示的组件。

在Onpause()中保存数据,

onStop()就解除广播和服务,消除一些变化了的组件。

但在一次锁屏之后,我发现问题了,一般我们只注意到,按back键和Home键在App中返回桌面时的生命周期有所不同,其中不同就是back键是会直接kill了这个Activity的,就会调用其onDestroy 的方法,而home只执行到onStop()中,但锁屏又是另一种生命周期的特性了,它只会调用onPause();换言之,我的onStop()中的代码是没有被执行,没有注销广播,没有注销服务,没有消除组件,当我解锁再进入Activity中时,很显然是调用OnResume()中的方法,再次执行其方法,但组件没有被一些组件却消去,导致屏幕出现布局错乱,因此我将Onstop()和onPause()中的代码互换,解决了。但我看见API中的一句:

onPause() is where you deal with theuser leaving your activity. Most importantly, any changes made by the usershould at this point be committed (usually to the ContentProvider holding the data).

 

我又改在onpause()中实现所有了。那么onStop()可以干点什么呢?继续看API

(1)可以在onCreat()启动后台线程下载,在onDestroy中销毁

 For example, if it has a thread running in the background to downloaddata from the network, it may create that thread in onCreate() and then stopthe thread in onDestroy().

(2)可见状态

 For example, you can register a BroadcastReceiver in onStart() to monitor forchanges that impact your UI, and unregister it in onStop() when the user nolonger sees what you are displaying. The onStart() and onStop() methods can becalled multiple times, as the activity becomes visible and hidden to the user.

在这里可以知道应该在onStop()注销了广播和服务。

 

说明锁屏的时候,Acitity是进入了可见,当不可交互的状态。

 

 

 

 


 

 

 

原创粉丝点击