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

Cách lấy Context của Activity đang chạy ở foreground trong Android?

Giới thiệu

Bài viết hướng dẫn cách lấy Context của Activity đang hiển thị (foreground) thông qua lớp Application tùy chỉnh. Kỹ thuật này hữu ích khi cần truy cập Context toàn cục từ bất kỳ đâu trong ứng dụng.

Các bước thực hiện

Bước 1: Tạo dự án mới

Tạo project Android Studio như bình thường.

Bước 2: Tạo lớp Application tùy chỉnh (src/MyApp.java)

package app.tutorialspoint.com.sample;

import android.app.Activity;
import android.app.Application;

public class MyApp extends Application {
    private Activity mCurrentActivity = null;

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

    public Activity getCurrentActivity() {
        return mCurrentActivity;
    }

    public void setCurrentActivity(Activity mCurrentActivity) {
        this.mCurrentActivity = mCurrentActivity;
    }
}

Bước 3: Tạo BaseActivity để theo dõi vòng đời (src/MyBaseActivity.java)

package app.tutorialspoint.com.sample;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class MyBaseActivity extends AppCompatActivity {
    protected MyApp mMyApp;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMyApp = (MyApp) this.getApplicationContext();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMyApp.setCurrentActivity(this);
    }

    @Override
    protected void onPause() {
        clearReferences();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        clearReferences();
        super.onDestroy();
    }

    private void clearReferences() {
        Activity currActivity = mMyApp.getCurrentActivity();
        if (this.equals(currActivity)) {
            mMyApp.setCurrentActivity(null);
        }
    }
}

Bước 4: Sử dụng trong MainActivity (src/MainActivity.java)

package app.tutorialspoint.com.sample;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Activity currentActivity = ((MyApp) getApplicationContext()).getCurrentActivity();
        // currentActivity giờ đây giữ tham chiếu đến Activity foreground
    }
}

Bước 5: Đăng ký trong AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.tutorialspoint.com.sample">
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <application
        android:name=".MyApp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MyBaseActivity" />
    </application>
</manifest>

Lưu ý quan trọng

  • Tất cả Activity cần truy cập foreground context nên kế thừa từ MyBaseActivity
  • Cơ chế tự động xóa tham chiếu trong onPause/onDestroy tránh memory leak
  • Phương pháp này thay thế cho các singleton context cũ dễ gây rò rỉ bộ nhớ