Android:如何检测手机处于活动状态和空闲状态



我想创建一个应用程序,将知道当用户正在使用手机(启动屏幕和关闭屏幕)。一段时间后,我需要调用doSomething()方法。

问题:

1。我怎么知道用户什么时候开始使用手机,什么时候关闭屏幕?

2。我应该使用Service还是IntentService?对我来说哪个更好?

你可以尝试使用BroadcastReceiver和Service:

你的类使用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);
        }
    }

和服务:

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

相关内容

  • 没有找到相关文章

最新更新