简体   繁体   中英

Which structure for my Android Application?

I did a lot of research, but I didn't get through it, so that i don't know how to realize my App. The App consists of 2+ Activities, that contain content, that should be updated by a service in the background. So I dont know how to do the connection, some say i should do ipc, but others say thats too much of work, as long as service and activites run within the same process. I concerned to easily create methods like ActivityOne.RefreshData(Data data) and call those within the service, but i did not manage to get it work until now. I hope you have some suggestions to me and sorry for my bad english!

cheers

If you only need to provide data/updates to your own activities then IPC is most certainly not needed.

To achieve this, I would reverse the orientation you seem to be describing and rather than have the service calling methods on the activity, have it pushing messages to a Handler provided to it by the Activity when/if it starts.

See: http://developer.android.com/reference/android/os/Handler.html

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

Note that if what you need to send from the service to activites is always the same type of object, you can simplify your implementation of handleMessage() by using the Message.obj field to hold your type and not bother with Bundles or parcelling. As in:

Handler impl in activity where NotificationModel is the type that the service always sends:

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

The service side of posting msgs to this handler looks like:

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);
    }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM