3

我正在尝试处理我的主类中的推送通知(而且我也有 GCMBroadcastReceiver - 对于我没有运行主类时出现的所有通知)

但 registerReceiver 不起作用(GCMBroadcasrReceiver 工作正常)

我的代码:

public class Main extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        registerReceiver(mHandleMessageReceiver, new IntentFilter("com.google.android.c2dm.intent.RECEIVE"));
    }

    private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("BroadcastReceiver","Working");
        }
    };

}

显现:

<receiver android:name="com.google.android.gcm.GCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" >
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
    </intent-filter>
</receiver>

*仅适用于我的 4.1.2 (S3)

4

2 回答 2

4

好吧,找到了解决方案:

在我的 GCMIntentService.java 中,我需要像这样设置 sendBroadcast:

@Override
protected void onMessage(Context context, Intent intent) {

        Intent i = new Intent("com.my.app.DISPLAY_PUSH");

        i.putExtra("msg", intent.getExtras().getString("msg"));
        context.sendBroadcast(i);
    }

并且广播接收器应该是

protected void onCreate(Bundle savedInstanceState) {
    registerReceiver(mHandleMessageReceiver, new IntentFilter("com.my.app.DISPLAY_PUSH"));
    }
.
.
.

private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("BroadcastReceiver","Working with msg:" + intent.getExtras().getString("msg")  );
        }
};

我想知道为什么它在没有 sendBroadcast 的情况下在 4.1.2 中工作......

于 2013-02-05T21:05:26.810 回答
1

如果你像这样调用 sendBroadcast

Intent  intent = new Intent(context, mBroadcastReceiver.getClass());
intent.setAction(ACTION_ON_CLICK);
context.sendBroadcast(intent);

// or

Intent  intent = new Intent(context, MyBroadcastReceiver.class);
intent.setAction(ACTION_ON_CLICK);
context.sendBroadcast(intent);

将其更改为:

Intent  intent = new Intent(ACTION_ON_CLICK);
context.sendBroadcast(intent);
于 2015-05-01T15:01:58.707 回答