Android: How to detect when phone is active and idle?

时光毁灭记忆、已成空白 提交于 2019-12-02 11:42:07

问题


I want to create an app that will know when user is using the phone(start the screen and close the screen). After a period of time I need to call doSomething() method.

Question:

1.How can I know when user start using the phone and when he close the screen?

2.Should I use Service or IntentService? Which is better in my case?


回答1:


You can try something like this using a BroadcastReceiver and a Service:

Your class using The BroadcastReceiver:

  public class ScreenReceiver extends BroadcastReceiver {

        private boolean screenOff;

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))    {
                screenOff = true;
            } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                screenOff = false;
            }
            Intent i = new Intent(context, UpdateService.class);
            i.putExtra("screen_state", screenOff);
            context.startService(i);
        }

    }

And the service:

    public static class ScreenService extends Service {

        @Override
        public void onCreate() {
            super.onCreate();
            IntentFilter filter = new     IntentFilter(Intent.ACTION_SCREEN_ON);
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            BroadcastReceiver mReceiver = new ScreenReceiver();
            registerReceiver(mReceiver, filter);
        }

        @Override
        public void onStart(Intent intent, int startId) {
            boolean screenOn = intent.getBooleanExtra("screen_state", false);
            if (!screenOn) {
                //Implement here your code
            } else {
                //Implement here your code
            }
        }
    }


来源:https://stackoverflow.com/questions/32891835/android-how-to-detect-when-phone-is-active-and-idle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!