我想检查设备空闲状态几分钟。我特别活动时能够得到。如下所示
public class MainActivity extends AppCompatActivity {
Handler handler;
Runnable r;
private ContentResolver contentResolver;
@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 is inactive from last 10 seconds", 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, 10000); //for 10 seconds
}
}
但是我想检查整个应用程序的设备空闲状态。在应用程序类中检查没有方法 onUserInteraction() 还有其他任何技巧吗?
答案 0 :(得分:2)
我认为您应该创建一个BaseActivity,它将扩展AppCompatActivity并将您的代码放在BaseActivity中,并在AppCompatActivity的所有活动中替换它。我希望它会对你有所帮助。
答案 1 :(得分:0)
在应用程序类中创建3个方法, 并在该方法中重置activityVisible变量的值
public static boolean activityVisible; // Variable that will check the current activity state
public static boolean isActivityVisible() {
return activityVisible; // return true or false
}
public static void activityResumed() {
activityVisible = true;// this will set true when activity resumed
}
public static void activityPaused() {
activityVisible = false;// this will set false when activity paused
}
您可以按照以下方式调用这些方法
AppClass.activityResumed();// On Resume notify the Application
AppClass.activityPaused();// On Pause notify the Application
当活动可见时执行操作
boolean isVisible = AppClass.isActivityVisible();