Android笔记之多个Activity的生命周期交互

 

单个Activity:

      应用开启时调用:onCreate(),onStart(),onResume();

      按下返回键:onPause(),onStop(),onDestory();

多个Activity之间交互时:

     跳转至第二个Activity时:

FirstActivity SecondActivity
onPause()  
 

onCreate()

  onStart()
  onResume()
onStop()  

 

 

 

 

 

 

 

按下锁屏键

SecondActivity
onPause()
onStop()

 

 

 

解锁

SecondActivity
onRestart()
onStart()
onResume()

 

 

 

 

按下返回键,或者SecondActivity调用finish()

FirstActivity SecondActivity
  onPause()
onRestart()  
onStart()  
onResume()  
  onStop()
  onDestory()

 

 

 

 

 

 

 

 

生命周期应用实例

在Activity中播放音乐

oncreate():

 1     private MediaPlayer mediaplayer;
 2     @Override
 3     protected void onCreate(Bundle savedInstanceState) {
 4         super.onCreate(savedInstanceState);
 5         setContentView(R.layout.activity_main);
 6         Log.i("imformation", "MainActivity onCreate!");
 7         mediaplayer=MediaPlayer.create(this, R.raw.quite);
 8         mediaplayer.start();
 9         
10     }

 

在Activity onPause时,音乐也需要暂停

此时,需要一个记录播放到的位置的变量:private int place;

onPause:

 1        @Override
 2     protected void onPause() {
 3     // TODO Auto-generated method stub
 4     super.onPause();
 5     if(mediaplayer.isPlaying())
 6     {
 7         mediaplayer.pause();
 8         place=mediaplayer.getCurrentPosition();
 9         
10     }
11     Log.i("imformation", "MainActivity onPause!");
12     }

同样,当Activity Resume时,音乐也要接着播放

onResume:

 1     @Override
 2     protected void onResume() {
 3     // TODO Auto-generated method stub
 4     super.onResume();
 5     if(place!=0)
 6     {
 7         mediaplayer.seekTo(place);
 8         mediaplayer.start();
 9     }
10     Log.i("imformation", "MainActivity onResume!");
11     }

 

当Activity 销毁时,音乐播放器也要销毁

 1     @Override
 2     protected void onDestroy() {
 3         // TODO Auto-generated method stub
 4         super.onDestroy();
 5             if(mediaplayer!=null){
 6         mediaplayer.release();
 7         mediaplayer=null;
 8                  }
 9         Log.i("imformation", "MainActivity onDestory!");
10     }        

 

注:本文是学习慕课网Android-重识Activity(http://www.imooc.com/learn/384)时的笔记,如有侵权行为,立即删除

你可能感兴趣的:(Activity)