在 onCreate 方法中传递 Activity 上下文

Pass Activity context in onCreate method

我需要在构建 activity 后立即将 activity 上下文传递给我的服务。这是我的代码:

public class myService extends Service
{
    private AppCompatActivity activity;

    public void setActivity(AppCompatActivity activity)
    {
        this.activity = activity;
    }
}

public class myActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // ... some things are being executed and myService is being bound
        mService.setActivity(this);
    }
}

我得到 NullPointerException 因为 - 我想 - myActivity class 仍在构造中,无法传递引用。在onCreate之后如何使Android运行这个方法?我找到了一些涉及工厂模式的 Java 解决方案,但我不确定如何使用它,如果我可以在我的案例中使用它的话。

Service 本身就是一个上下文。所以如果你只需要 Context,你可以在 Serviceclass.

中调用 this

或者,您应该在启动服务之前将 Activity 传递给该服务。确保在调用 super.onCreate(bundle);

后传递 Activity

但是,您不应操纵您的 ActivityService 的观点。更好的方法是 通过 Service.

通知 您的 Activity

Notify activity from service

编辑:观察者模式

创建一个名为 NotificationCenter.java

的新 class
public class NotificationCenter {

    private static int totalEvents = 1;

    public static final int updateActivity = totalEvents++;
    // you can add more events
    // public static final int anotherEvent = totalEvents++;

    private final SparseArray<ArrayList<Object>> observers = new SparseArray<>();
    private final SparseArray<ArrayList<Object>> removeAfterBroadcast = new SparseArray<>();
    private final SparseArray<ArrayList<Object>> addAfterBroadcast = new SparseArray<>();

    private int broadcasting = 0;

    public interface NotificationCenterDelegate {
        void didReceivedNotification(int id, Object... args);
    }

    private static volatile NotificationCenter Instance = null;

    public static NotificationCenter getInstance() {
        NotificationCenter localInstance = Instance;
        if (localInstance == null) {
            synchronized (NotificationCenter.class) {
                localInstance = Instance;
                if (localInstance == null) {
                    Instance = localInstance = new NotificationCenter();
                }
            }
        }
        return localInstance;
    }

    public void postNotificationName(int id, Object... args) {
        broadcasting++;
        ArrayList<Object> objects = observers.get(id);
        if (objects != null && !objects.isEmpty()) {
            for (int a = 0; a < objects.size(); a++) {
                Object obj = objects.get(a);
                ((NotificationCenterDelegate) obj).didReceivedNotification(id, args);
            }
        }
        broadcasting--;
        if (broadcasting == 0) {
            if (removeAfterBroadcast.size() != 0) {
                for (int a = 0; a < removeAfterBroadcast.size(); a++) {
                    int key = removeAfterBroadcast.keyAt(a);
                    ArrayList<Object> arrayList = removeAfterBroadcast.get(key);
                    for (int b = 0; b < arrayList.size(); b++) {
                        removeObserver(arrayList.get(b), key);
                    }
                }
                removeAfterBroadcast.clear();
            }
            if (addAfterBroadcast.size() != 0) {
                for (int a = 0; a < addAfterBroadcast.size(); a++) {
                    int key = addAfterBroadcast.keyAt(a);
                    ArrayList<Object> arrayList = addAfterBroadcast.get(key);
                    for (int b = 0; b < arrayList.size(); b++) {
                        addObserver(arrayList.get(b), key);
                    }
                }
                addAfterBroadcast.clear();
            }
        }
    }

    public void addObserver(Object observer, int id) {
        if (broadcasting != 0) {
            ArrayList<Object> arrayList = addAfterBroadcast.get(id);
            if (arrayList == null) {
                arrayList = new ArrayList<>();
                addAfterBroadcast.put(id, arrayList);
            }
            arrayList.add(observer);
            return;
        }
        ArrayList<Object> objects = observers.get(id);
        if (objects == null) {
            observers.put(id, (objects = new ArrayList<>()));
        }
        if (objects.contains(observer)) {
            return;
        }
        objects.add(observer);
    }

    public void removeObserver(Object observer, int id) {
        if (broadcasting != 0) {
            ArrayList<Object> arrayList = removeAfterBroadcast.get(id);
            if (arrayList == null) {
                arrayList = new ArrayList<>();
                removeAfterBroadcast.put(id, arrayList);
            }
            arrayList.add(observer);
            return;
        }
        ArrayList<Object> objects = observers.get(id);
        if (objects != null) {
            objects.remove(observer);
        }
    }
}

然后让你的Activities看起来像这样,你会收到来自didReceivedNotification()Service的消息

public class YourActivity implements NotificationCenter.NotificationCenterDelegate {

    @Override
    public void onPause() {
        NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateActivity);
        super.onPause();
    }

    @Override
    public void onResume() {
        NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateActivity);
        super.onResume();
    }

    @Override
    public void didReceivedNotification(int id, Object... args) {
        if (id == NotificationCenter.updateActivity) {
            // do something with your activity, your service called this
        }
    }
}

最后将您 Service 中的消息发送给所有正在收听的 Activities

NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateActivity, optionalData);

非常好,您不必传递 Activity 个实例。

NotificationCenter 来源来自 Telegram。

public class myService extends Service
{
 public static myActivity activity;

 public static void setActivity(myActivity activity)
 {
     this.activity = activity;
 }
 public void useActivityExample()
{
  myService.myActivity.update();
 }
}

public class myActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
   {
       // ... some things are being executed and myService is being bound
      mService.setActivity(getActivity());
   }
}