应用前台运行时如何接收adb发送的Android Intent
解决方法
首先要解决两个核心问题:
- Action拼写不匹配:你adb命令里用的是
com.ilw.admin.INSTALL_COMPLETE,但AndroidManifest里写的是com.ilw_admin.INSTALL_COMPLETE(下划线和点的差异),这会导致Intent无法正确匹配,先把Manifest里的Action改成和adb一致的。 - singleTop模式的Intent接收逻辑:因为MainActivity设置了
launchMode="singleTop",当Activity已经在前台栈顶时,系统不会重新创建实例,而是通过onNewIntent()方法传递新Intent,而非onCreate()。
步骤1:修正AndroidManifest.xml的Action
把intent-filter中的Action修改为和adb命令一致:
<activity android:name=".MainActivity" android:exported="true" android:launchMode="singleTop" android:theme="@style/LaunchTheme" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <action android:name="com.ilw.admin.INSTALL_COMPLETE"/> <!-- 修正Action拼写 --> <category android:name="android.intent.category.DEFAULT"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity>
步骤2:在MainActivity中重写onNewIntent方法
根据你使用的语言,添加以下代码接收并处理Intent:
Java版本
@Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); // 必须调用setIntent,否则后续getIntent()会拿到旧的Intent setIntent(intent); // 处理接收到的INSTALL_COMPLETE Intent processInstallCompleteIntent(intent); } private void processInstallCompleteIntent(Intent intent) { if (intent != null && "com.ilw.admin.INSTALL_COMPLETE".equals(intent.getAction())) { // 这里写你的业务逻辑,比如弹窗提示、更新UI等 Toast.makeText(this, "已收到INSTALL_COMPLETE指令", Toast.LENGTH_SHORT).show(); } }
Kotlin版本
override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) setIntent(intent) intent?.let { processInstallCompleteIntent(it) } } private fun processInstallCompleteIntent(intent: Intent) { if (intent.action == "com.ilw.admin.INSTALL_COMPLETE") { // 编写你的处理逻辑,比如显示提示 Toast.makeText(this, "已收到INSTALL_COMPLETE指令", Toast.LENGTH_SHORT).show() } }
关于警告的说明
你看到的Warning: Activity not started, intent has been delivered to currently running top-most instance是正常提示,并非错误。因为singleTop模式下,系统发现目标Activity已经在栈顶,就不会创建新实例,直接把Intent传递给现有实例,这个警告只是告知你这个行为逻辑。
内容的提问来源于stack exchange,提问作者bzark
相关产品推荐
相关产品推荐

