2012-03-17 103 views
6

所以我有我的onResume命令重新啓動一個停止的線程運行我的遊戲循環。 這適用於在主頁按鈕關閉或重點關注其他應用程序時恢復應用程序。 但是,當您關閉屏幕然後再次打開時,在屏幕解鎖之前,活動onResume命令將立即觸發。我需要我的活動來了解屏幕何時解鎖,以便它可以在適當的時間重新啓動線程。屏幕解鎖時的活動句柄

有沒有人有過這種情況?

回答

16

用於檢測屏幕上,屏幕關閉寄存器的廣播reciver像:

的AndroidManifest.xml:

<receiver android:name="receiverScreen"> 
     <intent-filter> 
      <action android:name="android.intent.action.SCREEN_ON" /> 
      <action android:name="android.intent.action.SCREEN_OFF" /> 
<action android:name="android.Intent.ACTION_USER_PRESENT" /> 
     </intent-filter> 
    </receiver> 

在活動或服務:

try { 
       IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON); 

       filter.addAction(Intent.ACTION_SCREEN_OFF); 
filter.addAction(Intent.ACTION_USER_PRESENT); 

       BroadcastReceiver mReceiver = new receiverScreen(); 

       registerReceiver(mReceiver, filter); 
     } catch (Exception e) { 

     } 

接收機如果屏幕開啓/關閉發生,系統會通知您的代碼爲

public class receiverScreen extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 

     if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)){ 

     } 
     if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){ 

     } 
if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)){ 

     } 
    } 

    } 
+0

看起來像AndroidManifest.xml的代碼沒有包含在內。 – louielouie 2012-03-17 05:47:55

+0

非常有幫助,但ACTION_SCREEN_OFF只在屏幕開啓並且解鎖屏幕出現時執行,當解鎖屏幕解鎖並消失時,我需要執行此操作 – tantonj 2012-03-17 08:51:49

+0

@tantonj然後註冊更多BroadcastReceiver接收器'Intent.ACTION_USER_PRESENT' – 2012-03-17 08:58:19