Anonymous
ОС Android Wear: как открыть свою деятельность или сделать всплывающее уведомление, от моего переднего плана, когда экра
Сообщение
Anonymous » 31 июл 2025, 08:07
У меня есть приложение для аварийного приложения Android Wear OS, которое отслеживает пользователя и ищет экстренные события. Когда приложение закрыто, я использую услугу переднего плана, чтобы продолжать мониторинг в фоновом режиме. Это работает нормально, и приложение регистрирует событие и оба вибрирует и издает звук пинга. Таким образом, пользователь знает, что событие было идентифицировано < /li>
< /ol>
Я попробовал кучу разных подходов, и я знаю, что это сложно нарочно, с упрочнением ограничений. Но, конечно, это возможно. < /P>
Мой первый подход: < /p>
Код: Выделить всё
private fun openApp() {
AppLogger.d(TAG, "Open App Intent")
val notificationManager = this.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
val saveRequestOptionsBundle: Bundle? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
val mode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA) {
ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOW_ALWAYS
} else {
ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED
}
ActivityOptions.makeBasic().apply {
pendingIntentCreatorBackgroundActivityStartMode = mode
}.toBundle()
} else {
null
}
val openAppIntent = Intent(this, MainActivity::class.java)
val openAppPendingIntent = PendingIntent.getActivity(
this,
1,
openAppIntent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
saveRequestOptionsBundle
)
val notification = NotificationCompat.Builder(this, getString(R.string.emergency_notification_channel_id))
.setContentTitle(getString(R.string.emergency_notification_title))
.setFullScreenIntent(openAppPendingIntent, true)
.setContentText(getString(R.string.event))
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setContentIntent(openAppPendingIntent)
.setSmallIcon(R.drawable.ic_app_logo)
.setAutoCancel(false)
.build()
notificationManager.notify(11, notification)
}
< /code>
Мой второй подход был: < /p>
private fun openApp1() {
Log.d(TAG, "Open App Intent")
val intent = Intent(this, MainActivity::class.java).apply {
addFlags(FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TOP)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA) { // API 36+
val activityOptions = ActivityOptions.makeBasic().apply {
pendingIntentCreatorBackgroundActivityStartMode = ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOW_ALWAYS
}
val launchActivityPendingIntent: PendingIntent = PendingIntent.getActivity(
this,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
activityOptions.toBundle()
)
try {
launchActivityPendingIntent.send()
} catch (e: PendingIntent.CanceledException) {
AppLogger.e(TAG, "PendingIntent was cancelled", e)
}
} else {
startActivity(intent)
}
}
< /code>
Оба подхода дали мне ошибку: < /p>
Запуск фоновой деятельности заблокирован! [CallingPackage: com.mypackage; CallingPackageTargetSDK: 36; CallingInguid: 10251; CallingPid: -1; AppSwitchState: 1; CallingIgnhAsanyVisibleWindow: false; CallingIngyDProcstate: Foreground_service; iscallinguidpersistententsystemprocess: false; upceDbalBypisender: FounalStartPrivileges [AlsbackGrackAntivityStarts = true, AlsbackgroundsgroundServiceStarts = true, OningatingToken=Android.os.binder@8]; намерение: намерение {cmp = com.mypackage.mainactivity}; CallerApp: Null; BallowedBypicReator: bsp.allay_bal; BallowedBypicReatorWithHardening: BSP.Allow_Bal; RELUCTIFPICREATORALLOWSBAL: BAL_BLOCK; Hasrealcaller: True; iscallforresult: ложь; IspendingIntent: true; Autooptinreason: Null; RealCallingPackage: com.samsung.android.wearable.sysui; RealCallingPackageTargetSDK: 33; RealCallingInguid: 10; RealCallingPid: 1; Realcallinginghasanyvisiblewindow: false; RealCallingingRocstate: Bound_foreground_service; IsRealCallingIngeDpersistentEntsystemProcess: false; OningingPendingIntent: pendingIntEntRecord {13CA919 com.mypackage startActivity (AllistList: 87:+30s0ms/0/notification_service/notification managerservice)}; RealCallerApp: ProcessRecord {55c 12: com.samsung.android.wearable.sysui/u0}; Realinvisibletask: ложь; BallowedBypisender: BSP.Allow_Bal; Resultifpisendenlowsbal: bal_block] < /p>
< /blockquote>
У меня есть все разрешения: < /p>
use_full_screen_intent < /li>
system_alert_window < /li>
< /li>
system_alert_window < /li> /> < /ul>
mainActivity в манифесте имеет это: < /p>
Android: LaunchMode = "singletask" < /li>
Android: Turnscreenon = "true" < /li>
Android: Showwhenlocked = "true" < /li>
android: showwhenlocked = "true" < /br />
android: showwhenlocked = "true". /> И мой канал уведомления выглядит так: < /p>
// Emergency Channel
String emergency_channel_id = getString(R.string.emergency_notification_channel_id);
CharSequence emergency_name = getString(R.string.emergency_notification_channel_name);
String emergency_description = getString(R.string.emergency_notification_channel_description);
NotificationChannel emergency_channel = new NotificationChannel(
emergency_channel_id,
emergency_name,
NotificationManager.IMPORTANCE_HIGH
);
emergency_channel.setDescription(emergency_description);
emergency_channel.enableLights(true);
emergency_channel.setLightColor(Color.RED);
emergency_channel.enableVibration(true);
emergency_channel.setVibrationPattern(new long[]{0, 500, 200, 500, 200, 500});
emergency_channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
emergency_channel.setBypassDnd(true);
emergency_channel.setShowBadge(true);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
emergency_channel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM), audioAttributes);
notificationManager.createNotificationChannel(emergency_channel);
Я пережил множество различных вопросов Stackoverflow и официальных документов об обновлении Android, но, похоже, ничто не пройдет эту BAL_BLOCK.>
Подробнее здесь:
https://stackoverflow.com/questions/797 ... ion-from-m
1753938477
Anonymous
У меня есть приложение для аварийного приложения Android Wear OS, которое отслеживает пользователя и ищет экстренные события. Когда приложение закрыто, я использую услугу переднего плана, чтобы продолжать мониторинг в фоновом режиме. Это работает нормально, и приложение регистрирует событие и оба вибрирует и издает звук пинга. Таким образом, пользователь знает, что событие было идентифицировано < /li> < /ol> Я попробовал кучу разных подходов, и я знаю, что это сложно нарочно, с упрочнением ограничений. Но, конечно, это возможно. < /P> Мой первый подход: < /p> [code]private fun openApp() { AppLogger.d(TAG, "Open App Intent") val notificationManager = this.getSystemService(NOTIFICATION_SERVICE) as NotificationManager val saveRequestOptionsBundle: Bundle? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { val mode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA) { ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOW_ALWAYS } else { ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED } ActivityOptions.makeBasic().apply { pendingIntentCreatorBackgroundActivityStartMode = mode }.toBundle() } else { null } val openAppIntent = Intent(this, MainActivity::class.java) val openAppPendingIntent = PendingIntent.getActivity( this, 1, openAppIntent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, saveRequestOptionsBundle ) val notification = NotificationCompat.Builder(this, getString(R.string.emergency_notification_channel_id)) .setContentTitle(getString(R.string.emergency_notification_title)) .setFullScreenIntent(openAppPendingIntent, true) .setContentText(getString(R.string.event)) .setCategory(NotificationCompat.CATEGORY_ALARM) .setPriority(NotificationCompat.PRIORITY_MAX) .setDefaults(NotificationCompat.DEFAULT_ALL) .setContentIntent(openAppPendingIntent) .setSmallIcon(R.drawable.ic_app_logo) .setAutoCancel(false) .build() notificationManager.notify(11, notification) } < /code> Мой второй подход был: < /p> private fun openApp1() { Log.d(TAG, "Open App Intent") val intent = Intent(this, MainActivity::class.java).apply { addFlags(FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TOP) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA) { // API 36+ val activityOptions = ActivityOptions.makeBasic().apply { pendingIntentCreatorBackgroundActivityStartMode = ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOW_ALWAYS } val launchActivityPendingIntent: PendingIntent = PendingIntent.getActivity( this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, activityOptions.toBundle() ) try { launchActivityPendingIntent.send() } catch (e: PendingIntent.CanceledException) { AppLogger.e(TAG, "PendingIntent was cancelled", e) } } else { startActivity(intent) } } < /code> Оба подхода дали мне ошибку: < /p> Запуск фоновой деятельности заблокирован! [CallingPackage: com.mypackage; CallingPackageTargetSDK: 36; CallingInguid: 10251; CallingPid: -1; AppSwitchState: 1; CallingIgnhAsanyVisibleWindow: false; CallingIngyDProcstate: Foreground_service; iscallinguidpersistententsystemprocess: false; upceDbalBypisender: FounalStartPrivileges [AlsbackGrackAntivityStarts = true, AlsbackgroundsgroundServiceStarts = true, OningatingToken=Android.os.binder@8]; намерение: намерение {cmp = com.mypackage.mainactivity}; CallerApp: Null; BallowedBypicReator: bsp.allay_bal; BallowedBypicReatorWithHardening: BSP.Allow_Bal; RELUCTIFPICREATORALLOWSBAL: BAL_BLOCK; Hasrealcaller: True; iscallforresult: ложь; IspendingIntent: true; Autooptinreason: Null; RealCallingPackage: com.samsung.android.wearable.sysui; RealCallingPackageTargetSDK: 33; RealCallingInguid: 10; RealCallingPid: 1; Realcallinginghasanyvisiblewindow: false; RealCallingingRocstate: Bound_foreground_service; IsRealCallingIngeDpersistentEntsystemProcess: false; OningingPendingIntent: pendingIntEntRecord {13CA919 com.mypackage startActivity (AllistList: 87:+30s0ms/0/notification_service/notification managerservice)}; RealCallerApp: ProcessRecord {55c 12: com.samsung.android.wearable.sysui/u0}; Realinvisibletask: ложь; BallowedBypisender: BSP.Allow_Bal; Resultifpisendenlowsbal: bal_block] < /p> < /blockquote> У меня есть все разрешения: < /p> use_full_screen_intent < /li> system_alert_window < /li> < /li> system_alert_window < /li> /> < /ul> mainActivity в манифесте имеет это: < /p> Android: LaunchMode = "singletask" < /li> Android: Turnscreenon = "true" < /li> Android: Showwhenlocked = "true" < /li> android: showwhenlocked = "true" < /br /> android: showwhenlocked = "true". /> И мой канал уведомления выглядит так: < /p> // Emergency Channel String emergency_channel_id = getString(R.string.emergency_notification_channel_id); CharSequence emergency_name = getString(R.string.emergency_notification_channel_name); String emergency_description = getString(R.string.emergency_notification_channel_description); NotificationChannel emergency_channel = new NotificationChannel( emergency_channel_id, emergency_name, NotificationManager.IMPORTANCE_HIGH ); emergency_channel.setDescription(emergency_description); emergency_channel.enableLights(true); emergency_channel.setLightColor(Color.RED); emergency_channel.enableVibration(true); emergency_channel.setVibrationPattern(new long[]{0, 500, 200, 500, 200, 500}); emergency_channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); emergency_channel.setBypassDnd(true); emergency_channel.setShowBadge(true); AudioAttributes audioAttributes = new AudioAttributes.Builder() .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) .setUsage(AudioAttributes.USAGE_ALARM) .build(); emergency_channel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM), audioAttributes); notificationManager.createNotificationChannel(emergency_channel); [/code] Я пережил множество различных вопросов Stackoverflow и официальных документов об обновлении Android, но, похоже, ничто не пройдет эту BAL_BLOCK.> Подробнее здесь: [url]https://stackoverflow.com/questions/79720806/android-wear-os-how-do-i-open-my-activity-or-make-a-pop-up-notification-from-m[/url]