【问题标题】:Android push notification offline [closed]Android推送通知离线[关闭]
【发布时间】:2026-01-29 04:55:01
【问题描述】:

我正在尝试在我的应用中实现推送通知,已经使用 GCM。但情况是我也想要离线工作的方式。 即:对于 android 应用程序内的多个条件,它应该触发推送通知。

目前正在尝试:

NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification);
contentView.setImageViewResource(R.id.image, R.drawable.ic_launcher);
contentView.setTextViewText(R.id.title, title);
contentView.setTextViewText(R.id.text, msg);
notification.contentView = contentView;

Intent notificationIntent = new Intent(this, HomeActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this,randomNo, notificationIntent, 0);

但问题是, 1.当应用程序没有运行时,通知到达但屏幕闪烁(因为我使用意图调用它)。 2.我想对多个条件使用同一个类并将其转发到不同的活动(目前我不能将意图更改为基于 condtiop 的另一个活动)。

【问题讨论】:

  • 请解释否决投票
  • 可能是因为不清楚你在问什么。
  • 很简单。我想在 android 中离线推送通知
  • 虽然我没有投反对票,但坦率地说,即使我不理解“离线推送通知”
  • 离线是什么意思 关于离线有多种理解 我没有使用 应用在bg 我的设备屏幕被锁定,应用在前台或后台 我的互联网处于离线状态跨度>

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


【解决方案1】:

1) 发送通知的正确方法是mNotificationManager.notify(...),如下所示:

private void sendNotification(String message, String title, int id) {
    Intent intent = new Intent(this, HomeActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, 
    intent, PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_stat_icon)
            .setContentTitle(title)
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

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

    notificationManager.notify(id /* ID of notification */, 
            notificationBuilder.build());
}

2) 您可以将HomeActivity.class 替换为类构造函数中给出的变量或作为参数的某个方法:Class<?> cls,然后使用Intent notificationIntent = new Intent(this, cls);

【讨论】:

  • 感谢您的回复。我可以知道如何将类从另一个活动传递给这个方法
  • 目前我可以发送like,private void sendNotification(String message, String title, int id,Context context)
  • 只需使用sendNotification(String message, String title, int id, Class<?> cls, Context context)
  • 然后将HomeActivity.class替换为cls
  • 出现错误-> 无法解析构造函数'Intent(com.id.myacitivity.java.lang.Class)