按键后,android检测用户不活动状态

时间:2014-09-17 06:01:04

标签: android user-interaction

在我的媒体播放器中,我添加了一个显示如果按下菜单键的视图,我希望它在一段时间后隐藏,即用户不想看到视图,视图是水平的,我想要它在几秒钟后隐藏,用户不会按向右或向左键。

我把我的逻辑放在这里,但它没有成功: “我的观点类似于”

 @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        super.onKeyDown(keyCode, event);
        lastUsed = System.currentTimeMillis();



case KeyEvent.KEYCODE_MENU:

                similar.setVisibility(View.VISIBLE);
                similar.bringToFront();
                similar.requestFocus();
                similar.bringToFront();
                nowHide()
}
public void nowHide(){
    new Thread(new Runnable() {
               public void run() {

                   while(true){
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {

                        e.printStackTrace();
                    } 

                      if(getLastInteractionTime()+5000 >= System.currentTimeMillis())
                      {
                          Log.d("MOVIE PLAY ACTIVITY:SADIP", "check time success");

                          runOnUiThread(new Runnable() {
                            public void run() {
                                similar.setVisibility(View.GONE);
                            }
                          });

                      }
                                            }
               }
                 }).start();
               }



 public long getLastInteractionTime() {
       return lastUsed;
    }

    public long setLastInteractionTime(int lastInteraction) {
       lastUsed = lastInteraction;
       return lastUsed;
    }

代码从未到达

if(getLastInteractionTime()+5000 >= System.currentTimeMillis())

而且我也没有想到停止这个帖子

我该怎么做? 任何其他方法将不胜感激 提前谢谢。

1 个答案:

答案 0 :(得分:8)

试试这个。它将在5秒后通过用户的吐司通知。 onUserInteraction 方法是此代码的主要部分。

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