一个activity播放背景音乐,当按下电源键锁屏,调用了 onPause(),再次点击电源键后,什么也没调用,此时屏幕还没有开锁,需要滑动屏幕后才能从新回到activity,此时也没有调用任何生命周期方法. 我的需求是:activity不显示时,把背景音乐暂停,然后回到activity时,再继续播放。
我在onPause()中暂停音乐,在onResume中重放音乐。但是这种方法在第二次按下音乐就播放了,也没有调用onresume。不知道什么原因?大家有对电源键,滑动开屏幕的开发经历和想法吗?望各位大侠指点。

解决方案 »

  1.   

    锁屏后,你的Activity可能被注销了,重新开只有onCreate和onStart。
      

  2.   

    按下电源键后,会走onSavedInstance()方法,建议打些Log看看Activity的状态。
      

  3.   

    你可以起一个BroadcastReceiver,监听屏幕的状态,Intent有ACTION_SCREEN_OFF等状态,根据不同的Action做不同的操作就可以了。
      

  4.   

    谢谢你,这中方法可以解决。下面是代码片段,希望对其他仁兄有帮助。private final BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {  
           @Override  
           public void onReceive(final Context context, final Intent intent) {  
               final String action = intent.getAction(); 
              if(Intent.ACTION_SCREEN_ON.equals(action)){ 
                   Log.d("lock_test", "screen is on...");  
              }else if(Intent.ACTION_SCREEN_OFF.equals(action)){  
               if(player.isPlaying()){
           player.pause();
             }
               isLock = true;
                   Log.d("lock_test", "screen is off...");  
              }else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT))
              {
               if(myApp.isMusicOn()&&!player.isPlaying()){
                   player.start();
                  }
               if(status!=GameView.LOSE){
               gameView.resumeTimer();
               }
               
              isLock = false;
               Log.d("lock_test", "ACTION_USER_PRESENT..."); 
                  //  Handle resuming events         }        }  
       };