0

I have code below to get the status of screen. What I am trying to do is to make a kind of chronometre to measure the elapsed time while phone is open or in use in my Android application. when screen is ON, the phone is in use,I thought this way. if there is any other way, I want to know. The answer here was not good , I have tried and It did not work onresume, I dont know why... Also I think it is not a good way, not professional. I need your help to calculate the elapsed time while the phone is in use. Thanks

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;
    }
}
}
Community
  • 1
  • 1
dds
  • 13
  • 4

1 Answers1

0

You can do that without using any ui interraction. Just declare your broadcast receiver in manifest. When you get Intent.ACTION_SCREEN_ON create a variable which holds system time with System.currentTimeMillis(). Save another variable which holds When you get Intent.ACTION_SCREEN_OFF event. Calculate the difference between to values you will get phone use time in milliseconds. Sum it with sharedpreferences last time

ekilic
  • 83
  • 8