介紹
ActivityManager
public boolean isForeground(String PackageName){
// Get the Activity Manager
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
// Get a list of running tasks, we are only interested in the last one,
// the top most so we give a 1 as parameter so we only get the topmost.
List< ActivityManager.RunningTaskInfo > task = manager.getRunningTasks(1);
// Get the info we need for comparison.
ComponentName componentInfo = task.get(0).topActivity;
// Check if it matches our package name.
if(componentInfo.getPackageName().equals(PackageName)) return true;
// If not then our app is not on the foreground.
return false;
}
static variable
public class example extends Activity {
static boolean isActive = false;
@Override
protected void onStart() {
super.onStart();
isActive = true;
}
@Override
protected void onStop() {
super.onStop();
isActive = false;
}
}
當activity在屏幕最前端是這樣寫的,如果被其他界面覆蓋了,activity是stop了的,所以也可以寫在onCreate()和onDestory()裏
利:非常簡便的代碼
shared preferences
public class example extends Activity {
@Override
protected void onStart() {
super.onStart();
// Store our shared preference
SharedPreferences sp = getSharedPreferences("OURINFO", MODE_PRIVATE);
Editor ed = sp.edit();
ed.putBoolean("active", true);
ed.commit();
}
@Override
protected void onStop() {
super.onStop();
// Store our shared preference
SharedPreferences sp = getSharedPreferences("OURINFO", MODE_PRIVATE);
Editor ed = sp.edit();
ed.putBoolean("active", false);
ed.commit();
}
}
利:shared preferences 不會被android銷燬
利:shared preferences 不會被重置成默認值
利:
你可以有很高的控制權並很容易的按照你的實現將Activity分類,就如同最上層Activity這麼一個分類結論
異常處理
final Thread.UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
// fix our issues for static variables
isActive = false;
// fix our issues for sharedpreferences
SharedPreferences sp = getSharedPreferences("OURINFO", MODE_PRIVATE);
Editor ed = sp.edit();
ed.putBoolean("active", false);
ed.commit();
// Handle everthing else
defaultHandler.uncaughtException(thread, throwable);
}
});