Приложение записывает данные датчика непрерывно в фоновом режиме, даже если дисплей выключен (режим ожидания). Для этой функции я установил сервис, который начинается с взаимодействия с пользователем (кнопка нажатия).
По состоянию на 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 « или « foregressServiceStartNotAllowedException ».
Как я могу найти источник ошибок? Исключение java.lang.runtimeexception: at
(активнопттхард.java:4952) на
android.app.activityThread.-$ )
at android.app.ActivityThread $ H.HandLemessage
(активность Looper.looponce (looper.java:205)
at android.os.looper.loop (looper.java:294) at
aldroid.app.activityThread.main (ActivityTread.java: 8376) в
Java.lang.reflect.method.invoke at
comm.Android.Internal.os.runtimeInit $ methodandargscaller.run
(runtimeinit.java:640) у Com.android. Internal.os.zygoteinit.main
(zygoteinit.java:982), вызванная java.lang.securityexception < /strong>: at
android.os.parcel.createexception (parcel.java:3041) у
android.os.parcel.readexception (parcel.java:3024) на
android.os.parcel .ReadException (parcel.java:2966) at
android.app.iactivitymanager $ stub $ proxy.setserviceforeground
(яковивностьмагер. .java: 862) at
androidx.core.app.servicecompat $api34impl.startforeground
(servicecompat.java:241) at
(ServiceCompat.java:172) at
net.braun_home.sensorercording.sensorservice.onstartCommand
(Sensorservice.java:549) < /strong> at
android.app.ActivityThread. HandleServiceArgs
( ActivityThread.java:4934), вызванные Android.os.RemoteeXcept .java: 2690) at
comm.android.server.am.activesers.setserviceforeNinnerLocked
( AactiveServices.java:2401) at
com.android.server.am.activesers.setserviceforegroundxed
( activeServices.java:1748) at
comm.android.server.am.ActivityManagerService.setServiceforeforge
(активно -managerservice.java:13460) at
android.app.iactanagemanager $
(ааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааааа br />
Исключение java.lang.runtimeexception: at
(активность App.ActivityThread .- $$ Nest $ MhandleServiceArgs (неизвестный источник)
at android.app.activityThread $ h.handlemessage
(активность > (Handler.java:106) at android.os.looper.looponce (looper.java:230)
at android.os.looper.loop (looper.java:319) at
android.app.activityThread.main (ActivityThread.java:8919) at
Java.lang.reflect.method.invoke at
comm.Android.Internal.os.runtimeInit $ methodandargscaller.run
(RuntimeInit.java:578) на com.android.internal.os.zygoteinit.main
(zygoteinit.java:1103), вызванные
android.app.foregroundservicestartnothallowedexception: < /strong> at
android.app.foregroundServiceStartNotAllowedException$1.createFromParcel
(foregroundServiceStartNotAllowedException.java:54) at
android.os.parcel.readparcelableinternal (parcel.java:4882) у
android.os.parcel.readparcelable (parcel.java:4864) на
android.os.parcel.createexceptionorlull (посылка .java: 3064) у
android.os.parcel.createexception (parcel.java:3053) на
android.os.parcel.readexception (parcel.java:3036) на
android. os.parcel.readexception (parcel.java:2978) at
android.app.iactivitymanager$stub $ proxy.setserviceforeforge
(яковисманман. > (Service.java:862) at
androidx.core.app.servicecompat $api34impl.startforeground
(servicecompat.java:241) на
androidx.core.app.servicecompat.startforeground
androidx. br />(servicecompat.java:172) at
shrong>net.braun_home.sensoreRecording.sensorservice.onstartCommand
(SensorService.java:549) < /strong> at
( AactivityThread.java:5268)
< /blockquote>
Подробнее здесь: https://stackoverflow.com/questions/793 ... me-devices
Мобильная версия