通过重写一个继承自Activity的基类中的onUserLeaveHint()方法,当用户按Home键等操作使程序进入后台时即开始计时,当用户使程序恢复为前台显示时执行onResume()方法,在其中判断是否超时.
public class BaseActivity extends Activity {
private static final String TAG = "z";
private static SharedPreferences pref;
private static boolean isLeave = false; public OfficeBaseActivity() {
super();
// TODO Auto-generated constructor stub
} @Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
pref = getSharedPreferences("timeoutcheck", Context.MODE_PRIVATE);
} @Override
protected void onUserLeaveHint() { //当用户按Home键等操作使程序进入后台时即开始计时
// TODO Auto-generated method stub
super.onUserLeaveHint();
if(!isLeave){
isLeave=true;
saveStartTime();
}
} @Override
protected void onResume() { //当用户使程序恢复为前台显示时执行onResume()方法,在其中判断是否超时.
// TODO Auto-generated method stub
super.onResume();
if(isLeave){
isLeave=false;
timeOutCheck();
}
} public void timeOutCheck() {
long endtime = System.currentTimeMillis();
Log.i(TAG, "endtime == " + endtime);
Log.i(TAG, "starttime == " + getStartTime());
Log.i(TAG, "endtime - getStartTime == " + (endtime - getStartTime()));
if (endtime - getStartTime()>= 30 * 1000){
Toast.makeText(this, "超时了", Toast.LENGTH_SHORT).show();
}
} public void saveStartTime() {
pref.edit().putLong("starttime", System.currentTimeMillis()).commit();
} public long getStartTime() {
return pref.getLong("starttime", 0); } }