我正在开发一个蓝牙广告程序。它在 SDK 28 中编译。根据文档的要求,我添加了 android.permission.FOREGROUND 权限。但即使是现在,如果单击“蓝牙广告”按钮并调用 startForeground(),应用程序也会崩溃。
在我添加权限后,捕获从未达到。在添加权限之前,我仍然会到达捕获序列,并且消息告诉我,我必须添加上面提到的 FOREGROUND_SERVICE 权限。
对于这个应用程序,我使用 Java。
`/**
* Starts BLE Advertising.
*/
private void startAdvertising() {
goForeground();
Log.d(TAG, "Service: Starting Advertising");
if (mAdvertiseCallback == null) {
AdvertiseSettings settings = buildAdvertiseSettings();
AdvertiseData data = buildAdvertiseData();
mAdvertiseCallback = new SampleAdvertiseCallback();
if (mBluetoothLeAdvertiser != null) {
mBluetoothLeAdvertiser.startAdvertising(settings, data,
mAdvertiseCallback);
}
}
}
/**
* Move service to the foreground, to avoid execution limits on background processes.
*
* Callers should call stopForeground(true) when background work is complete.
*/
private void goForeground() {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Notification n = new Notification.Builder(this)
.setContentTitle("Advertising device via Bluetooth")
.setContentText("This device is discoverable to others nearby.")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pendingIntent)
.build();
//TODO: startForeground throws Exception. Has to be Fixed
try{
startForeground(FOREGROUND_NOTIFICATION_ID, n);
} catch (SecurityException e) {
Toast toast = Toast.makeText(this, e.getMessage() + " Exception Throwed", Toast.LENGTH_SHORT);
toast.getView().setBackgroundColor(Color.parseColor("#FF0FF0"));
toast.show();
}
}`
您的代码已过时:替换这两行
PendingIntent pendingIntent = ...
Notification n = ...
由
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
NotificationChannel notificationChannel = new NotificationChannel("your_Channel_ID", "your channel name", NotificationManager.IMPORTANCE_LOW);
getSystemService(NotificationManager.class).createNotificationChannel(notificationChannel);
Notification n = new Notification.Builder(this, "your_Channel_ID")