2014-02-10 38 views
6

我試圖做一些(理論上)簡單與我的第一個應用程序,但我需要一些幫助入門。我想建立一個應用程序,告訴我今天Nexus 4上的屏幕有多長。如何跟蹤Android上的「屏幕開啓」時間?

的Android讓我看到屏幕上有多久,因爲通過設置>電池>屏幕上次充電過,但我不知道如何分析這些數據,或者如何將其限制在當前的一天。 迄今爲止,我的研究表明,batterystats.bin涉及到上面列出的屏幕跟蹤,並且我可能能夠使用ACTION_SCREEN_ON和ACTION_SCREEN_OFF進行此操作,但我不確定這正是我正在尋找的內容。

任何想法?

回答

3

我知道這是一個老問題,但希望這可以幫助某人。

在我的服務,我聽SCREEN_ON/SCREEN_OFF行動,抓住兩個時間之間的差異,並保存到的onDestroy回調中sharedpreferences。

BroadcastReceiver mybroadcast = new BroadcastReceiver() { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     Log.i("[BroadcastReceiver]", "MyReceiver"); 

     if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){ 
      startTimer = System.currentTimeMillis(); 
     } 
     else if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){ 
      endTimer = System.currentTimeMillis(); 
      screenOnTime = endTimer - startTimer; 

      if(screenOnTime < TIME_ERROR) { 
       times.add(screenOnTime); 
      } 

     } 

    } 
}; 

該服務在啓動時以及更換包時發現(我發現它有助於調試)。

public class BootReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     Intent i = new Intent(context, ScreenOnService.class); 
     context.startService(i); 
    } 
} 

這裏是我對廣播接收機

 <receiver android:name=".BootReceiver"> 
      <intent-filter> 
       <action android:name="android.intent.action.BOOT_COMPLETED" /> 
      </intent-filter> 
      <intent-filter> 
       <action android:name="android.intent.action.PACKAGE_REPLACED" /> 
       <data android:scheme="package" android:path="com.application.test" /> 
      </intent-filter> 
     </receiver> 
+0

清單,我們不能保證服務一直在後臺運行。 – User9527