android有应用程序状态,如背景还是前(前景)?
基本上每当我的应用程序进入后台(按下主页按钮)时,如果我重新打开它(使其进入前台)我想对我的网络服务器进行asyc调用,就像ping到我的网络服务器一样。它应该在哪个活动中存在。
我不能使用Activity生命周期方法,因为它们只适用于活动。我想要在整个应用程序级别上工作/行为的东西。感谢
答案 0 :(得分:1)
我不确定你的问题,但我认为你可以拥有一个BaseActivity并从那个派生出来然后onResume()将永远被调用吗?
答案 1 :(得分:0)
简单的答案是不,android没有提供这样的状态。
经过大量研究后,我找到了一个可靠而简单的解决方案:
public class ApplicationLifecycleHandler implements Application.ActivityLifecycleCallbacks, ComponentCallbacks2 {
private static final String TAG = ApplicationLifecycleHandler.class.getSimpleName();
private static boolean isInBackground = false;
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
Adjust.onResume();
if(isInBackground){
Log.d(TAG, "app went to foreground");
isInBackground = false;
}
}
@Override
public void onActivityPaused(Activity activity) {
Adjust.onPause();
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
@Override
public void onConfigurationChanged(Configuration configuration) {
}
@Override
public void onLowMemory() {
}
@Override
public void onTrimMemory(int i) {
if(i == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN){
Log.d(TAG, "app went to background");
isInBackground = true;
}
}
}
答案 2 :(得分:0)
我在这里写的最简单的答案是找到app是在前景还是后台。没有得到任务,没有这样的检查。但结果非常明确,并且根据需要。
public class MainApplication extends Application implements Application.ActivityLifecycleCallbacks {
private static boolean background = false;
private static int count = 0;
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(this);
}
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
}
@Override
public void onActivityStarted(Activity activity) {
if(background){
background = false;
Log.v("activityFocus", "Activity came in foreground ");
Toast.makeText(getApplicationContext(), "Foreground", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onActivityResumed(Activity activity) {
count++;
}
@Override
public void onActivityPaused(Activity activity) {
count--;
}
@Override
public void onActivityStopped(Activity activity) {
if(count==0){
Log.v("activityFocus", "Activity is in background ");
Toast.makeText(getApplicationContext(), "Background", Toast.LENGTH_SHORT).show();
background=true;
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
}