【发布时间】:2021-06-15 18:19:54
【问题描述】:
尝试使用 kotlin 构建一个 android 应用程序,我在其中连接、发送和读取 BLE(蓝牙低功耗)设备的数据。我设计了一个活动,它将向我显示连接统计信息和从 BLE 设备接收到的数据。我有一个前台服务正在运行,以保持与 BLE 设备的连接处于活动状态并收听统计信息。 我已使用待处理意图从我的前台服务通知中打开此活动。
以下代码展示了创建通知的方法
private fun getServiceNotification(textToShowInNotification: String)
{
val pendingIntent = Intent(<Static context from application class>,ActivityName::class.java)
pendingIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
val contentIntent = PendingIntent.getActivity(<static_context_from_application_class>, 0, pendingIntent, 0)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
val notificationChannel = NotificationChannel("DATA_CHANNEL", <Static context from application class>.resources.getString(R.string.app_name),NotificationManager.IMPORTANCE_DEFAULT)
notificationManager!!.createNotificationChannel(notificationChannel)
}
notification = notificationBuilder!!.setOngoing(true)
.setOnlyAlertOnce(true)
.setContentText(textToShowInNotification)
.setContentIntent(contentIntent)
.build()
notificationManager!!.notify(NOTIFICATION_ID, notification)
}
因为我有一个用例来打开显示 BLE 连接和数据接收的活动。 Activity 的多个实例被创建并且之前的一次没有被破坏,因此我无法获取正在运行的 Activity 的上下文,因此我在 Activity 中显示警报对话框时遇到了问题。
实际用例 - 当我终止应用程序并从前台服务通知打开它时,当建立与设备的连接并从服务监听数据时,必须显示的对话框说我的设备仍然连接并且正在接收的数据不显示,显示对话框时出现异常
尝试显示警报对话框时出现以下错误/异常
D/DialogExecption: Unable to add window -- token null is not valid; is your activity running?
D/DialogExecption: Unable to add window token android.os.BinderProxy@4250d6d8 is not valid; is your activity running?
我使用下面的代码来显示对话框
private fun showAlertDialog()
{
val dialogAlertDialog = AlertDialog.Builder(<Activity Context>)
val inflater: LayoutInflater = layoutInflater
val dialogAlertView: View = inflater.inflate(R.layout.activity_xml_file,null)
dialogAlertDialog.setView(dialogAlertView)
dialogAlertDialog.setCancelable(false)
val builderAlertDialog : AlertDialog = dialogAlertDialog.create()
try
{
builderAlertDialog.show()
}
catch(exception: Exception)
{
Log.d("DialogExecption",""+exception.message)
}
}
我也试过方法
if (!this.isFinishing)
{
builderAlertDialogCycleCancelled.show()
}
但这也无济于事。上面的代码会抑制执行,但我不想这样做,而是想不惜一切代价显示对话框。
为了提供一个 pov,我在我的清单文件中尝试了以下内容,以保持活动的单个实例成为可能,但这并不奏效。
<activity android:name=".ActivityName"
android:alwaysRetainTaskState="true"
android:launchMode="singleTop"
android:screenOrientation="portrait"
android:theme="@style/AppThemeGeneral">
</activity>
我必须以最好的方式使用警报对话框,跳过它不是一个选择。 任何帮助都会很棒。
重要提示 - 我在我的活动中使用范围为 Dispatchers.IO 的协程从 BLE 设备获取数据。
【问题讨论】:
标签: android kotlin android-activity android-service android-alertdialog