package br.com.elwnet.manuia import android.app.role.RoleManager import android.content.Intent import android.os.Build import android.os.Handler import android.os.Looper import android.view.WindowManager import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.MethodChannel class MainActivity : FlutterActivity() { companion object { const val CHANNEL = "br.com.elwnet.mikeai/service" var instance: MainActivity? = null } private var channel: MethodChannel? = null override fun configureFlutterEngine(flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) instance = this channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL) channel!!.setMethodCallHandler { call, result -> when (call.method) { "startForeground" -> { startMikeService(); result.success(null) } "stopForeground" -> { stopMikeService(); result.success(null) } "wakeScreen" -> { wakeScreen(); result.success(null) } "isAssistantApp" -> { result.success(isAssistantApp()) } else -> result.notImplemented() } } // App aberto via ACTION_ASSIST (Home longo) na primeira inicialização if (intent?.action == Intent.ACTION_ASSIST || intent?.getBooleanExtra("from_assistant", false) == true) { Handler(Looper.getMainLooper()).postDelayed({ channel?.invokeMethod("assistantActivated", null) }, 900) } } // Chamado quando o app já está aberto e recebe nova Intent (Home longo novamente) override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) if (intent.action == Intent.ACTION_ASSIST || intent.getBooleanExtra("from_assistant", false)) { wakeScreen() Handler(Looper.getMainLooper()).postDelayed({ channel?.invokeMethod("assistantActivated", null) }, 300) } } // Verifica se o MikeAI está definido como assistente padrão private fun isAssistantApp(): Boolean { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { val rm = getSystemService(RoleManager::class.java) rm?.isRoleHeld(RoleManager.ROLE_ASSISTANT) ?: false } else false } private fun startMikeService() { val intent = Intent(this, MikeForegroundService::class.java).apply { action = MikeForegroundService.ACTION_START } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) startForegroundService(intent) else startService(intent) } private fun stopMikeService() { startService(Intent(this, MikeForegroundService::class.java).apply { action = MikeForegroundService.ACTION_STOP }) } private fun wakeScreen() { runOnUiThread { window.addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON or WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED ) val bringToFront = Intent(this, MainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_REORDER_TO_FRONT or Intent.FLAG_ACTIVITY_SINGLE_TOP putExtra("wake_word_triggered", true) } startActivity(bringToFront) } } override fun onDestroy() { instance = null super.onDestroy() } }