Приложение записывает данные датчика непрерывно в фоновом режиме, даже если дисплей выключен (режим ожидания). Для этой функции я установил сервис, который начинается с взаимодействия с пользователем (кнопка нажатия).
По состоянию на Android версию 12, в коде должны быть какие -то предпосылки, которые я выполнил. .
Вот фрагмент кода из « sensorservice.java < /em>»: < /p>
Код: Выделить всё
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
// ...
// ...
String channelId = "4711"; // arbitrary
Intent notificationIntent = new Intent(this, SensorService.class);
int flag = PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE;
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, flag);
Notification notification;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) // O = OREO = 26
{
NotificationChannel channel = new NotificationChannel(channelId,
getString(R.string.app_name),
NotificationManager.IMPORTANCE_HIGH);
notMan = getSystemService(NotificationManager.class);
if (notMan != null)
{
notMan.createNotificationChannel(channel);
Notification.Builder builder = new Notification.Builder(this, channelId);
builder.setSmallIcon(R.drawable.vector3d_bg_transp)
.setContentTitle(text0)
.setContentText(text1)
.setTicker(text1)
.setSubText("Start Service")
.setShowWhen(true)
.setAutoCancel(true)
.setTimeoutAfter(500)
.setChannelId(channelId)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(Notification.PRIORITY_HIGH)
.setCategory(Notification.CATEGORY_MESSAGE)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setContentIntent(pendingIntent);
notification = builder.build();
int serviceType = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) // Q = Quince Tart = 29
serviceType |= ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) // R = Red Velvet Cake = 30
serviceType |= ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE;
ServiceCompat.startForeground(this, id, notification, serviceType);
}
}
else
{
// ...
}
return START_REDELIVER_INTENT;
}
Код: Выделить всё
< /code>
Это прекрасно работает на четырех версиях Android, которые я протестировал: < /p>
Samsung Galaxy A14 (Android 13 ) < /li>
Google Pixel 6a (Android 15) < /li>
Samsung Galaxy Tab A 10,5 (Android 10) < /li>
Huawei P10 Lite (Android 8.0) < /li>
< /ul>
Однако в консоли разработчика Google (раздел Android Vitals, Crashes и ANR), я получаю частые сообщения об ошибках от других Устройства (с Android 14 или 15), на которых у меня нет физического доступа: < /p>
Google TangorPro < /li>
t- Mobile Cypresspoint < /li>
safaricom neon_smarta_2 < /li>
goggle oriole < /li>
samsung a06 < /li>
< li> Samsung A15 < /li>
< /ul>
Ошибка всегда возникает в строке < /p>
ServiceCompat.startForeground(this, id, notification, serviceType);и является либо « securityException « или « foregressServiceStartNotallowed ».
Как я могу найти источник ошибок?
Подробнее здесь: https://stackoverflow.com/questions/793 ... me-devices
Мобильная версия