安卓如何在手机重启时启动广播接收器



每当用户手机重新启动时,我如何启动我的广播接收器。 如果用户杀死应用程序, 广播接收器可以继续在后台运行吗?

我创建了一个 ParsePushBroadcastReceiver,它接收来自 parse.com 的推送通知,但我的应用程序只有在用户打开应用程序时才会收到通知。

public class MyParseReceiver extends ParsePushBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        Log.i(TAG, "onReceive Called");
        if (intent == null) {
            Log.e(TAG, "Receiver intent null");
        } 
        else {
            // Parse push message and handle accordingly
            Log.d(TAG, "Receiver intent data => " + intent.toString());
        }
    }//end onReceive

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

我的清单:

<activity
        android:name=".SplashActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
<service android:name="com.parse.PushService" />
<receiver android:name="com.parse.ParseBroadcastReceiver" >
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <action android:name="android.intent.action.RECEIVE_BOOT_COMPLETED" />
        <action android:name="android.intent.action.USER_PRESENT" />
    </intent-filter>
</receiver>
<receiver
    android:name="com.my.app.core.MyParseReceiver"
    android:exported="false" >
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <action android:name="android.intent.action.USER_PRESENT" />
        <action android:name="com.parse.push.intent.RECEIVE" />
        <action android:name="com.parse.push.intent.DELETE" />
        <action android:name="com.parse.push.intent.OPEN" />
    </intent-filter>
</receiver>
<receiver
    android:name="com.parse.GcmBroadcastReceiver"
    android:permission="com.google.android.c2dm.permission.SEND" >
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <action android:name="android.intent.action.RECEIVE_BOOT_COMPLETED" />
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
        <category android:name="com.my.app" />
    </intent-filter>
</receiver>
<meta-data
    android:name="com.parse.push.notification_icon"
    android:resource="@drawable/ic_launcher" />

您能否尝试在清单中为接收者标签设置android:exported="true"

问:每当用户手机重新启动时,如何启动我的广播接收器。 如果用户杀死应用程序,广播接收器可以继续在后台运行吗?
答:可以。
如果您想在应用中实现 BroadcastReceiver(推送通知),您应该将 Google Cloud Message 与最新的 GCM 一起使用,而不是旧的 C2DM。
此服务使用Google Play服务,因此您不必运行该应用程序,因为它基于Google Play服务,这是Android上的服务。
请参考: https://developer.android.com/google/gcm/index.html
示例:https://github.com/google/gcm

最新更新