Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách phát hiện ứng dụng Android chuyển nền (background) và về trước (foreground)

Giới thiệu

Ví dụ này trình bày cách kiểm tra xem ứng dụng đang ở trạng thái foreground (trước mặt) hay background (chạy ngầm). Lưu ý: Cách dùng ActivityManager.getRunningTasks() trong ví dụ gốc đã bị deprecated từ API 21 (Android 5.0) và không còn hoạt động tin cậy trên các phiên bản mới. Bài viết này cung cấp cả cách cũ (tham khảo) và cách hiện đại.

Cách cũ (Deprecated - chỉ dùng cho API < 21)

Bước 1: Tạo dự án & Giao diện

Tương tự các ví dụ trước. Layout chỉ cần một TextView hiển thị trạng thái.

Bước 2: Code cũ (MainActivity.java)

// CHỈ DÙNG CHO API < 21 - KHÔNG KHUYẾN NGHỊ
public class MainActivity extends FragmentActivity {
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.text);

        if (!isApplicationBroughtToBackground()) {
            textView.setText("Ứng dụng đang ở Foreground");
        } else {
            textView.setText("Ứng dụng đang ở Background");
        }
    }

    @SuppressWarnings("deprecation")
    private boolean isApplicationBroughtToBackground() {
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            return !topActivity.getPackageName().equals(getPackageName());
        }
        return false;
    }
}

Cách hiện đại (Khuyến nghị - API 14+)

Sử dụng ComponentCallbacks2 và onTrimMemory() hoặc ProcessLifecycleOwner (từ Android Architecture Components).

Cách 1: Sử dụng ProcessLifecycleOwner (Lifecycle 2.0+)

// build.gradle (app)
dependencies {
    implementation "androidx.lifecycle:lifecycle-process:2.6.0"
}

// Application class
public class MyApplication extends Application implements LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onAppForeground() {
        // App về foreground
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onAppBackground() {
        // App vào background
    }
}

// Trong Manifest: android:name=".MyApplication"

Cách 2: ComponentCallbacks2 (Không cần thư viện thêm)

public class MyApplication extends Application implements ComponentCallbacks2 {
    private boolean isInBackground = false;

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
            isInBackground = true;
            // App vào background
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }

    public boolean isInBackground() {
        return isInBackground;
    }
}

Khi cần kiểm tra: ((MyApplication) getApplication()).isInBackground().

Chạy ứng dụng (với code cũ)

Kết nối thiết bị, nhấn Run. Trên Android 4.4 và cũ hơn, TextView sẽ hiển thị trạng thái chính xác. Trên Android 5.0+, kết quả không đáng tin cậy.

Cách phát hiện ứng dụng Android chuyển nền (background) và về trước (foreground)

Tóm tắt

  • Không dùng getRunningTasks() cho app sản xuất.
  • Dùng ProcessLifecycleOwner (Lifecycle) cho giải pháp chuẩn, hiện đại.
  • Dùng ComponentCallbacks2 nếu không muốn thêm dependency.