NKR NKR - 4 years ago 108
Android Question

Data sharing (one way communication) between service and a seperate app. (Android)

Consider a data being generated in a service (Continuously), i want an other application to retrieve the data from service.

Example: App A (Service) will open the serial port and communicate with external device to get data.

App B (Standalone app) must read the data from service (Data from external device).i have not done that since i need data to be retrieved from external device even if App B is not running, and i have 3 more other apps that require the same data from external device, hence i have decided to run a service in the background.

Answer Source

You could use BroadcastReceivers.

In your app with the service you can broadcast Intents to the system, which can then be picked up by the other apps.

In your app with the service you can send a broadcast like so:

public class MyService extends Service {

    public static final String ACTION_PUBLISH_DATA = "com.example.action.publish_data";

    public void publishResult(Bundle data) {
        Intent intent = new Intent(ACTION_PUBLISH_DATA);
        intent.putExtras(data);
        sendBroadcast(intent);
    }

}

In your client apps, create a broadcast receiver:

public class DataBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // do something with data in the intent.
    }

}

And register it in your manifest like so:

<application>
    ...

    <receiver android:name="com.example.DataBroadcastReceiver">
        <intent-filter>
            <action android:name="com.example.action.publish_data" />
        </intent-filter>
    </receiver>

</application>

Instead of registering in your manifest, you can also register the receiver at runtime using the registerReceiver method

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download