0
我正在開發一個應用程序,該應用程序應該在Android服務中啓動藍牙掃描(無需請求用戶啓用藍牙因爲應用程序根本沒有任何活動),我的應用程序沒有UI或更精確地說我的設備沒有LCD/LED顯示屏。經過詳盡的搜索&引用谷歌和stackoverflow中的鏈接,我可以部分找到解決方案並編寫下面的代碼。在Android服務中啓動藍牙
在這裏,我從廣播接收器啓動服務,並在服務,我開始了藍牙,但是藍牙似乎沒有開機,我曾嘗試直接使藍牙使用的代碼
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
}
}
};
}
而且敬酒消息中的使用服務類不顯示。
我的代碼中沒有啓用&掃描藍牙有什麼問題?
執行onStartCommand後,藍牙仍然無法打開。我在任務管理器中看不到該服務。 – User210282
你表示吐司? –
不,烤麪包沒有顯示 – User210282