I have a solution with two projects in it. A portable areas project, and a web site that references the portable areas project, and Both reference MvcContrib.

The problem I am have is with the embedded resources, they are giving me a 404 error when I try to get to them. It seems like it's trying to access a physical path not the dll. The partial view works fine.

The file I'm trying to access looks like this inside my visual studio solution explorer

AdHocReporting/Areas/AdHocReportBuilder/Content/adhoc.css (the build action is embedded)

**Here is the routing for the portable area:**

```
using System.Web.Mvc;
using MvcContrib.PortableAreas;

namespace AdHocReporting.Areas.AdHocReportBuilder
{
    public class AdHocReportBuilderAreaRegistration : PortableAreaRegistration
    {
        public override string AreaName
        {
            get { return "AdHocReportBuilder"; }
        }

        public override void RegisterArea(AreaRegistrationContext context, IApplicationBus bus)
        {
            RegisterRoutes(context);
            RegisterAreaEmbeddedResources();

        }
        private void RegisterRoutes(AreaRegistrationContext context)
        {
            context.MapRoute(
              AreaName + "_content",
              base.AreaRoutePrefix + "/Content/{resourceName}",
              new { controller = "EmbeddedResource", action = "Index", resourcePath = "Content" },
              new[] { "MvcContrib.PortableAreas" }
          );

            context.MapRoute(
                AreaName + "_default",
                base.AreaRoutePrefix + "/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

```

**Here is the Web sites Global.aspx that has the reference to the portable area**

```
namespace AdHocReportingSite
{
    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            PortableAreaRegistration.RegisterEmbeddedViewEngine();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }
}

```

**here is an image of what my solution explore looks like:**

![Solution Explorer](https://i.stack.imgur.com/6P0TK.png)
['https://Stackoverflow.com/questions/14695580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/937294/']
See below for my original answer - that pattern has worked well, but recently I've started using a different approach to Service/Activity communication:

* Use a [bound service](https://developer.android.com/guide/components/bound-services.html) which enables the Activity to get a direct
reference to the Service, thus allowing direct calls on it, rather
than using Intents.
* Use RxJava to execute asynchronous operations.
* If the Service needs to continue background operations even when no
Activity is running, also start the service from the Application
class so that it does not get stopped when unbound.

The advantages I have found in this approach compared to the startService()/LocalBroadcast technique are

* No need for data objects to implement Parcelable - this is particularly important to me as I am now sharing code between Android and iOS (using RoboVM)
* RxJava provides canned (and cross-platform) scheduling, and easy composition of sequential asynchronous operations.
* This should be more efficient than using a LocalBroadcast, though the overhead of using RxJava may outweigh that.

Some example code. First the service:

```
public class AndroidBmService extends Service implements BmService {

    private static final int PRESSURE_RATE = 500000;   // microseconds between pressure updates
    private SensorManager sensorManager;
    private SensorEventListener pressureListener;
    private ObservableEmitter<Float> pressureObserver;
    private Observable<Float> pressureObservable;

    public class LocalBinder extends Binder {
        public AndroidBmService getService() {
            return AndroidBmService.this;
        }
    }

    private IBinder binder = new LocalBinder();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        logMsg("Service bound");
        return binder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_NOT_STICKY;
    }

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

        sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
        Sensor pressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
        if(pressureSensor != null)
            sensorManager.registerListener(pressureListener = new SensorEventListener() {
                @Override
                public void onSensorChanged(SensorEvent event) {
                    if(pressureObserver != null) {
                        float lastPressure = event.values[0];
                        float lastPressureAltitude = (float)((1 - Math.pow(lastPressure / 1013.25, 0.190284)) * 145366.45);
                        pressureObserver.onNext(lastPressureAltitude);
                    }
                }

                @Override
                public void onAccuracyChanged(Sensor sensor, int accuracy) {

                }
            }, pressureSensor, PRESSURE_RATE);
    }

    @Override
    public Observable<Float> observePressure() {
        if(pressureObservable == null) {
            pressureObservable = Observable.create(emitter -> pressureObserver = emitter);
            pressureObservable = pressureObservable.share();
        }
         return pressureObservable;
    }

    @Override
    public void onDestroy() {
        if(pressureListener != null)
            sensorManager.unregisterListener(pressureListener);
    }
} 

```

And an Activity that binds to the service and receives pressure altitude updates:

```
public class TestActivity extends AppCompatActivity {

    private ContentTestBinding binding;
    private ServiceConnection serviceConnection;
    private AndroidBmService service;
    private Disposable disposable;

    @Override
    protected void onDestroy() {
        if(disposable != null)
            disposable.dispose();
        unbindService(serviceConnection);
        super.onDestroy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.content_test);
        serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                logMsg("BlueMAX service bound");
                service = ((AndroidBmService.LocalBinder)iBinder).getService();
                disposable = service.observePressure()
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(altitude ->
                        binding.altitude.setText(
                            String.format(Locale.US,
                                "Pressure Altitude %d feet",
                                altitude.intValue())));
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                logMsg("Service disconnected");
            }
        };
        bindService(new Intent(
            this, AndroidBmService.class),
            serviceConnection, BIND_AUTO_CREATE);
    }
}

```

The layout for this Activity is:

```
<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.controlj.mfgtest.TestActivity">

        <TextView
            tools:text="Pressure"
            android:id="@+id/altitude"
            android:gravity="center_horizontal"
            android:layout_gravity="center_vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

    </LinearLayout>
</layout>

```

If the service needs to run in the background without a bound Activity it can be started from the Application class as well in `OnCreate()` using [`Context#startService()`](https://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent)).

---

**My Original Answer (from 2013):**

**In your service:** (using COPA as service in example below).

Use a LocalBroadCastManager. In your service's onCreate, set up the broadcaster:

```
broadcaster = LocalBroadcastManager.getInstance(this);

```

When you want to notify the UI of something:

```
static final public String COPA_RESULT = "com.controlj.copame.backend.COPAService.REQUEST_PROCESSED";

static final public String COPA_MESSAGE = "com.controlj.copame.backend.COPAService.COPA_MSG";

public void sendResult(String message) {
    Intent intent = new Intent(COPA_RESULT);
    if(message != null)
        intent.putExtra(COPA_MESSAGE, message);
    broadcaster.sendBroadcast(intent);
}

```

**In your Activity:** 

Create a listener on onCreate:

```
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    super.setContentView(R.layout.copa);
    receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String s = intent.getStringExtra(COPAService.COPA_MESSAGE);
            // do something here.
        }
    };
}

```

and register it in onStart:

```
@Override
protected void onStart() {
    super.onStart();
    LocalBroadcastManager.getInstance(this).registerReceiver((receiver), 
        new IntentFilter(COPAService.COPA_RESULT)
    );
}

@Override
protected void onStop() {
    LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    super.onStop();
}

```
You could use android Jetpack's [LiveData](https://developer.android.com/topic/libraries/architecture/livedata)

As per the documentation:

> 
> You can extend a `LiveData` object using the singleton pattern to wrap
> system services so that they can be shared in your app. The LiveData
> object connects to the system service once, and then any observer that
> needs the resource can just watch the LiveData object. For more
> information, see [Extend
> LiveData](https://developer.android.com/topic/libraries/architecture/livedata?hl=en#extend_livedata).
> 
> 
> 

Below is what I did for communication between Service and Activity and also Service and Fragment.

In this example, I have:

* a class `SyncLogLiveData` extending `LiveData` that contains a `SpannableStringBuilder`
* a service `SyncService`
* a fragment `SyncFragment`

The Fragment "observes" the LiveData (ie SyncLogLiveData) and performs an action when the LiveData changes.  

The LiveData is updated by the Service.  

I could also update the LiveData from the Fragment in the same way but don't show it here.

**class `SyncLogLiveData`**

```java
public class SyncLogLiveData extends LiveData<SpannableStringBuilder> {
    private static SyncLogLiveData sInstance;
    private final static SpannableStringBuilder log = new SpannableStringBuilder("");

    @MainThread
    public static SyncLogLiveData get() {
        if (sInstance == null) {
            sInstance = new SyncLogLiveData();
        }
        return sInstance;
    }

    private SyncLogLiveData() {
    }

    public void appendLog(String text) {
        log.append(text);
        postValue(log);
    }

    public void appendLog(Spanned text) {
        log.append(text);
        postValue(log);
    }
}

```

**in class `SyncService`**

This line of code will update the content of the LiveData

```java
SyncLogLiveData.get().appendLog(message);

```

You could also make direct use of `setValue(...)` or `postValue(...)` methods of `LiveData`

```java
SyncLogLiveData.get().setValue(message);

```

**class SyncFragment**

```java
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {

    //...

    // Create the observer which updates the UI.
    final Observer<SpannableStringBuilder> ETAObserver = new Observer<SpannableStringBuilder>() {
        @Override
        public void onChanged(@Nullable final SpannableStringBuilder spannableLog) {
            // Update the UI, in this case, a TextView.
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    textViewLog.setText(spannableLog);
                }
            });
        }
    };
    // Observe the LiveData, passing in this activity/fragment as the LifecycleOwner and the observer.
    SyncLogLiveData.get().observe(getViewLifecycleOwner(), ETAObserver);

    //...
}

```

From within an activity it works the same way, but for `.observe(...)`, you may use this instead

```java
SyncLogLiveData.get().observe(this, ETAObserver);

```

You could also fetch the current value of the LiveData this way at anytime in your code.

```java
SyncLogLiveData.get().getValue();

```

Hopefully this will help someone. There wasn't any mention of LiveData in this answer yet.