2015-10-01 121 views
1

我想創建一個應用程序,它會知道用戶何時使用手機(啓動屏幕並關閉屏幕)。經過一段時間後,我需要撥打doSomething()方法。Android:如何檢測手機何時處於活動狀態並閒置?

問:

1.How我可以知道,當用戶開始使用手機時,他關閉屏幕?

2.我應該使用Service還是IntentService?我的情況哪個更好?使用廣播接收器

你的類:

回答

1

您可以使用廣播接收器和一個服務嘗試這樣的事情

public class ScreenReceiver extends BroadcastReceiver { 

     private boolean screenOff; 

     @Override 
     public void onReceive(Context context, Intent intent) { 
      if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { 
       screenOff = true; 
      } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { 
       screenOff = false; 
      } 
      Intent i = new Intent(context, UpdateService.class); 
      i.putExtra("screen_state", screenOff); 
      context.startService(i); 
     } 

    } 

,服務:

public static class ScreenService extends Service { 

     @Override 
     public void onCreate() { 
      super.onCreate(); 
      IntentFilter filter = new  IntentFilter(Intent.ACTION_SCREEN_ON); 
      filter.addAction(Intent.ACTION_SCREEN_OFF); 
      BroadcastReceiver mReceiver = new ScreenReceiver(); 
      registerReceiver(mReceiver, filter); 
     } 

     @Override 
     public void onStart(Intent intent, int startId) { 
      boolean screenOn = intent.getBooleanExtra("screen_state", false); 
      if (!screenOn) { 
       //Implement here your code 
      } else { 
       //Implement here your code 
      } 
     } 
    } 
+0

謝謝!這是我正在尋找的答案。經過測試和工作! –

相關問題