android - 从 ADB 安装后静态 BroadcastReceiver 不工作

标签 android android-intent broadcastreceiver adb

我从事的项目需要通过 adb 广播自定义 Intent “com.example.demo.action.LAUNCH”来启动应用程序。

我的计划是静态注册一个广播接收器“LaunchAppReceiver”,它会在收到定制的 Intent 时启动应用。

我通过调用安装了 .apk

adb install -r <pakcageName>

然后我通过调用发送了 Intent

adb shell am broadcast -a com.example.demo.action.LAUNCH

然而,发送 Intent 后,没有任何反应。似乎广播接收器根本没有收到 Intent 。在接收 Intent 之前,我是否需要以某种方式实例化接收者?

注意:由于android设备是远程的,我必须使用adb来处理安装和启动。

谢谢!!


我声明广播接收器如下

public class LaunchAppReceiver extends BroadcastReceiver{

    public LaunchAppReceiver () {}

    @Override
    public void onReceive(Context context, Intent intent) {

        Intent newIntent = new Intent(context, MainActivity.class);
        newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(newIntent);
    }
}

并将其静态注册到 AndroidManifest.xml 中。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.demo" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:enabled="true">
        <receiver
            android:name="com.example.demo.LaunchAppReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.example.demo.action.LAUNCH"/>
            </intent-filter>
        </receiver>
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

最佳答案

终于解决了这个问题。

自 Honeycomb 以来,所有新安装的应用程序将进入 STOP 阶段,直到它们至少启动一次。 Android 为所有广播 Intent 添加了一个标志“FLAG_EXCLUDE_STOPPED_PACKAGES”,以阻止它们到达已停止的应用程序。 http://droidyue.com/blog/2014/01/04/package-stop-state-since-android-3-dot-1/

要解决此问题,只需将标志“FLAG_INCLUDE_STOPPED_PACKAGES”添加到我们发送的 Intent 中即可。就我而言,我将 adb 命令修改为

adb shell am broadcast -a com.example.demo.action.LAUNCH --include-stopped-packages

关于android - 从 ADB 安装后静态 BroadcastReceiver 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29978715/

相关文章:

android - 使用 Windows Azure 推送数据

android - 从谷歌地图 URL 打开应用程序

android - Activity 打不开

android - 关于 WakefulBroadcastReceiver 的困惑

android - 蓝牙设备未在 android oreo 中列出

android - Android 中的全屏 DialogFragment(通过 ActionBar)

android - Retrofit2 反序列化响应主体,即使响应不是 200

android.net.conn.CONNECTIVITY_CHANGE 广播接收器不会在 JellyBean 中触发以进行 VPN 连接和断开连接

android - 在广播接收器中优先接听电话

java - BroadcastReceiver.onReceive 未调用,但 Activity.onNewIntent 执行。为什么?