programing

다른 클래스에서 현재 또는 주요 활동을 참조하는 방법

nicescript 2021. 1. 16. 09:18
반응형

다른 클래스에서 현재 또는 주요 활동을 참조하는 방법


일부 활동을 참조해야하는 메서드에 액세스해야하는 경우가 종종 있습니다. 예를 들어를 사용 getWindowManager하려면 일부 활동에 액세스해야합니다. 그러나 종종 이러한 메서드를 사용하는 코드는 활동에 대한 참조가없는 다른 클래스에 있습니다. 지금까지 주 활동에 대한 참조를 저장하거나 일부 활동의 컨텍스트를 클래스에 전달했습니다. 이 작업을 수행하는 더 좋은 방법이 있습니까?


이미 유효한 컨텍스트가있는 경우 다음을 사용하십시오. Activity activity = (Activity) context;


컨텍스트를 전달하는 것이 굴절 활동에 더 좋은 방법입니다.

Context를 다른 클래스에 전달할 수 있습니다.

IN 활동 ::

AnotherClass Obj  = new AnotherClass(this);

다른 수업에서

class AnotherClass{

public AnotherClass(Context Context){

    }

}

활동에 필요한 메소드를 구현하고 Handler를 구현할 수 있습니다 . 그런 다음 핸들러 인스턴스를 클래스에 전달하면 핸들러에 대한 메시지를 가져 와서 대상으로 보낼 수 있습니다.


나는 포럼에서 논의하지 않은 비 활동 클래스에 활동을 가져 오는 방법을 찾았습니다. 이것은 getApplicationContext ()를 사용하고 컨텍스트를 생성자에 매개 변수로 전달하려는 시도가 여러 번 실패한 후였으며, 어느 것도 Activity를 제공하지 않았습니다. 내 어댑터가 들어오는 컨텍스트를 Activity로 캐스팅하는 것을 보았으므로 비 활동 클래스 생성자에도 동일한 캐스트를 만들었습니다.

public class HandleDropdown extends Application{
...
    public Activity activity;
...
public HandleDropdown() {
    super();
}
public HandleDropdown(Activity context) {
    this.activity = context;
    this.context = context;
}
public void DropList(View v,Activity context) {
    this.activity = context;
    this.context = context; 
...
}

Context를 Activity로 캐스트 변환 한 후 Activity 컨텍스트가 필요한 곳에서 this.activity를 사용할 수 있습니다.


활동 커뮤니케이션에는 여러 가지 방법이 있습니다.

당신이 사용할 수있는:

  • startActivityForResult 메서드

  • 브로드 캐스트 메시지 및 수신기 시스템 (실제 활동에서 이벤트를 브로드 캐스트하고 대상 활동에 수신기를 등록 할 수 있습니다. 대상 활동은 이전에 초기화되고 완료되지 않았어야 함)

  • 당신이 말했듯이, 당신이 필요로 할 때마다 대상 활동의 참조를 저장하십시오.

애플리케이션 인스턴스를 싱글 톤으로 만들고 컨텍스트가 필요할 때 사용할 수 있습니다.

이 질문에 예가 있습니다.
Android Application as Singleton

이렇게하면 Context가 필요할 때 다음과 같이 얻을 수 있습니다.
Context context = MyApplication.getInstance()

이것은 가장 깨끗한 솔루션이 아닐 수도 있지만 지금까지는 잘 작동했습니다.


우리는이를위한 프레임 워크를 구축했습니다. BaseActivity상속 클래스 가 있으며 Activity모든 수명주기 메서드를 재정의하고 활동 스택을 추적하는 일부 정적 (클래스) 변수가 있습니다. 현재 활동이 무엇인지 알고 싶은 것이 있으면 BaseActivity비공개로 관리되는 스택 위에 활동을 반환 하는 정적 메서드를 호출하기 만하면 됩니다.

약간 해키이지만 작동합니다. 그래도 추천 할 수 있을지 모르겠습니다.


나는 안드로이드를 처음 사용하기 때문에 내 제안이 어리석은 것처럼 보일 수 있지만 활동에 대한 참조를 개인 속성으로 만들고 OnCreate 메서드에 할당하면 어떻게 될까요? OnCreate를 사용하여 CustomActivity를 생성하고 adnroid에서 제공하는 일반 활동이 아닌 CustomActivity에서 모든 활동을 파생시킬 수도 있습니다.

class blah extends Activity{
  private Activity activityReference;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityReference = this;
    }

}
그 후에는 원하는 방식으로 사용할 수 있습니다.

Intent i = new Intent(activityReference, SomeOtherActivity.class)

기타


이러한 메서드를 수행하려는 클래스에서 인 텐트를 처리하고 다음과 같이 번들로 정보를 보냅니다.

    Intent i = new Intent("android.intent.action.MAIN");
    i.setComponent(new ComponentName("com.my.pkg","com.my.pkg.myActivity"));
    Bundle data = new Bundle();

    i.putExtras(data);

    startActivityForResult(i);

그런 다음 OnActivityResultListener를 사용하여 새 데이터를 가져옵니다.


싱글 톤 클래스가 멤버로 아래 클래스의 인스턴스를 갖도록하여이 문제를 해결했습니다.

public class InterActivityReferrer <T> {
    HashMap<Integer, T> map;
    ArrayList<Integer> reserve;

    public InterActivityReferrer() {
        map = new HashMap<>();
        reserve = new ArrayList<>();
    }

    public synchronized int attach(T obj) {
        int id;
        if (reserve.isEmpty()) {
            id = reserve.size();
        }
        else {
            id = reserve.remove(reserve.size() - 1);
        }

        map.put(id, obj);
        return id;
    }

    public synchronized T get(int id) {
        return map.get(id);
    }

    public synchronized T detach(int id) {
        T obj = map.remove(id);
        if (obj != null) reserve.add(id);
        return obj;
    }
}

이 클래스는 T 객체를 가져오고 attach ()에 의해 객체에 할당 된 고유 한 정수를 반환 할 수 있습니다. 할당 된 정수는 HashMap이 실패하지 않는 한 서로 충돌하지 않습니다. 해당 객체가 detach ()에 의해 분리되면 할당 된 각 정수가 해제됩니다. 해제 된 정수는 새 개체가 연결될 때 다시 사용됩니다.

그리고 싱글 톤 클래스에서 :

public class SomeSingleton {
    ...
    private InterActivityReferrer<Activity> referrer = new InterActivityReferrer<>();
    ...
    public InterActivityReferrer<Activity> getReferrer() {return referrer;}
}

참조해야하는 활동에서 :

    ...
    int activityID = SomeSingleton.getInstance().getReferrer().attach(this);
    ...

이제이 활동 인스턴스에 해당하는 고유 한 정수가 리턴됩니다. Intent 및 putExtra ()를 사용하여 정수를 다른 시작 활동에 전달할 수 있습니다.

    ...
    Intent i = new Intent(this, AnotherActivity.class);
    i.putExtra("thisActivityID", activityID);
    startActivityForResult(i, SOME_INTEGER);
    ...

And from the another activity:

    ...
    id refereeID = getIntent().getIntExtra("thisActivityID", -1);
    Activity referredActivity = SomeSingleton.getInstance().getReferrer().get(refereeID);
    ...

And finally the activity can be referred. And InterActivityReferrer can be used for any other class.

I hope this helps.


public static Activity getLaunchActivity()
{
    final Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");

    final Method methodApp = activityThreadClass.getMethod("currentApplication");
    App = (Application) methodApp.invoke(null, (Object[]) null);
    Intent launcherIntent = App.getPackageManager().getLaunchIntentForPackage(App.getPackageName());
    launchActivityInfo = launcherIntent.resolveActivityInfo(App.getPackageManager(), 0);
    Class<?> clazz;
    try
    {
        clazz = Class.forName(launchActivityInfo.name);
        if(clazz != null)
            return Activity.class.cast(clazz.newInstance());
    }
    catch (Exception e)
    {}

    return null;
}

Just a guess since I haven't done this but it might work.

1) Get your applicationContext by making your Android Application class a Singleton.

2) Get your ActivityManager class from the context.

3) Get a list of RunningTaskInfos using getRunningTasks() on the ActivityManager.

4) Get the first RunningTaskInfo element from the list which should be the most recent task launched.

5) Call topActivity on that RunningTaskInfo which should return you the top activity on the activity stack for that task.

Now, this seems like a LOT more work than any of the other methods mentioned here, but you can probably encapsulate this in a static class and just call it whenever. It seems like it might be the only way to get the top activity on the stack without adding references to the activities.

ReferenceURL : https://stackoverflow.com/questions/11227591/how-to-reference-the-current-or-main-activity-from-another-class

반응형