使用 Manifest 注册广播接收器

Posted

技术标签:

【中文标题】使用 Manifest 注册广播接收器【英文标题】:Registering Broadcast Receiver using Manifest 【发布时间】:2013-10-04 00:15:45 【问题描述】:

我一直在尝试为推送通知制定扩展,其中我没有应用程序的包名称(因为该扩展将用于任何数量的应用程序而无需修改)。我在清单中有以下信息 -

<receiver
            android:name=".GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="App.package" />
            </intent-filter>
            <!-- Receive the registration id -->
          <intent-filter>
              <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
              <category android:name="App.package" />
          </intent-filter>
        </receiver>
        <service android:name=".GcmIntentService" />

清单可以在每个应用程序中使用,无需包含在扩展程序中。这是 IntentService 和 BroadCastReceiver 代码 -

public class GcmIntentService extends IntentService 

    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
    private static final String TAG = "INTENT_TAG";

    public GcmIntentService() 
        super("GcmIntentService");
    

    @Override
    protected void onHandleIntent(Intent intent) 
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        String messageType = gcm.getMessageType(intent);

        if (!extras.isEmpty()) 
            if (GoogleCloudMessaging.
                    MESSAGE_TYPE_SEND_ERROR.equals(messageType)) 
                sendNotification("Send error: " + extras.toString());
             else if (GoogleCloudMessaging.
                    MESSAGE_TYPE_DELETED.equals(messageType)) 
                sendNotification("Deleted messages on server: " +
                        extras.toString());
             else if (GoogleCloudMessaging.
                    MESSAGE_TYPE_MESSAGE.equals(messageType)) 

                for (int i=0; i<5; i++) 
                    Log.i(TAG, "Working... " + (i+1)
                            + "/5 @ " + SystemClock.elapsedRealtime());
                    try 
                        Thread.sleep(5000);
                     catch (InterruptedException e) 
                    
                
                Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
                // Post notification of received message.
                sendNotification("Received: " + extras.toString());
                Log.i(TAG, "Received: " + extras.toString());
            
        
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    
    private void sendNotification(String msg) 
        mNotificationManager = (NotificationManager)
                this.getSystemService(Context.NOTIFICATION_SERVICE);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, LoaderActivity.class), 0);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
        //.setSmallIcon(R.drawable.ic_launcher)
        .setContentTitle("GCM Notification")
        .setStyle(new NotificationCompat.BigTextStyle()
        .bigText(msg))
        .setContentText(msg);

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    


public class GcmBroadcastReceiver extends WakefulBroadcastReceiver 
    @Override
    public void onReceive(Context context, Intent intent) 
        // Explicitly specify that GcmIntentService will handle the intent.
        ComponentName comp = new ComponentName(context.getPackageName(),
                GcmIntentService.class.getName());
        // Start the service, keeping the device awake while it is launching.
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    

当我尝试从服务器发送消息时,通知永远不会被调用,就好像接收者从未被实例化或注册一样。是不是因为我的 IntentService 和 BroacastReceiver 都在默认包中?

【问题讨论】:

我创建了另一个问题,因为问题不是我最初的想法 - ***.com/q/19350641/1079901 【参考方案1】:

您的GCMBroadcastReceiver 在应用程序的主包中查找GcmIntentService,因此如果它在另一个包中则不会被找到。

您可以使用以下代码启动 Intent 服务:

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver 
    @Override
    public void onReceive(Context context, Intent intent) 
        Intent gcmIntent = new Intent (context, GcmIntentService.class);
        gcmIntent.putExtras (intent.getExtras());
        startWakefulService(context, gcmIntent);
        setResultCode(Activity.RESULT_OK);
    

此外,每个使用您的代码的应用程序(我不确定您的代码是否应该用作库项目或以其他方式使用),必须在其清单中使用正确的包名称声明广播接收器在意图过滤器的类别中。并且您必须为 GCM 定义一个包含该包名称的权限。

【讨论】:

所以分类名应该是我在GCMIntentService/GCMBroadcastReceiver中提到的包名吧?这可以与应用程序的实际包名称不同,以便我可以为扩展定义一个通用包名称吗?在权限中,需要哪个包名,扩展名或应用程序(如果允许其中两个不同)?它就像一个库项目,不过称它为插件会是一个更好的术语:-) 不行,类别名称必须是使用您的GCM代码的特定应用程序的包(并且权限中必须使用相同的包)。每个使用您的代码的应用程序都有不同的包名称,因此也有不同的类别名称和 GCM 权限。服务类的包名是一个不同的问题。您应该更改广播接收器代码以停止在应用程序的主包中查找服务类,而是在扩展包中查找它。 感谢您的帮助。我希望这应该很容易解决。 我已经尝试通过更改意图服务和广播接收器的包来解决它。该应用程序现在找到它。我以前从未使用过 IntentService/Boradcastreceiver,所以我在这里遗漏了一些基本的东西。你能告诉我是否需要在代码中启动服务还是会自动启动它。我正在考虑通过代码来做,因为它仍然无法正常工作。 @Creator 我编辑了答案以添加用于从广播接收器启动服务的代码。我希望它对你有用。

以上是关于使用 Manifest 注册广播接收器的主要内容,如果未能解决你的问题,请参考以下文章

普通广播接收者和有序广播接收者

在服务中获取上下文

Android 第六讲 广播接收器和服务

安卓开发学习——广播接收器

android 学习随笔十八(广播与服务 )

Android - 在动态注册的广播接收器上出现“无法传递广播”错误