我正在尝试用我的第一个应用程序(理论上)做一些简单的事情,但我需要一些帮助才能开始.我想构建一个应用程序,告诉我今天Nexus 4上的屏幕有多长时间了.
Android显示自上次通过设置>以来屏幕已经显示的时间长度电池>屏幕,但我不知道如何解析这些数据,或者如何将其限制在当天.
到目前为止,我的研究表明,batterystats.bin涉及上面概述的屏幕跟踪,我可以使用ACTION_SCREEN_ON和ACTION_SCREEN_OFF,但我不确定这是否正是我正在寻找的.
有任何想法吗?
解决方法
我知道这是一个老问题,但希望这会对某人有所帮助.
在我的服务中,我监听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>