我正在开发一个应用程序,它应该在 android 服务中启动蓝牙扫描(无需请求用户启用蓝牙,因为该应用程序根本没有任何活动)并且我的应用程序没有 UI,或者更准确地说我的设备没有 LCD/LED 显示屏。经过详尽的搜索和引用 google 和 stackoverflow 中的链接后,我可以部分找到解决方案并编写以下代码。
这里我从广播接收器启动了一个服务,在服务中我启动了蓝牙,但是蓝牙好像没有开启,我试过直接使用代码开启蓝牙
BluetoothAdapter.getDefaultAdapter().enable()
也试过
Intent btIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
btIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
serviceContext.startActivity(btIntent);
但在任何一种情况下,蓝牙都不会打开。
这是清单文件:
android:versionCode="1"
android:versionName="1.0" android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name=".StartReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<service android:name=".StartService"></service>
</application>
这是广播接收器类:
public class StartReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Intent receiverIntent = new Intent(context, StartService.class);
context.startService(receiverIntent);
Log.i("Autostart", "started");
}
}
和服务类:
public class StartService extends Service{
private static final String TAG = "BluetoothService";
BluetoothAdapter btAdapter;
BluetoothDevice device;
Context serviceContext;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onStart(Intent intent, int startid){
Toast.makeText(this, "Bluetooth Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "OnStart");
BluetoothAdapter.getDefaultAdapter().enable();
//Intent btIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//btIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//serviceContext.startActivity(btIntent);
registerReceiver(bcReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
btAdapter.startDiscovery();
}
@Override
public void onDestroy(){
BluetoothAdapter.getDefaultAdapter().disable();
unregisterReceiver(bcReceiver);
btAdapter.cancelDiscovery();
}
private final BroadcastReceiver bcReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
//Do Something
}
}
};
}
此外,服务类中使用的 Toast 消息也不会显示。
我的代码中没有启用和扫描蓝牙可能有什么问题?