BroadcastReceiver

从android 8.0(API26)开始,对清单文件中静态注册广播接收者增加了限制,建议大家不要在清单文件中静态注册广播接收者

静态注册BR,通过action的方式拉起,已经不支持

为了解决这个问题,项目采用了

intent.setComponent(new ComponentName(requireContext().getPackageName(), "com.sohu.myapplication.TestReceiver"));

    /**
     * (Usually optional) Explicitly set the component to handle the intent.
     * If left with the default value of null, the system will determine the
     * appropriate class to use based on the other fields (action, data,
     * type, categories) in the Intent.  If this class is defined, the
     * specified class will always be used regardless of the other fields.  You
     * should only set this value when you know you absolutely want a specific
     * class to be used; otherwise it is better to let the system find the
     * appropriate class so that you will respect the installed applications
     * and user preferences.
     *
     * @param component The name of the application component to handle the
     * intent, or null to let the system find one for you.
     *
     * @return Returns the same Intent object, for chaining multiple calls
     * into a single statement.
     *
     * @see #setClass
     * @see #setClassName(Context, String)
     * @see #setClassName(String, String)
     * @see #getComponent
     * @see #resolveActivity
     */
    public @NonNull Intent setComponent(@Nullable ComponentName component) {
        mComponent = component;
        return this;
    }

(通常是可选的)显式地设置组件来处理意图。如果保留默认值null,系统将根据Intent中的其他字段(action, data, type, categories)决定使用合适的类。如果定义了该类,则无论其他字段如何,都将始终使用指定的类。只有当你确定一定要使用某个特定的类时,你才应该设置这个值;否则,最好让系统找到适当的类,这样您就会尊重已安装的应用程序和用户首选项。


    /**
     * Create a new component identifier.
     *
     * @param pkg The name of the package that the component exists in.  Can
     * not be null.
     * @param cls The name of the class inside of pkg that
     * implements the component.  Can not be null.
     */
    public ComponentName(@NonNull String pkg, @NonNull String cls) {
        if (pkg == null) throw new NullPointerException("package name is null");
        if (cls == null) throw new NullPointerException("class name is null");
        mPackage = pkg;
        mClass = cls;
    }

也就是说,通过setComponet的方式明确指定要接收的广播,通过包名和类的完整路径指定。
通过这种方式,即便两个app的广播接收类的完整路径都是一样的,两个app直接也不会相互干扰,因为两个app的包名是不一样的。
测试发现,即便A app指定B app包名的广播接收器,也是不起作用的,除非B app的进程是存活状态。

你可能感兴趣的:(android)