Android的蓝牙从服务中 [英] Android Bluetooth from within Service

查看:97
本文介绍了Android的蓝牙从服务中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个理论上可以没有与之关联的活动(以下简称服务的目的是在Android平台上)工作的服务。

I have a service that theoretically can work without an Activity associated to it (as "services" are intended on the Android platform).

该服务使用蓝牙,尤其是寄存器蓝牙服务与给定的名称监听通信。当然工作它必须有蓝牙活性

This service uses Bluetooth, in particular registers a Bluetooth Service with a given Name that listens for communications. Of course to work it has to have the Bluetooth active.

由于我使用的是 BluetoothAdapter.ACTION_REQUEST_ENABLE 来提示用户启用蓝牙的情况下,它不是也已显示在蓝牙API文档。此,虽然是一个活动的,因此需要从另一个活动调用,即:

As also shown on the Bluetooth api docs I'm using the BluetoothAdapter.ACTION_REQUEST_ENABLE to prompt the user to enable Bluetooth in case it's not on already. This, though, is an activity, and therefore needs to be called from another activity, i.e.:

Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
InstanceOfAnActivity.startActivity(enableIntent);

我想实现的是有服务(例如,启动引导时),从任何活动完全脱钩,因此不会有 InstanceOfAnActivity 启动弹出指导用户开启蓝牙​​。

What I would want to achieve is to have the service (which, for example, starts up at boot), completely decoupled from any Activity, and therefore wouldn't have the InstanceOfAnActivity to start up the pop-up instructing the user to turn on Bluetooth.

现在,我知道,还有的(臭名昭著)调用 BluetoothAdapter.enable(),但作为医生说这不应该被直接调用。

Now, I know that there's the (infamous) call to BluetoothAdapter.enable(), but as the doc says it shouldn't be called directly.

所以,任何提示/解决这个难题呢? (也许是容易的,我只是失去了一些东西......)

So, any tip/solution to this dilemma? (Maybe it's easy and I'm just missing something...)

推荐答案

startActivity()不是严格意义上的活动方法 - 这是一个上下文方法,继承活动的服务。 有一件事是清楚的,但 - 正如在 Service.startActivity()文档,如果这种方法被从活动上下文之外调用,那么意图必须包括 FLAG_ACTIVITY_NEW_TASK 启动的标志。

startActivity() is not strictly an Activity method - it is a Context method, inherited by Activity and Service. There is one thing to be aware of, though - as pointed out in the Service.startActivity() doc, "if this method is being called from outside of an Activity Context, then the Intent must include the FLAG_ACTIVITY_NEW_TASK launch flag".

因此​​,与语境绑定服务实例,下面应该工作:

Thus, with 'context' bound to the Service instance, the following should work:

Intent btIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
btIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(btIntent);

这篇关于Android的蓝牙从服务中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆