我正在使用 Phonegap 插件“PushPlugin”(https://github.com/phonegap-build/PushPlugin)以及适用于 iOS 和 Android 的 Phonegap 2.9.0。对于 iOS,一切都按预期工作:通知到达,我单击通知并启动应用程序。
在 Android 上,我们区分两种情况:应用程序处于前台(活动)或后台(关闭或只是未积极使用)。当我在前台收到通知时,该插件可以工作。当我在后台收到通知时,插件会在通知栏中创建通知,但点击通知不会打开我的应用程序。
应该打开我的应用程序的相关代码是:
// Gets called when the notification arrives
protected void onMessage(Context context, Intent intent) {
Log.d(TAG, "onMessage - context: " + context);
// Extract the payload from the message
final Bundle extras = intent.getExtras();
if (extras != null)
{
final boolean foreground = this.isInForeground();
extras.putBoolean("foreground", foreground);
if (foreground)
PushPlugin.sendExtras(extras);
else
createNotification(context, extras);
}
}
// This creates the notification in the notification bar, but a click on the notification does not open my app
public void createNotification(Context context, Bundle extras)
{
final NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
final String appName = getAppName(this);
final Intent notificationIntent = new Intent(this, PushHandlerActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
notificationIntent.putExtra("pushBundle", extras);
final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
final NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(context.getApplicationInfo().icon)
.setWhen(System.currentTimeMillis())
.setContentTitle(appName)
.setTicker(appName)
.setContentIntent(contentIntent);
final String message = extras.getString("message");
if (message != null) {
mBuilder.setContentText(message);
} else {
mBuilder.setContentText("<missing message content>");
}
final String msgcnt = extras.getString("msgcnt");
if (msgcnt != null) {
mBuilder.setNumber(Integer.parseInt(msgcnt));
}
mNotificationManager.notify(appName, NOTIFICATION_ID, mBuilder.build());
tryPlayRingtone();
}