通知不是来自Android服务

时间:2016-06-08 12:37:25

标签: android

我有一个从服务器接收消息的服务类,我应该通知用户该消息。我从互联网上获取此代码以显示通知 -

public void showNotification(String msg){
        logger.debug("GOT NEW TEXT MESSAGE0: " + msg);
        Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        Intent intent = new Intent(this, NotificationReceiver.class);

        PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
        logger.debug("GOT NEW TEXT MESSAGE1: " + msg);
        Notification n  = new Notification.Builder(this)
                .setContentTitle("New Message Received")
                .setContentText(msg)
                .setContentIntent(pIntent)
                .setAutoCancel(true)
                .addAction(0, "Ok", pIntent).build();

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(0, n);
    } 

根据日志,我正确收到消息 -

GOT NEW MESSAGE0: hello
GOT NEW MESSAGE1: hello

但我仍然没有收到任何通知。我的代码中是否有任何问题。

3 个答案:

答案 0 :(得分:0)

试试这个样本。

Intent intent = new Intent(context, ResultActivity.class);
                PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationCompat.Builder b = new NotificationCompat.Builder(context);

            b.setAutoCancel(true)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setTicker("Hearty365")
                    .setContentTitle("Default notification")
                    .setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
                    //.setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_SOUND)
                    .setContentIntent(contentIntent)
                    .setContentInfo("Info")
            .addAction(android.R.drawable.ic_media_pause, "Start", contentIntent)
                    .addAction(android.R.drawable.ic_dialog_alert, "Pause", contentIntent);



            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(1, b.build());

答案 1 :(得分:0)

致电PendingIntent.getActivity()时会提供一个标记(即PendingIntent.FLAG_UPDATE_CURRENT),而不仅仅是0

引用所有可能的常量:https://developer.android.com/reference/android/app/PendingIntent.html

答案 2 :(得分:0)

虽然(据我所知)没有记录,但通知需要设置小图标才能显示。

尝试以下方法:

Notification n  = new Notification.Builder(this)
    .setSmallIcon(android.R.drawable.ic_dialog_info) // this is required
    .setContentTitle("New Message Received")
    .setContentText(msg)
    .setContentIntent(pIntent)
    .setAutoCancel(true)
    .addAction(0, "Ok", pIntent).build();