|
|
|
@ -37,9 +37,13 @@ class BleWakeReceiver : BroadcastReceiver() { |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
/** |
|
|
|
* 启动BLE服务的改进方法 |
|
|
|
* 处理Android系统对后台服务启动的限制 |
|
|
|
*/ |
|
|
|
private fun startBleService(context: Context) { |
|
|
|
try { |
|
|
|
// 检查是否存在BleMediaService类,如果不存在则使用BleService |
|
|
|
// 检查是否存在BleMediaService类 |
|
|
|
val serviceClass = try { |
|
|
|
Log.d(TAG, "startBleService存在") |
|
|
|
Class.forName("com.yunqiinnovation.agent_service.BleMediaService") |
|
|
|
@ -48,22 +52,55 @@ class BleWakeReceiver : BroadcastReceiver() { |
|
|
|
return |
|
|
|
} |
|
|
|
|
|
|
|
// 创建服务Intent,并携带MAC地址 |
|
|
|
// 创建服务Intent |
|
|
|
val serviceIntent = Intent().apply { |
|
|
|
setClassName(context, serviceClass.name) |
|
|
|
action = BleConst.ACTION_SCAN_RESULT |
|
|
|
} |
|
|
|
|
|
|
|
// 启动前台服务 |
|
|
|
|
|
|
|
// 启动服务的改进策略 |
|
|
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { |
|
|
|
context.startForegroundService(serviceIntent) |
|
|
|
Log.i(TAG, "已启动前台服务: ${serviceClass.name}") |
|
|
|
try { |
|
|
|
// 首先尝试启动前台服务 |
|
|
|
Log.i(TAG, "尝试启动前台服务: ${serviceClass.name}") |
|
|
|
context.startForegroundService(serviceIntent) |
|
|
|
Log.i(TAG, "前台服务启动成功") |
|
|
|
} catch (e: IllegalStateException) { |
|
|
|
Log.w(TAG, "前台服务启动失败,尝试其他方式: ${e.message}") |
|
|
|
|
|
|
|
// 如果前台服务启动失败,尝试通过Activity启动 |
|
|
|
try { |
|
|
|
Log.i(TAG, "通过Activity启动服务成功: ${serviceClass.name}") |
|
|
|
val activityIntent = context.packageManager.getLaunchIntentForPackage(context.packageName)?.apply { |
|
|
|
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP |
|
|
|
putExtra("auto_start_ble_service", true) |
|
|
|
putExtra("ble_service_action", BleConst.ACTION_SCAN_RESULT) |
|
|
|
} |
|
|
|
|
|
|
|
if (activityIntent != null) { |
|
|
|
context.startActivity(activityIntent) |
|
|
|
|
|
|
|
Log.i(TAG, "通过Activity启动应用,将在前台启动服务") |
|
|
|
} else { |
|
|
|
Log.e(TAG, "无法获取应用启动Intent") |
|
|
|
} |
|
|
|
} catch (activityException: Exception) { |
|
|
|
Log.e(TAG, "通过Activity启动也失败: ${activityException.message}") |
|
|
|
} |
|
|
|
} catch (e: Exception) { |
|
|
|
Log.e(TAG, "启动前台服务时发生未知错误: ${e.message}", e) |
|
|
|
} |
|
|
|
} else { |
|
|
|
context.startService(serviceIntent) |
|
|
|
Log.i(TAG, "已启动服务: ${serviceClass.name}") |
|
|
|
// Android 8.0以下直接启动服务 |
|
|
|
try { |
|
|
|
context.startService(serviceIntent) |
|
|
|
Log.i(TAG, "已启动服务: ${serviceClass.name}") |
|
|
|
} catch (e: Exception) { |
|
|
|
Log.e(TAG, "启动服务失败: ${e.message}", e) |
|
|
|
} |
|
|
|
} |
|
|
|
} catch (e: Exception) { |
|
|
|
Log.e(TAG, "启动BLE服务失败: ${e.message}", e) |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
} |