Android - BroadcastReceiver 服务

Android - Service with BroadcastReceiver

我的应用程序有一个通过蓝牙检测对象的后台服务,我想在当前 activity 中显示一个对话框(在前台或后台检测应用程序的逻辑已完成)当检测到 BT 对象时. 我阅读了 BroadcastReceiver class,但我不知道如何将数据从我的服务发送到当前 activity 的广播以在 Activity.[=11= 中显示对话框]

如果您知道其他解决方案也可以

据我了解,您不会将数据从服务发送到您的 class。 您将在当前 activity 中启动 class,并使用一个等待服务响应的侦听器。如果给出肯定响应,则会显示对话框

BroadcastReceiver class 在服务中使用,而不是在您当前的 activity class.

中使用

当您的服务检测到设备时,您应该从该服务发送广播接收器,如下所示:

 final Intent intent = new Intent(action);
 sendBroadcast(intent);

然后在您的 activity 中使用该操作注册此接收器。

你可以参考这个,这是 BLE sample 作者 google:

接收此类广播的最佳方法是查找蓝牙状态已更改,documented here. Your code will look something like this (Copied from this question, with some modification)

public class BluetoothReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            //See if new bluetooth objects detected
        }
    }
};

接下来您需要将接收器添加到您的清单中。需要这样的东西:

<receiver android:name=".BlutoothReceiver" >
    <intent-filter>
        <action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
    </intent-filter>
</receiver>" />
</receiver>

除此之外,请阅读上面列出的文档。

您可以使用此 Android service broadcastreceiver example 来实现您的目标。

作为替代方案,您需要提供 Service class 对 MainActivity 的回调。您可以使用 Bound services 作为起点。