1. 程式人生 > >android 8.0靜態廣播接收不到

android 8.0靜態廣播接收不到

原專案適配只適配到android7.0,公司沒有android8.0的手機,一直沒進行android8.0的適配,

今天用廣播接收和傳送訊息的時候,用android8.0測試,結果死活接收不到訊息,就想到了可能是8.0傳送廣播寫法變了,於是度娘了下,

        /**
         * 其中ComponentName(引數1,引數2)
         * 引數1指的是你的app的包名,引數2指的是你的自定義廣播所在的路徑
         *
         * 當時度娘時,看到好多人寫引數1,表示是自定義廣播的包名,其實是不對的,我的自定義廣播的包名是“com.btzh.baidulocation.receiver”
         * 我測試了好久,根本接收不到訊息,後來用了方法2,點進去看到原始碼才明白需要的是app的包名
         *
         */
Intent intent = new Intent(); intent.setAction(MqReceiver.Mq_Message); //寫法一 ComponentName componentName = new ComponentName("com.btzh.baidulocation","com.btzh.baidulocation.receiver.MqReceiver"); //寫法二 //ComponentName componentName = new ComponentName(this,"com.btzh.baidulocation.receiver.MqReceiver");
intent.setComponent(componentName); sendBroadcast(intent);

api中原始碼

   /**
     * 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 <var>pkg</var> 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; } /** * Create a new component identifier from a Context and class name. * * @param pkg A Context for the package implementing the component, * from which the actual package name will be retrieved. * @param cls The name of the class inside of <var>pkg</var> that * implements the component. */ public ComponentName(@NonNull Context pkg, @NonNull String cls) { if (cls == null) throw new NullPointerException("class name is null"); mPackage = pkg.getPackageName(); mClass = cls; }

以上為兩種方法的原始碼解釋,看到第一種寫法,根據翻譯很容易誤解為,引數1為自己自定義的廣播接收器的包名,其實不然,我們可以通過 mPackage = pkg.getPackageName(); ctrl+enter點選去看到,

    /** Return the name of this application's package. */
    public abstract String getPackageName();

註釋寫的很清楚,是你的app的包名,所以千萬不用弄錯。然後你的靜態廣播就能適配android8.0了