如何测量手机正在使用时的流逝时间

问题描述:

我有下面的代码来获取屏幕的状态。我正在尝试做的是制作一种计时器来衡量手机在我的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; 
    } 
} 
} 

你可以做,没有使用任何UI interraction。只需在清单中声明您的广播接收器。当你得到Intent.ACTION_SCREEN_ON时,用System.currentTimeMillis()创建一个保存系统时间的变量。保存另一个保存的变量当您收到Intent.ACTION_SCREEN_OFF事件时。计算您将以毫秒为单位获得电话使用时间的值之间的差异。总结它与上次sharepreferences