如何判断Android应用当前是否被用户使用?解决后台或关闭状态识别问题
Hey Ahmad, great question! Tracking user online/offline status in Android needs more than just the onCreate method—you need to account for app backgrounding, foregrounding, and closure scenarios. Let’s walk through the most reliable approaches:
The best way to cover all cases (regardless of which Activity the user is in) is to use Application.ActivityLifecycleCallbacks to monitor when your app enters the foreground or background. Here’s how to implement it:
Step 1: Create a Custom Application Class
This class will track active activities and trigger status updates when the app moves between foreground/background:
public class MyApp extends Application implements Application.ActivityLifecycleCallbacks { private int activeActivityCount = 0; private boolean isAppInForeground = false; @Override public void onCreate() { super.onCreate(); registerActivityLifecycleCallbacks(this); } @Override public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {} @Override public void onActivityStarted(@NonNull Activity activity) { activeActivityCount++; // Trigger when app comes back to foreground if (!isAppInForeground) { makeMeOnline(); isAppInForeground = true; } } @Override public void onActivityResumed(@NonNull Activity activity) {} @Override public void onActivityPaused(@NonNull Activity activity) {} @Override public void onActivityStopped(@NonNull Activity activity) { activeActivityCount--; // Trigger when app goes to background (no active activities left) if (activeActivityCount == 0) { makeMeOffline(); isAppInForeground = false; } } @Override public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {} @Override public void onActivityDestroyed(@NonNull Activity activity) {} // Your existing online logic private void makeMeOnline() { Log.d("UserStatus", "User marked as online"); // Add your API call or local storage update here } // New offline logic for background/closure private void makeMeOffline() { Log.d("UserStatus", "User marked as offline"); // Add your API call or local storage update here } }
Step 2: Register the Application in Manifest
Add your custom application class to AndroidManifest.xml so it’s initialized when the app starts:
<application android:name=".MyApp" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" ...> <!-- Your activities go here --> </application>
- App closure: When the user swipes your app away from recent tasks, all activities will be destroyed, triggering
onActivityStoppedand setting the user to offline. - System kills: If the system terminates your app due to low memory,
makeMeOfflinewon’t run. To handle this, you can:- Use a periodic heartbeat API call to confirm the user’s status.
- Update the user’s status to offline when they next open the app (since you’ll know they were inactive).
If your app only has one Activity, you can use its lifecycle methods, but note this won’t work if you add more activities later:
@Override protected void onResume() { super.onResume(); // Re-mark online if user comes back to this Activity makeMeOnline(); } @Override protected void onPause() { super.onPause(); // Check if the app is moving to background if (isAppGoingToBackground(this)) { makeMeOffline(); } } // Deprecated in API 21, but works for older devices private boolean isAppGoingToBackground(Context context) { ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1); if (!tasks.isEmpty()) { ComponentName topActivity = tasks.get(0).topActivity; return !topActivity.getPackageName().equals(context.getPackageName()); } return false; }
The global lifecycle approach is far more robust and future-proof, so it’s the way to go for most apps.
内容的提问来源于stack exchange,提问作者Ahmad Sabbagh

