简体   繁体   中英

Receive bluetooth data in whole app

i develop an Android-Bluetooth App with 3-4 Activitys. Now i have to receive bluetooth data in any of these activitys. I think i have to implement a Service which contains a BroadcastReceiver which listens to incoming BlueTooth Data and send a Broadcast, but i don't know how to do that.

Thanks in advance.

You can implement your own BroadcastReceiver. So, when your LocalService receive a data, it will notify using sendBroadcast method. Your activities should register the specific BrodcastReceiver.

In your Service

Notify about received messages:

public void onMessageReceived(String message) {
    Intent intent = new Intent(ACTION_BLUETOOTH_MESSAGE);
    intent.putExtra(BLUETOOTH_MESSAGE_CONTENT, message);
    sendBroadcast(intent);
}

On each activity

Registering the broadcast receiver:

registerReceiver(messageReceiver,
            new IntentFilter(ACTION_BLUETOOTH_MESSAGE));    

Implementation of the broadcast receiver:

private BroadcastReceiver messageReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        String message = intent.getStringExtra(BLUETOOTH_MESSAGE_CONTENT);
    //Do something you want 
    }
};

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