我有以下代码来获取屏幕状态。我想要做的是制作一种计时器来衡量手机在我的Android应用程序中打开或使用时所经过的时间。当屏幕打开时,手机正在使用中,我就是这么想的。如果还有其他方式,我想知道。 答案here并不好,我已经尝试过,它没有工作,我不知道为什么......我认为这不是一个好方法,不是专业。我需要你的帮助来计算手机使用时的经过时间。感谢
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
///start calculating the elapsed time
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
}
@Override
protected void onPause() {
if (ScreenReceiver.screenMod) {
Toast.makeText(getApplicationContext(),"turn off",Toast.LENGTH_SHORT).show();
/////stop calculating
} else {
}
super.onPause();
}
@Override
protected void onResume() {
if (!ScreenReceiver.screenMod) {
Toast.makeText(getApplicationContext(),"turn on",Toast.LENGTH_LONG).show();
////continue calculating
} else {
}
super.onResume();
}
}
ScreenReceiver.class
public class ScreenReceiver extends BroadcastReceiver {
public static boolean screenMod = true;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenMod = false;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenMod = true;
}
}
}
答案 0 :(得分:0)
你可以不使用任何ui交互来做到这一点。只需在清单中声明您的广播接收器即可。当您获得Intent.ACTION_SCREEN_ON时,使用System.currentTimeMillis()创建一个保存系统时间的变量。保存另一个保存的变量当您获得Intent.ACTION_SCREEN_OFF事件时。计算您将获得电话使用时间的值之间的差异,以毫秒为单位。上次使用共享偏好求和