【发布时间】:2016-04-14 22:04:37
【问题描述】:
我正在尝试创建一个前台服务来与蓝牙设备进行通信,我已经使用这个结构完成了:
使用服务,该服务也将 BroadcastReceiver 注册为私有成员变量(用于处理 Gatt 事件),然后使用 startService 命令启动服务。然后,我在当前 Activity 中绑定到该服务。在 onStartCommand 内部,我分配了一个 BluetoothDevice 对象 (my_device),该对象在 onStartCommand 意图中作为额外的传递给服务中的成员变量。但是,在服务运行并分配了成员变量之后,它以某种方式丢失了该成员变量实例,并且当我尝试在处理 BLE Gatt 事件的 BroadcastReceiver 中执行任何操作时,它再次变为 null。
public final class My_BLEService extends Service {
private My_BLEDevice my_device = null;
private BroadcastReceiver gattUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Problem: my_device is null inside this function
}
};
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Create the Foreground notification
if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
// Get BluetoothDevice object
if(this.my_device == null) {
// Initialize the my_device object
BluetoothDevice bleDevice = intent.getParcelableExtra(My_AppManager.RFSTAR);
this.my_device = new my_BLEDevice(bleDevice);
}
// Connect to the bluetooth device first thing:
if(!this.isConnected) {
this.connect();
}
// Start up the broadcast receiver here
if(!this.receiverRegistered) {
registerReceiver(this.gattUpdateReceiver, this.bleIntentFilter());
this.receiverRegistered = true;
}
Intent notificationIntent = new Intent(My_BLEService.this, MonitoringActivity.class);
// FIXME: Necessary? - notificationIntent.putExtra(My_AppManager.RFSTAR, bleDevice);
notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.drawable.logo_md);
// TODO: Add close button
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("BLE Monitor")
.setTicker("BLE Monitor")
.setContentText("BLE")
// TODO; This isn't appearing correctly the first time
.setSmallIcon(R.drawable.logo_md)
//.setLargeIcon(
// Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pendingIntent)
// Note: this doesn't seem to do anything (setting it to false doesn't change it either)
.setOngoing(true).build();
startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE, notification);
} else if (intent.getAction().equals(Constants.ACTION.STOPFOREGROUND_ACTION)) {
if(this.receiverRegistered) {
unregisterReceiver(this.gattUpdateReceiver);
this.receiverRegistered = false;
}
if(this.isConnected) {
this.disconnect();
}
stopForeground(true);
stopSelf();
}
return START_STICKY;
}
【问题讨论】:
-
您确定没有获得
My_BLEService的新实例吗? -
不,我不知道服务生命周期是如何工作的。它会丢弃并创建新实例吗?
-
不知道 - 从未编写过安卓应用程序(除了玩具示例)。这是我看到你在
my_device为非空之后为空的唯一方法。
标签: java android service bluetooth bluetooth-lowenergy