Android应用未收到gcm通知

时间:2017-11-28 09:26:00

标签: android push-notification google-cloud-messaging

我正在尝试使用GCM向我的Android应用添加通知。我开始遵循这个 tutorial并使用this example project作为参考。

我按照所有步骤创建了所有需要的类和服务,但我仍然没有收到任何通知。 我正在检查Google Play服务,似乎在我的服务器上成功注册了我的设备。我将google-services.json文件添加到我的项目中,并将所有权限和库添加到项目中。

出了什么问题?
我忘了什么吗?我还需要做点什么吗?我现在很困惑。

AndroidManifest

权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
<permission android:name="com.manager_android.permission.C2D_MESSAGE" android:protectionLevel="signature"/>
<uses-permission android:name="com.manager_android.permission.C2D_MESSAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

接收者和服务

<receiver
        android:name="com.google.android.gms.gcm.GcmReceiver"
        android:exported="true"
        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" />
            <category android:name="com.manager_android" />
            <!--here-->
        </intent-filter>
    </receiver>

    <service
        android:name=".Activities.GcmIntentService"
        android:exported="false" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        </intent-filter>
    </service>

    <service
        android:name=".Activities.TokenRefreshListenerService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.android.gms.iid.InstanceID"/>
        </intent-filter>
    </service>

    <service android:name=".Activities.RegistrationService"
        android:exported="false">
    </service>

已添加到应用 build.gradle

compile 'com.google.android.gms:play-services-gcm:11.0.4'

apply plugin: 'com.google.gms.google-services'

添加到项目 build.gradle

classpath 'com.google.gms:google-services:3.1.0'

RegistrationService

public class RegistrationService extends IntentService {

public RegistrationService() {
    super("");
}

private final String TAG = "RegistrationInfo";

@Override
protected void onHandleIntent(@Nullable Intent intent) {
    registerDevice();
}

private void registerDevice() {
    InstanceID myID = InstanceID.getInstance(getApplicationContext());
    String registratonToken = "";
    try {
        registratonToken = myID.getToken(getString(R.string.gcm_defaultSenderId),
                GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
        log.d("Registration Token", registratonToken);
        Map<String, String> params = new HashMap<>();
        params.put("user_id", registratonToken);
        params.put("platform", "GCM");
        SaveSharedPreference.setToken(getApplicationContext(), registratonToken);

        //Register token on server
        Communication.post(getString(R.string.register_device_url), new RequestParams(params), new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                Log.i(TAG, "Registration was successful");
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Log.i(TAG, "Registration failed.");
            }
        });
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(), "Couldn't register device", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }
}

TokenRefreshListenerService

public class TokenRefreshListenerService extends InstanceIDListenerService {

@Override
public void onTokenRefresh() {
    Intent i = new Intent(this, RegistrationService.class);
    startService(i);
}
}

GCMIntentService

public class GcmIntentService extends GcmListenerService {

private int testId = 1234;

@Override
public void onMessageReceived(String from, Bundle data) {
    String message = data.getString("message");
    sendNotification(message);
}

private void sendNotification(String message) {
    Intent intent = new Intent(this, MainScreenActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), testId, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.logo)
            .setContentTitle("GCM Message")
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent)
            .setWhen(System.currentTimeMillis());

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(testId, notificationBuilder.build());
}
}

当用户登录注册设备时,我将RegistrationService作为服务启动。

1 个答案:

答案 0 :(得分:0)

documentation可以帮助您了解通知。

  

通知是您向自己以外的用户显示的消息   应用程序的正常用户界面。当您告诉系统发出通知时,它   首先在通知区域中显示为图标。要查看详细信息   通知,用户打开通知抽屉。这俩   通知区域和通知抽屉是系统控制的   用户可以随时查看的区域。

它还提供了您将要处理的每个主题的示例代码。

对于GCM,您可以参考this documentation

  

Google Cloud Messaging(GCM)是一项支持开发人员的免费服务   在服务器和客户端应用之间发送消息。这包括   从服务器到客户端应用程序和上游消息的下游消息   从客户端应用程序到服务器。

它将帮助您了解GCM的概念。它还提供sample开头。