Android 判断系统用户无操作

       最近项目需求,RK3326平台,无触摸机器(智能电子称),可以接鼠标操作。需求是这样的,客户要保证自己的app一直在前台运行,当用户手动切到桌面或者其他app,超过一分钟没有操作就回到客户的app界面。刚开始想在PhoneWindowManager里面去监听按键事件,后来发现有点问题,于是用了另一个办法,在frameworks/base/core/java/android/view,在这里有个叫ViewRootImpl.java的类,里面有个广播 

final class WindowInputEventReceiver extends InputEventReceiver {
        public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {
            super(inputChannel, looper);
        }

        @Override
        public void onInputEvent(InputEvent event, int displayId) {
            enqueueInputEvent(event, this, 0, true);
			if(event instanceof MotionEvent){
				MotionEvent motionEvent = (MotionEvent)event;
				if(motionEvent.getAction()==MotionEvent.ACTION_UP){
					Intent intent =new Intent("com.rp.ACTION_UP");
					mContext.sendBroadcast(intent);
					Log.i("gyx","MotionEvent.ACTION_UP");
				}
			}
			
        }

        @Override
        public void onBatchedInputEventPending() {
            if (mUnbufferedInputDispatch) {
                super.onBatchedInputEventPending();
            } else {
                scheduleConsumeBatchedInput();
            }
        }

        @Override
        public void dispose() {
            unscheduleConsumeBatchedInput();
            super.dispose();
        }
    }

 WindowInputEventReceiver,这个广播会接受到系统的各种事件,按键,触摸等,一旦有触摸或者按键事件,onInputEvent方法就会响应,这要在这里面检测,通过计算就可以知道用户多长事件无操作。我在这里当用户按键事件抬起的时候发送广播

    //add by gyx
    static final class CheckRunnable implements Runnable {
        @Override
        public void run() {
            if (!isForeground()) {
                Intent startIntent = new Intent();
                ComponentName componentName = new ComponentName("com.sayesInternet.yunkangbao", "activity为com.sayesinternet.yunkangbao.ui.WelcomeActivity");
                startIntent.setComponent(componentName);
                mContext.startActivity(startIntent);
            }
        }
    }

    private static boolean isForeground() {
        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        String currentPackageName = cn.getPackageName();
        if (!TextUtils.isEmpty(currentPackageName) && currentPackageName.equals("com.qingniu.sharescale")) {
            Log.i("gyx", "isForeground");
            return true;
        }
        Log.i("gyx", "not Foreground");
        return false;

    }


    final static CheckRunnable mCheckRunnable = new CheckRunnable();

    //end

接收端处理事件
 

if (action.equals("com.rp.ACTION_UP")) {
           mHandler.removeCallbacks(mCheckRunnable);
            mHandler.postDelayed(mCheckRunnable, 60 * 1000);
   }

这样就大功告成了

你可能感兴趣的:(android)