gpt4 book ai didi

android - 应用程序空闲时间

转载 作者:IT老高 更新时间:2023-10-28 23:02:16 26 4
gpt4 key购买 nike

在我的应用程序中有三个 Activity A -> B -> C -> A。我想检测应用程序的空闲时间,以便在 15 分钟后无论 Activity 如何都会弹出一条消息。实现这一点的最佳方法是什么。

最佳答案

我会这样做:

  1. 创建将控制空闲 Activity 的线程
  2. 在应用环境中运行这个线程
  3. 在每次用户交互时只刷新空闲时间

用于存储控制空闲时间的全局线程的类

public class ControlApplication extends Application
{
private static final String TAG=ControlApplication.class.getName();
private Waiter waiter; //Thread which controls idle time

// only lazy initializations here!
@Override
public void onCreate()
{
super.onCreate();
Log.d(TAG, "Starting application"+this.toString());
waiter=new Waiter(15*60*1000); //15 mins
waiter.start();
}

public void touch()
{
waiter.touch();
}
}

将成为您所有 Activity 的父级的类

public class ControlActivity extends Activity
{
private static final String TAG=ControlActivity.class.getName();

/**
* Gets reference to global Application
* @return must always be type of ControlApplication! See AndroidManifest.xml
*/
public ControlApplication getApp()
{
return (ControlApplication )this.getApplication();
}

@Override
public void onUserInteraction()
{
super.onUserInteraction();
getApp().touch();
Log.d(TAG, "User interaction to "+this.toString());
}

}

最后是线程本身

public class Waiter extends Thread
{
private static final String TAG=Waiter.class.getName();
private long lastUsed;
private long period;
private boolean stop;

public Waiter(long period)
{
this.period=period;
stop=false;
}

public void run()
{
long idle=0;
this.touch();
do
{
idle=System.currentTimeMillis()-lastUsed;
Log.d(TAG, "Application is idle for "+idle +" ms");
try
{
Thread.sleep(5000); //check every 5 seconds
}
catch (InterruptedException e)
{
Log.d(TAG, "Waiter interrupted!");
}
if(idle > period)
{
idle=0;
//do something here - e.g. call popup or so
}
}
while(!stop);
Log.d(TAG, "Finishing Waiter thread");
}

public synchronized void touch()
{
lastUsed=System.currentTimeMillis();
}

public synchronized void forceInterrupt()
{
this.interrupt();
}

//soft stopping of thread
public synchronized void stop()
{
stop=true;
}

public synchronized void setPeriod(long period)
{
this.period=period;
}

}

关于android - 应用程序空闲时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4075180/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com