Bar*_*ica 63
我会这样做:
用于存储全局线程的类,用于控制空闲时间
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();
}
}
Run Code Online (Sandbox Code Playgroud)
将成为您所有活动的父级的班级
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());
}
}
Run Code Online (Sandbox Code Playgroud)
最后是Thread本身
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;
}
}
Run Code Online (Sandbox Code Playgroud)
所以我个人会使用AlarmService.您可以指定将启动显示对话框的活动的PendingIntent.在应该重新启动计时器的任何事件之后,您只需取消pendingIntent并重新注册它.
| 归档时间: |
|
| 查看次数: |
22075 次 |
| 最近记录: |