0

我做了很多研究,但我没有通过它,所以我不知道如何实现我的应用程序。该应用程序由 2 个以上的活动组成,其中包含应由后台服务更新的内容。所以我不知道如何进行连接,有人说我应该做 ipc,但其他人说那工作量太大,只要服务和活动在同一个进程中运行。我关心轻松创建像 ActivityOne.RefreshData(Data data) 这样的方法并在服务中调用这些方法,但直到现在我才设法让它工作。我希望你对我有一些建议,并为我糟糕的英语感到抱歉!

干杯

4

1 回答 1

1

如果您只需要为自己的活动提供数据/更新,那么肯定不需要 IPC。

为了实现这一点,我将反转您似乎正在描述的方向,而不是让服务调用活动上的方法,让它在/如果它启动时将消息推送到活动提供给它的处理程序。

请参阅:http: //developer.android.com/reference/android/os/Handler.html

http://mobileorchard.com/android-app-developmentthreading-part-1-handlers/

请注意,如果您需要从服务发送到 activites 始终是相同类型的对象,您可以通过使用 Message.obj 字段来保存您的类型来简化您的 handleMessage() 实现,而不用打扰 Bundles 或 parcelling。如:

处理程序 impl 在 NotificationModel 是服务始终发送的类型的活动中:

private Handler mNotificationListener = new Handler(){
     @Override
      public void handleMessage(Message msg) {
         handleIncomingNotification((NotificationModel)msg.obj);
         }
    };

将消息发布到此处理程序的服务端如下所示:

public class NotificationRouter {

    private Application mContext;
    private SparseArray<Handler> mListeners = new SparseArray<Handler>();

    public NotificationRouter (Application app){
    this.mContext = app;
    }

    public void registerListener(Handler handler){
    mListeners.put(handler.hashCode(), handler);
    }

    public void unRegisterListener(Handler handler){
    mListeners.remove(handler.hashCode());
    }

    public void post(NotificationModel notice){
    Message m = new Message();
    m.obj = notice;
    for (int i = 0; i < mListeners.size(); i++){
        Handler h = mListeners.valueAt(i);
        h.sendMessage(m);
    }
    }
}
于 2012-08-25T16:17:22.230 回答