从服务创建通知

时间:2016-02-20 13:46:12

标签: android notifications google-cloud-messaging

我使用GCM服务从节点js服务器发送消息,在服务中接收设备,最后在通知中显示它。所有作品和设备都会收到通知,但是,在我想要创建通知的那一刻,它不会显示它。我很遗憾,也许我在通知的创建上遗漏了一些东西。我用谷歌提供的gcm示例指导我自己,虽然,我无法显示通知。

以下是服务的代码:

public class MyGcmListenerService extends GcmListenerService {

private static final String TAG = "MyGcmListenerService";
@Override
public void onMessageReceived(String from, Bundle data) {
    String message = data.getString("TableMeNot");
    Log.d(TAG, "From: " + from);
    Log.d(TAG, "Message: " + message);
    sendNotification(message);

}
private void sendNotification(String message) {
    Intent intent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setContentTitle("You have a new notification!!!")
            .setContentText(message)
            .setContentIntent(pendingIntent);
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    notificationManager.notify(1, notificationBuilder.build());
    Log.d(TAG, "NOTIFICATION CREATED!!!!!!!!!!!!!!!" );
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

试试这个

private void sendNotification() {
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_stat_msg_box_copy)
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                        .setContentTitle(getResources().getString(R.string.app_name))
                        .setColor(getResources().getColor(R.color.colorPrimary))

                        .setContentText("New message");

        mBuilder.setAutoCancel(true);

        Intent resultIntent = new Intent(this, MainActivity.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                        (int) System.currentTimeMillis(),
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(0, mBuilder.build());
    }