如何跟踪“屏幕显示"时间在Android上? [英] How do I track "screen on" time on Android?

查看:146
本文介绍了如何跟踪“屏幕显示"时间在Android上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用我的第一个应用程序(理论上)简单地做一些事情,但是我需要一些入门帮助.我想构建一个应用程序,该应用程序可以告诉我Nexus 4的屏幕今天已经打开了多长时间.

I'm trying to do something (theoretically) simple with my first app, but I need some help getting started. I'd like to build an app that tells me how long the screen on my Nexus 4 has been on today.

Android通过设置">电池">屏幕"向我显示了自上次充电以来屏幕已打开多长时间,但是我不确定如何解析此数据或如何将其限制为当前日期. 到目前为止,我的研究表明,batterystats.bin与上面概述的屏幕跟踪有关,并且我可以为此使用ACTION_SCREEN_ON和ACTION_SCREEN_OFF,但是我不确定这是否正是我所要的.

Android shows me how long the screen has been on since last charge via Setting > Battery > Screen, but I'm not sure how to parse this data, or how to limit it to the current day. My research so far indicates that batterystats.bin is involved with screen tracking outlined above, and that I might be able to use ACTION_SCREEN_ON and ACTION_SCREEN_OFF for this, but I'm not sure if that's exactly what I'm looking for.

有什么想法吗?

推荐答案

我知道这是一个古老的问题,但希望这会对某人有所帮助.

I know this is a old question but hopefully this will help someone.

在我的服务中,我听SCREEN_ON/SCREEN_OFF动作,并抓住两次之间的差,并保存到onDestroy回调中的sharedpreferences中.

Within my service i listen for SCREEN_ON/SCREEN_OFF actions and grab the difference between the two times and save to sharedpreferences within onDestroy callback.

    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);
           }

        }

    }
};

该服务在启动时以及更换软件包时启动(我发现这对调试很有帮助).

The service is started on boot and when the package is replaced (I find it helpful for debugging).

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

这是我给广播接收者的清单

And here is my manifest for the broadcast receiver

        <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>

这篇关于如何跟踪“屏幕显示"时间在Android上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆