android detect user inactivity after key pressed

拟墨画扇 提交于 2019-12-05 15:05:48

Try this. It will notify with a toast on user inactive after 5 seconds. onUserInteraction method is the main part of this code.

Handler handler;
Runnable r;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    handler = new Handler();
    r = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            Toast.makeText(MainActivity.this, "user inactive",
                    Toast.LENGTH_SHORT).show();
        }
    };
    startHandler();
}
@Override
public void onUserInteraction() {
    // TODO Auto-generated method stub
    super.onUserInteraction();
    stopHandler();//stop first and then start
    startHandler();
}
public void stopHandler() {
    handler.removeCallbacks(r);
}

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