entry : idTags.entrySet()) {
Integer id = entry.getKey();
String tag = entry.getValue();
- if (tag != null) cancelNotification(tag, id);
+ if (tag != null) {
+ cancelNotification(tag, id);
+ }
}
}
@@ -657,7 +691,9 @@ public void cancelNotificationsWithTag(String tag) {
public void cancelScheduledNotifications() {
for (String id : sharedPreferences.getAll().keySet()) {
- cancelScheduledNotification(id);
+ if (!id.equals(HeadlessPushPlugin.KEY_CALLBACK) && !id.equals(HeadlessPushPlugin.KEY_HANDLER)) {
+ cancelScheduledNotification(id);
+ }
}
}
diff --git a/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/logger/HMSLogger.java b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/logger/HMSLogger.java
index f1eac9b6..94b8da52 100644
--- a/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/logger/HMSLogger.java
+++ b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/logger/HMSLogger.java
@@ -40,7 +40,7 @@ public final class HMSLogger {
private static final String PLATFORM = "Flutter";
- private static final String VERSION = "5.0.2.304";
+ private static final String VERSION = "5.1.1.301";
private static final String SERVICE = "Cross-Platform";
diff --git a/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/BackgroundMessageBroadcastReceiver.java b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/BackgroundMessageBroadcastReceiver.java
index 49712b5a..818f8c40 100644
--- a/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/BackgroundMessageBroadcastReceiver.java
+++ b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/BackgroundMessageBroadcastReceiver.java
@@ -31,7 +31,8 @@
public class BackgroundMessageBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = BackgroundMessageBroadcastReceiver.class.getSimpleName();
- public static final String BACKGROUND_REMOTE_MESSAGE = "com.huawei.hms.flutter.push.receiver.BACKGROUND_REMOTE_MESSAGE";
+ public static final String BACKGROUND_REMOTE_MESSAGE
+ = "com.huawei.hms.flutter.push.receiver.BACKGROUND_REMOTE_MESSAGE";
@Override
public void onReceive(Context context, Intent intent) {
@@ -40,7 +41,7 @@ public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BACKGROUND_REMOTE_MESSAGE.equals(action)) {
Bundle result = intent.getExtras();
- Log.d("Receiver-java", intent.getExtras().toString());
+ Log.d(TAG, result != null ? result.toString() : "");
if (result != null) {
HeadlessPushPlugin headLess = new HeadlessPushPlugin(context);
headLess.handleBackgroundMessage(context, (RemoteMessage) result.get(Param.MESSAGE.code()));
diff --git a/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/MultiSenderTokenReceiver.java b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/MultiSenderTokenReceiver.java
new file mode 100644
index 00000000..d651d6fb
--- /dev/null
+++ b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/MultiSenderTokenReceiver.java
@@ -0,0 +1,49 @@
+/*
+ Copyright 2020-2021. Huawei Technologies Co., Ltd. All rights reserved.
+
+ Licensed under the Apache License, Version 2.0 (the "License")
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+package com.huawei.hms.flutter.push.receiver;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+
+import com.huawei.hms.flutter.push.constants.Code;
+import com.huawei.hms.flutter.push.constants.PushIntent;
+
+import io.flutter.plugin.common.EventChannel;
+
+import java.util.Objects;
+
+public class MultiSenderTokenReceiver extends BroadcastReceiver {
+ final EventChannel.EventSink events;
+
+ public MultiSenderTokenReceiver(EventChannel.EventSink events) {
+ this.events = events;
+ }
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ if (Objects.requireNonNull(intent.getAction()).equals(PushIntent.MULTI_SENDER_TOKEN_INTENT_ACTION.id())) {
+ String err = intent.getStringExtra(PushIntent.MULTI_SENDER_TOKEN_ERROR.id());
+ if (err == null) {
+ String res = intent.getStringExtra(PushIntent.MULTI_SENDER_TOKEN.id());
+ this.events.success(res);
+ } else {
+ this.events.error(Code.RESULT_ERROR.code(), err, "");
+ }
+ }
+ }
+}
diff --git a/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/DataMessageReceiver.java b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/RemoteDataMessageReceiver.java
similarity index 89%
rename from flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/DataMessageReceiver.java
rename to flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/RemoteDataMessageReceiver.java
index fd17e8c9..d9b0e67e 100644
--- a/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/DataMessageReceiver.java
+++ b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/RemoteDataMessageReceiver.java
@@ -24,10 +24,10 @@
import io.flutter.plugin.common.EventChannel;
-public class DataMessageReceiver extends BroadcastReceiver {
+public class RemoteDataMessageReceiver extends BroadcastReceiver {
final EventChannel.EventSink events;
- public DataMessageReceiver(EventChannel.EventSink events) {
+ public RemoteDataMessageReceiver(EventChannel.EventSink events) {
this.events = events;
}
diff --git a/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/common/NotificationIntentListener.java b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/common/NotificationIntentListener.java
index ccb77421..11f43076 100644
--- a/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/common/NotificationIntentListener.java
+++ b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/common/NotificationIntentListener.java
@@ -16,6 +16,7 @@
package com.huawei.hms.flutter.push.receiver.common;
+import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
@@ -26,15 +27,15 @@
import com.huawei.hms.flutter.push.utils.Utils;
import com.huawei.hms.push.RemoteMessage;
+import io.flutter.Log;
+import io.flutter.plugin.common.MethodChannel;
+import io.flutter.plugin.common.PluginRegistry.NewIntentListener;
+
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
-import io.flutter.Log;
-import io.flutter.plugin.common.MethodChannel;
-import io.flutter.plugin.common.PluginRegistry.NewIntentListener;
-
/**
* class NotificationIntentListener
*
@@ -47,13 +48,21 @@ public class NotificationIntentListener implements NewIntentListener {
private String initialIntent;
+ private Context context;
+
+ public NotificationIntentListener(Context context) {
+ this.context = context;
+ }
+
@Override
public boolean onNewIntent(Intent intent) {
- handleIntent(intent);
+ if (Utils.checkNotificationFlags(intent)) {
+ handleIntent(intent);
+ }
return false;
}
- public static Map getInitialNotification() {
+ public static synchronized Map getInitialNotification() {
return NotificationIntentListener.initialNotification;
}
@@ -75,16 +84,20 @@ public void handleIntent(Intent intent) {
if (bundleExtras != null) {
RemoteMessage remoteMessage = new RemoteMessage(bundleExtras);
map.put("remoteMessage", RemoteMessageUtils.toMap(remoteMessage));
- Map extras = MapUtils.toMap(BundleUtils.convertJSONObject(bundleExtras));
+ Map extras = MapUtils.toMap(BundleUtils.convertJSONObject(bundleExtras));
map.put("extras", extras);
}
if (Intent.ACTION_VIEW.equals(action)) {
initialIntent = dataString;
- Utils.sendIntent(PushIntent.REMOTE_MESSAGE_NOTIFICATION_INTENT_ACTION, PushIntent.CUSTOM_INTENT,
- initialIntent);
- if (bundleExtras != null) sendNotificationOpenedAppEvent(map);
+ Utils.sendIntent(context, PushIntent.REMOTE_MESSAGE_NOTIFICATION_INTENT_ACTION, PushIntent.CUSTOM_INTENT,
+ initialIntent);
+ if (bundleExtras != null) {
+ sendNotificationOpenedAppEvent(map);
+ }
} else if (Intent.ACTION_MAIN.equals(action) || PushIntent.LOCAL_NOTIFICATION_ACTION.name().equals(action)) {
- if (bundleExtras != null) sendNotificationOpenedAppEvent(map);
+ if (bundleExtras != null) {
+ sendNotificationOpenedAppEvent(map);
+ }
} else {
Log.i("NotificationIntentListener", "Unsupported action intent:" + action);
}
@@ -93,7 +106,8 @@ public void handleIntent(Intent intent) {
private void sendNotificationOpenedAppEvent(Map initialNotification) {
setInitialNotification(initialNotification);
JSONObject jsonObject = new JSONObject(initialNotification);
- Utils.sendIntent(PushIntent.NOTIFICATION_OPEN_ACTION, PushIntent.NOTIFICATION_OPEN, jsonObject.toString());
+ Utils.sendIntent(context, PushIntent.NOTIFICATION_OPEN_ACTION, PushIntent.NOTIFICATION_OPEN,
+ jsonObject.toString());
}
}
diff --git a/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/local/HmsLocalNotificationActionsReceiver.java b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/local/HmsLocalNotificationActionsReceiver.java
index 68dfd90c..4d4dfd1a 100644
--- a/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/local/HmsLocalNotificationActionsReceiver.java
+++ b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/local/HmsLocalNotificationActionsReceiver.java
@@ -16,7 +16,6 @@
package com.huawei.hms.flutter.push.receiver.local;
-import android.app.Application;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
@@ -33,15 +32,20 @@ public class HmsLocalNotificationActionsReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
String intentActionPrefix = context.getPackageName() + ".ACTION_";
- if (intent.getAction() == null || !intent.getAction().startsWith(intentActionPrefix))
+ if (intent.getAction() == null || !intent.getAction().startsWith(intentActionPrefix)) {
return;
+ }
final Bundle bundle = intent.getBundleExtra(NotificationConstants.NOTIFICATION);
- if (bundle == null) return;
+ if (bundle == null) {
+ return;
+ }
- NotificationManager notificationManager =
- (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
- if (notificationManager == null) return;
+ NotificationManager notificationManager = (NotificationManager) context.getSystemService(
+ Context.NOTIFICATION_SERVICE);
+ if (notificationManager == null) {
+ return;
+ }
int id = Integer.parseInt(BundleUtils.get(bundle, NotificationConstants.ID));
@@ -55,12 +59,12 @@ public void onReceive(final Context context, Intent intent) {
}
if (BundleUtils.getB(bundle, NotificationConstants.INVOKE_APP, true)) {
- HmsLocalNotificationController hmsLocalNotificationController =
- new HmsLocalNotificationController((Application) context.getApplicationContext());
+ HmsLocalNotificationController hmsLocalNotificationController = new HmsLocalNotificationController(
+ context.getApplicationContext());
hmsLocalNotificationController.invokeApp(bundle);
} else {
- Utils.sendIntent(PushIntent.LOCAL_NOTIFICATION_CLICK_ACTION, PushIntent.LOCAL_NOTIFICATION_CLICK,
- BundleUtils.convertJSON(bundle));
+ Utils.sendIntent(context, PushIntent.LOCAL_NOTIFICATION_CLICK_ACTION, PushIntent.LOCAL_NOTIFICATION_CLICK,
+ BundleUtils.convertJSON(bundle));
}
}
}
diff --git a/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/local/HmsLocalNotificationBootEventReceiver.java b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/local/HmsLocalNotificationBootEventReceiver.java
index b4aff667..16e0547e 100644
--- a/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/local/HmsLocalNotificationBootEventReceiver.java
+++ b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/receiver/local/HmsLocalNotificationBootEventReceiver.java
@@ -31,13 +31,16 @@
import java.util.Set;
public class HmsLocalNotificationBootEventReceiver extends BroadcastReceiver {
- private final String TAG = HmsLocalNotificationBootEventReceiver.class.getSimpleName();
+ private static final String TAG = HmsLocalNotificationBootEventReceiver.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
- if (intent.getAction() == null) return;
- if (!intent.getAction().equals(Core.ScheduledPublisher.BOOT_EVENT))
+ if (intent.getAction() == null) {
return;
+ }
+ if (!intent.getAction().equals(Core.ScheduledPublisher.BOOT_EVENT)) {
+ return;
+ }
Log.i(TAG, "Loading scheduled notifications....");
@@ -45,22 +48,21 @@ public void onReceive(Context context, Intent intent) {
Set ids = sharedPreferences.getAll().keySet();
Application applicationContext = (Application) context.getApplicationContext();
- HmsLocalNotificationController hmsLocalNotificationController =
- new HmsLocalNotificationController(applicationContext);
+ HmsLocalNotificationController hmsLocalNotificationController = new HmsLocalNotificationController(
+ applicationContext);
for (String id : ids) {
try {
String notificationAttributesJson = sharedPreferences.getString(id, null);
if (notificationAttributesJson != null) {
- NotificationAttributes notificationAttributes =
- NotificationAttributes.fromJson(notificationAttributesJson);
+ NotificationAttributes notificationAttributes = NotificationAttributes.fromJson(
+ notificationAttributesJson);
if (notificationAttributes.getFireDate() < System.currentTimeMillis()) {
- hmsLocalNotificationController
- .localNotificationNow(notificationAttributes.toBundle(), null);
+ hmsLocalNotificationController.localNotificationNow(notificationAttributes.toBundle(), null);
} else {
- hmsLocalNotificationController
- .localNotificationScheduleSetAlarm(notificationAttributes.toBundle());
+ hmsLocalNotificationController.localNotificationScheduleSetAlarm(
+ notificationAttributes.toBundle());
}
}
} catch (Exception e) {
diff --git a/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/utils/ApplicationUtils.java b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/utils/ApplicationUtils.java
index 43252646..b6b3eeb2 100644
--- a/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/utils/ApplicationUtils.java
+++ b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/utils/ApplicationUtils.java
@@ -21,7 +21,7 @@
import java.util.List;
-public class ApplicationUtils {
+public final class ApplicationUtils {
private ApplicationUtils() {
throw new IllegalStateException("Utility class");
@@ -32,12 +32,16 @@ public static boolean isApplicationInForeground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List processInfos = activityManager.getRunningAppProcesses();
- if (processInfos == null) return false;
+ if (processInfos == null) {
+ return false;
+ }
for (ActivityManager.RunningAppProcessInfo processInfo : processInfos) {
- if (processInfo.pkgList.length < 1) return false;
+ if (processInfo.pkgList.length < 1) {
+ return false;
+ }
if (processInfo.processName.equals(context.getPackageName())
- && processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
+ && processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return true;
}
}
diff --git a/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/utils/LocalNotificationUtils.java b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/utils/LocalNotificationUtils.java
index ac5a6123..6c156459 100644
--- a/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/utils/LocalNotificationUtils.java
+++ b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/utils/LocalNotificationUtils.java
@@ -19,10 +19,8 @@
import android.os.Bundle;
import com.huawei.hms.flutter.push.config.NotificationAttributes;
-import com.huawei.hms.flutter.push.constants.Code;
import io.flutter.plugin.common.MethodCall;
-import io.flutter.plugin.common.MethodChannel;
public class LocalNotificationUtils {
@@ -30,11 +28,7 @@ private LocalNotificationUtils() {
throw new IllegalStateException("Utility class");
}
- public static Bundle callArgsToBundle(MethodCall call, MethodChannel.Result result) {
- if (call.arguments == null) {
- result.error(Code.NULL_BUNDLE.code(), "Arguments are empty", "");
- return null;
- }
+ public static Bundle callArgsToBundle(MethodCall call) {
try {
return new NotificationAttributes(call).toBundle();
} catch (Exception e) {
diff --git a/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/utils/MapUtils.java b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/utils/MapUtils.java
index e0461a0f..60432b67 100644
--- a/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/utils/MapUtils.java
+++ b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/utils/MapUtils.java
@@ -16,6 +16,8 @@
package com.huawei.hms.flutter.push.utils;
+import android.os.Bundle;
+
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
@@ -23,6 +25,7 @@
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
+import java.util.Set;
public class MapUtils {
@@ -30,12 +33,13 @@ private MapUtils() {
throw new IllegalStateException("Utility class");
}
-
public static Map toMap(JSONObject jsonObject) {
Map map = new HashMap<>();
- if (jsonObject == null) return map;
+ if (jsonObject == null) {
+ return map;
+ }
Iterator iterator = jsonObject.keys();
try {
@@ -60,4 +64,19 @@ public static Map toMap(JSONObject jsonObject) {
}
+ public static Map bundleToMap(Bundle bundle) {
+ Map map = new HashMap<>();
+ if (bundle != null) {
+ Set keys = bundle.keySet();
+ for (String key : keys) {
+ Object value = bundle.get(key);
+ if (value instanceof Bundle) {
+ map.put(key, bundleToMap((Bundle) value));
+ } else {
+ map.put(key, value);
+ }
+ }
+ }
+ return map;
+ }
}
diff --git a/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/utils/RemoteMessageUtils.java b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/utils/RemoteMessageUtils.java
index 6e39ddd1..f76f69e5 100644
--- a/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/utils/RemoteMessageUtils.java
+++ b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/utils/RemoteMessageUtils.java
@@ -20,13 +20,14 @@
import com.huawei.hms.flutter.push.constants.RemoteMessageAttributes;
import com.huawei.hms.push.RemoteMessage;
+import io.flutter.plugin.common.MethodCall;
+
import org.json.JSONObject;
+import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
-import io.flutter.plugin.common.MethodCall;
-
public class RemoteMessageUtils {
private RemoteMessageUtils() {
@@ -55,62 +56,38 @@ public static Map toMap(RemoteMessage message) {
if (message.getNotification() != null) {
RemoteMessage.Notification notification = message.getNotification();
- notificationContent.put(RemoteMessageAttributes.TITLE,
- notification.getTitle());
+ notificationContent.put(RemoteMessageAttributes.TITLE, notification.getTitle());
notificationContent.put(RemoteMessageAttributes.TITLE_LOCALIZATION_KEY,
- notification.getTitleLocalizationKey());
+ notification.getTitleLocalizationKey());
notificationContent.put(RemoteMessageAttributes.TITLE_LOCALIZATION_ARGS,
- notification.getTitleLocalizationArgs());
+ Arrays.asList(notification.getTitleLocalizationArgs()));
notificationContent.put(RemoteMessageAttributes.BODY_LOCALIZATION_KEY,
- notification.getBodyLocalizationKey());
+ notification.getBodyLocalizationKey());
notificationContent.put(RemoteMessageAttributes.BODY_LOCALIZATION_ARGS,
- notification.getBodyLocalizationArgs());
- notificationContent.put(RemoteMessageAttributes.BODY,
- notification.getBody());
- notificationContent.put(RemoteMessageAttributes.ICON,
- notification.getIcon());
- notificationContent.put(RemoteMessageAttributes.SOUND,
- notification.getSound());
- notificationContent.put(RemoteMessageAttributes.TAG,
- notification.getTag());
- notificationContent.put(RemoteMessageAttributes.COLOR,
- notification.getColor());
- notificationContent.put(RemoteMessageAttributes.CLICK_ACTION,
- notification.getClickAction());
- notificationContent.put(RemoteMessageAttributes.CHANNEL_ID,
- notification.getChannelId());
- notificationContent.put(RemoteMessageAttributes.IMAGE_URL,
- notification.getImageUrl() + "");
- notificationContent.put(RemoteMessageAttributes.LINK,
- notification.getLink() + "");
- notificationContent.put(RemoteMessageAttributes.NOTIFY_ID,
- notification.getNotifyId());
- notificationContent.put(RemoteMessageAttributes.WHEN,
- notification.getWhen());
- notificationContent.put(RemoteMessageAttributes.LIGHT_SETTINGS,
- notification.getLightSettings());
- notificationContent.put(RemoteMessageAttributes.BADGE_NUMBER,
- notification.getBadgeNumber());
- notificationContent.put(RemoteMessageAttributes.IMPORTANCE,
- notification.getImportance());
- notificationContent.put(RemoteMessageAttributes.TICKER,
- notification.getTicker());
- notificationContent.put(RemoteMessageAttributes.VIBRATE_CONFIG,
- notification.getVibrateConfig());
- notificationContent.put(RemoteMessageAttributes.VISIBILITY,
- notification.getVisibility());
- notificationContent.put(RemoteMessageAttributes.INTENT_URI,
- notification.getIntentUri());
- notificationContent.put(RemoteMessageAttributes.IS_AUTO_CANCEL,
- notification.isAutoCancel());
- notificationContent.put(RemoteMessageAttributes.IS_LOCAL_ONLY,
- notification.isLocalOnly());
- notificationContent.put(RemoteMessageAttributes.IS_DEFAULT_LIGHT,
- notification.isDefaultLight());
- notificationContent.put(RemoteMessageAttributes.IS_DEFAULT_SOUND,
- notification.isDefaultSound());
- notificationContent.put(RemoteMessageAttributes.IS_DEFAULT_VIBRATE,
- notification.isDefaultVibrate());
+ Arrays.asList(notification.getBodyLocalizationArgs()));
+ notificationContent.put(RemoteMessageAttributes.BODY, notification.getBody());
+ notificationContent.put(RemoteMessageAttributes.ICON, notification.getIcon());
+ notificationContent.put(RemoteMessageAttributes.SOUND, notification.getSound());
+ notificationContent.put(RemoteMessageAttributes.TAG, notification.getTag());
+ notificationContent.put(RemoteMessageAttributes.COLOR, notification.getColor());
+ notificationContent.put(RemoteMessageAttributes.CLICK_ACTION, notification.getClickAction());
+ notificationContent.put(RemoteMessageAttributes.CHANNEL_ID, notification.getChannelId());
+ notificationContent.put(RemoteMessageAttributes.IMAGE_URL, notification.getImageUrl() + "");
+ notificationContent.put(RemoteMessageAttributes.LINK, notification.getLink() + "");
+ notificationContent.put(RemoteMessageAttributes.NOTIFY_ID, notification.getNotifyId());
+ notificationContent.put(RemoteMessageAttributes.WHEN, notification.getWhen());
+ notificationContent.put(RemoteMessageAttributes.LIGHT_SETTINGS, notification.getLightSettings());
+ notificationContent.put(RemoteMessageAttributes.BADGE_NUMBER, notification.getBadgeNumber());
+ notificationContent.put(RemoteMessageAttributes.IMPORTANCE, notification.getImportance());
+ notificationContent.put(RemoteMessageAttributes.TICKER, notification.getTicker());
+ notificationContent.put(RemoteMessageAttributes.VIBRATE_CONFIG, notification.getVibrateConfig());
+ notificationContent.put(RemoteMessageAttributes.VISIBILITY, notification.getVisibility());
+ notificationContent.put(RemoteMessageAttributes.INTENT_URI, notification.getIntentUri());
+ notificationContent.put(RemoteMessageAttributes.IS_AUTO_CANCEL, notification.isAutoCancel());
+ notificationContent.put(RemoteMessageAttributes.IS_LOCAL_ONLY, notification.isLocalOnly());
+ notificationContent.put(RemoteMessageAttributes.IS_DEFAULT_LIGHT, notification.isDefaultLight());
+ notificationContent.put(RemoteMessageAttributes.IS_DEFAULT_SOUND, notification.isDefaultSound());
+ notificationContent.put(RemoteMessageAttributes.IS_DEFAULT_VIBRATE, notification.isDefaultVibrate());
content.put(RemoteMessageAttributes.NOTIFICATION, notificationContent);
}
@@ -120,31 +97,34 @@ public static Map toMap(RemoteMessage message) {
public static RemoteMessage callArgsToRemoteMsg(MethodCall call) {
String to = call.argument(RemoteMessageAttributes.TO);
- if (to == null || to.equals("")) to = Core.REMOTE_MESSAGE_UPLINK_TO;
+ if (to == null || to.equals("")) {
+ to = Core.REMOTE_MESSAGE_UPLINK_TO;
+ }
RemoteMessage.Builder builder = new RemoteMessage.Builder(to);
- String messageId = call.hasArgument(RemoteMessageAttributes.MESSAGE_ID) ?
- (String) call.argument(RemoteMessageAttributes.MESSAGE_ID) :
- NotificationConfigUtils.generateNotificationId();
- String messageType = call.hasArgument(RemoteMessageAttributes.MESSAGE_TYPE) ?
- (String) call.argument(RemoteMessageAttributes.MESSAGE_TYPE) : "hms";
- int ttl = call.hasArgument(RemoteMessageAttributes.TTL) ?
- (int) call.argument(RemoteMessageAttributes.TTL) : 120;
- String collapseKey = call.hasArgument(RemoteMessageAttributes.COLLAPSE_KEY) ?
- (String) call.argument(RemoteMessageAttributes.COLLAPSE_KEY) : "-1";
- int receiptMode = call.hasArgument(RemoteMessageAttributes.RECEIPT_MODE) ?
- (int) call.argument(RemoteMessageAttributes.RECEIPT_MODE) : 1; // Default Mode is 0
- int sendMode = call.hasArgument(RemoteMessageAttributes.SEND_MODE) ?
- (int) call.argument(RemoteMessageAttributes.SEND_MODE) : 1; // Default Mode is 0
+ String messageId = call.hasArgument(RemoteMessageAttributes.MESSAGE_ID) ? (String) call.argument(
+ RemoteMessageAttributes.MESSAGE_ID) : NotificationConfigUtils.generateNotificationId();
+ String messageType = call.hasArgument(RemoteMessageAttributes.MESSAGE_TYPE) ? (String) call.argument(
+ RemoteMessageAttributes.MESSAGE_TYPE) : "hms";
+ int ttl = call.hasArgument(RemoteMessageAttributes.TTL)
+ ? (int) call.argument(RemoteMessageAttributes.TTL)
+ : 120;
+ String collapseKey = call.hasArgument(RemoteMessageAttributes.COLLAPSE_KEY) ? (String) call.argument(
+ RemoteMessageAttributes.COLLAPSE_KEY) : "-1";
+ int receiptMode = call.hasArgument(RemoteMessageAttributes.RECEIPT_MODE) ? (int) call.argument(
+ RemoteMessageAttributes.RECEIPT_MODE) : 1; // Default Mode is 0
+ int sendMode = call.hasArgument(RemoteMessageAttributes.SEND_MODE) ? (int) call.argument(
+ RemoteMessageAttributes.SEND_MODE) : 1; // Default Mode is 0
HashMap map = null;
- if (call.hasArgument(RemoteMessageAttributes.DATA) &&
- call.argument(RemoteMessageAttributes.DATA) instanceof HashMap) {
+ if (call.hasArgument(RemoteMessageAttributes.DATA) && call.argument(
+ RemoteMessageAttributes.DATA) instanceof HashMap) {
map = call.argument(RemoteMessageAttributes.DATA);
}
- if (map != null)
+ if (map != null) {
builder.setData(map);
+ }
builder.setCollapseKey(collapseKey);
builder.setMessageId(messageId);
diff --git a/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/utils/Utils.java b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/utils/Utils.java
index 8f13169f..32658f11 100644
--- a/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/utils/Utils.java
+++ b/flutter-hms-push/android/src/main/java/com/huawei/hms/flutter/push/utils/Utils.java
@@ -16,17 +16,22 @@
package com.huawei.hms.flutter.push.utils;
+import android.content.Context;
import android.content.Intent;
+import android.os.Handler;
+import android.os.Looper;
import android.util.Log;
-import com.huawei.hms.flutter.push.PushPlugin;
+import com.huawei.hms.flutter.push.constants.Code;
+import com.huawei.hms.flutter.push.constants.NotificationConstants;
import com.huawei.hms.flutter.push.constants.PushIntent;
+import io.flutter.plugin.common.MethodCall;
+import io.flutter.plugin.common.MethodChannel;
+
import java.io.InvalidClassException;
import java.util.Objects;
-import io.flutter.plugin.common.MethodCall;
-
/**
* class Utils
*
@@ -38,7 +43,7 @@ private Utils() {
throw new IllegalStateException("Utility class");
}
- private static String TAG = "FlutterHmsUtils";
+ private static final String TAG = "FlutterHmsUtils";
public static boolean isEmpty(Object str) {
return str == null || str.toString().trim().length() == 0;
@@ -77,12 +82,40 @@ public static double getDoubleArgument(MethodCall call, String argument) {
}
}
- public static void sendIntent(PushIntent action, PushIntent extraName, String result) {
+ public static void sendIntent(Context context, PushIntent action, PushIntent extraName, String result) {
Intent intent = new Intent();
- intent.setPackage(PushPlugin.getContext().getPackageName());
+ intent.setPackage(context.getPackageName());
intent.setAction(action.id());
intent.putExtra(extraName.id(), result);
- PushPlugin.getContext().sendBroadcast(intent);
+ context.sendBroadcast(intent);
+ }
+
+ /**
+ * Checks if the intent is a tapped notification.
+ *
+ * @param intent The intent object to be checked.
+ * @return true if the intent is identified as a notification, false otherwise.
+ */
+ public static boolean checkNotificationFlags(Intent intent) {
+ int flagNumber = Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_RECEIVER_REPLACE_PENDING
+ | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT;
+ int flagNumberAndBroughtToFront = flagNumber | Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT;
+ return intent.getFlags() == flagNumber || intent.getFlags() == flagNumberAndBroughtToFront
+ || intent.getBundleExtra(NotificationConstants.NOTIFICATION) != null || intent.getDataString() != null;
+ }
+
+ public static void handleSuccessOnUIThread(final MethodChannel.Result result) {
+ new Handler(Looper.getMainLooper()).post(() -> result.success(Code.RESULT_SUCCESS.code()));
+ }
+
+ public static void handleErrorOnUIThread(final MethodChannel.Result result, final String errorMessage) {
+ new Handler(Looper.getMainLooper()).post(() -> result.error(Code.RESULT_ERROR.code(), errorMessage, ""));
+ }
+
+ public static void handleErrorOnUIThread(final MethodChannel.Result result, final String errorCode,
+ final String errorMessage, final String errorDetails) {
+ new Handler(Looper.getMainLooper()).post(
+ () -> result.error(errorCode, errorMessage, errorDetails != null ? errorDetails : ""));
}
}
diff --git a/flutter-hms-push/example/.gitignore b/flutter-hms-push/example/.gitignore
index 1ba9c339..55d320e6 100644
--- a/flutter-hms-push/example/.gitignore
+++ b/flutter-hms-push/example/.gitignore
@@ -29,6 +29,7 @@
.pub-cache/
.pub/
/build/
+*.lock
# Web related
lib/generated_plugin_registrant.dart
diff --git a/flutter-hms-push/example/android/gradle/wrapper/gradle-wrapper.properties b/flutter-hms-push/example/android/gradle/wrapper/gradle-wrapper.properties
index a4b44297..442d9132 100644
--- a/flutter-hms-push/example/android/gradle/wrapper/gradle-wrapper.properties
+++ b/flutter-hms-push/example/android/gradle/wrapper/gradle-wrapper.properties
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
diff --git a/flutter-hms-push/example/android/gradlew b/flutter-hms-push/example/android/gradlew
index cccdd3d5..4f906e0c 100644
--- a/flutter-hms-push/example/android/gradlew
+++ b/flutter-hms-push/example/android/gradlew
@@ -1,5 +1,21 @@
#!/usr/bin/env sh
+#
+# Copyright 2015 the original author or authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
##############################################################################
##
## Gradle start up script for UN*X
@@ -28,7 +44,7 @@ APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-DEFAULT_JVM_OPTS=""
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
@@ -66,6 +82,7 @@ esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
@@ -109,10 +126,11 @@ if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
-# For Cygwin, switch paths to Windows format before running java
-if $cygwin ; then
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
@@ -138,19 +156,19 @@ if $cygwin ; then
else
eval `echo args$i`="\"$arg\""
fi
- i=$((i+1))
+ i=`expr $i + 1`
done
case $i in
- (0) set -- ;;
- (1) set -- "$args0" ;;
- (2) set -- "$args0" "$args1" ;;
- (3) set -- "$args0" "$args1" "$args2" ;;
- (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
- (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
- (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
- (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
- (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
- (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+ 0) set -- ;;
+ 1) set -- "$args0" ;;
+ 2) set -- "$args0" "$args1" ;;
+ 3) set -- "$args0" "$args1" "$args2" ;;
+ 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+ 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+ 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+ 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+ 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+ 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
@@ -159,14 +177,9 @@ save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
-APP_ARGS=$(save "$@")
+APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
-# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
-if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
- cd "$(dirname "$0")"
-fi
-
exec "$JAVACMD" "$@"
diff --git a/flutter-hms-push/example/android/gradlew.bat b/flutter-hms-push/example/android/gradlew.bat
index f9553162..107acd32 100644
--- a/flutter-hms-push/example/android/gradlew.bat
+++ b/flutter-hms-push/example/android/gradlew.bat
@@ -1,3 +1,19 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@@ -13,15 +29,18 @@ if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-set DEFAULT_JVM_OPTS=
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
-if "%ERRORLEVEL%" == "0" goto init
+if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
@@ -35,7 +54,7 @@ goto fail
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
-if exist "%JAVA_EXE%" goto init
+if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
@@ -45,28 +64,14 @@ echo location of your Java installation.
goto fail
-:init
-@rem Get command-line arguments, handling Windows variants
-
-if not "%OS%" == "Windows_NT" goto win9xME_args
-
-:win9xME_args
-@rem Slurp the command line arguments.
-set CMD_LINE_ARGS=
-set _SKIP=2
-
-:win9xME_args_slurp
-if "x%~1" == "x" goto execute
-
-set CMD_LINE_ARGS=%*
-
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
@rem Execute Gradle
-"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
diff --git a/flutter-hms-push/example/lib/local_notification.dart b/flutter-hms-push/example/lib/local_notification_page.dart
similarity index 86%
rename from flutter-hms-push/example/lib/local_notification.dart
rename to flutter-hms-push/example/lib/local_notification_page.dart
index d1394f7a..93b9fb92 100644
--- a/flutter-hms-push/example/lib/local_notification.dart
+++ b/flutter-hms-push/example/lib/local_notification_page.dart
@@ -16,11 +16,10 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
-import 'package:huawei_push/local_notification/local_notification.dart';
-import 'package:huawei_push/push.dart';
+import 'package:huawei_push/huawei_push_library.dart';
class LocalNotificationPage extends StatefulWidget {
- LocalNotificationPage({Key key}) : super(key: key);
+ LocalNotificationPage({Key? key}) : super(key: key);
@override
_LocalNotificationPageState createState() => _LocalNotificationPageState();
@@ -41,7 +40,7 @@ class _LocalNotificationPageState extends State {
TextEditingController tagTextController = TextEditingController();
TextEditingController logTextController = TextEditingController();
- Map receivedNotification;
+ late Map receivedNotification;
Map defaultNotification = {
HMSLocalNotificationAttr.TITLE: 'Notification Title',
HMSLocalNotificationAttr.MESSAGE: 'Notification Message',
@@ -83,33 +82,39 @@ class _LocalNotificationPageState extends State {
onError: _onLocalNotificationClickErr);
}
- _onLocalNotificationClickEvent(Map event) {
+ void _onLocalNotificationClickEvent(Map event) {
receivedNotification = event;
if (mounted) {
// Check if widget is still mounted to call setState
showResult(
"onLocalNotificationClickEvent", receivedNotification.toString());
}
- Push.showToast("Clicked: " + receivedNotification['action'] ?? " ");
+ Push.showToast("Clicked: " + receivedNotification['action']);
if (receivedNotification[HMSLocalNotificationAttr.ACTION] == "Yes") {
int id = int.parse(receivedNotification[HMSLocalNotificationAttr.ID]);
- String tag = receivedNotification[HMSLocalNotificationAttr.TAG];
- Push.cancelNotificationsWithIdTag({id: tag}).then((_) => showResult(
- "cancelNotificationsWithIdTag",
- "Cancelled, Notification with id: $id, and tag: $tag"));
+ String? tag = receivedNotification[HMSLocalNotificationAttr.TAG];
+ if (tag != null) {
+ Push.cancelNotificationsWithIdTag({id: tag}).then((_) => showResult(
+ "cancelNotificationsWithIdTag",
+ "Cancelled, Notification with id: $id, and tag: $tag"));
+ } else {
+ Push.cancelNotificationsWithId([id]).then((_) => showResult(
+ "cancelNotificationsWithId",
+ "Cancelled, Notification with id: $id"));
+ }
}
}
- _onLocalNotificationClickErr(dynamic err) =>
+ void _onLocalNotificationClickErr(dynamic err) =>
showResult("onLocalNotificationClickError", err.toString());
- _clearLog() {
+ void _clearLog() {
setState(() {
logTextController.text = "";
});
}
- _localNotification() async {
+ void _localNotification() async {
try {
Map notification = _constructNotificationMap();
Map response =
@@ -120,7 +125,7 @@ class _LocalNotificationPageState extends State {
}
}
- _localNotificationOngoing() async {
+ void _localNotificationOngoing() async {
try {
Map ongoingNotification = _constructNotificationMap();
ongoingNotification[HMSLocalNotificationAttr.ONGOING] = true;
@@ -132,7 +137,7 @@ class _LocalNotificationPageState extends State {
}
}
- _localNotificationSound() async {
+ void _localNotificationSound() async {
try {
Map soundNotification = _constructNotificationMap();
soundNotification[HMSLocalNotificationAttr.PLAY_SOUND] = true;
@@ -146,7 +151,7 @@ class _LocalNotificationPageState extends State {
}
}
- _localNotificationVibrate() async {
+ void _localNotificationVibrate() async {
try {
Map vibrateNotification = _constructNotificationMap();
vibrateNotification[HMSLocalNotificationAttr.VIBRATE] = true;
@@ -159,7 +164,7 @@ class _LocalNotificationPageState extends State {
}
}
- _localNotificationBigImage() async {
+ void _localNotificationBigImage() async {
try {
Map bigImgNotification = _constructNotificationMap();
bigImgNotification[HMSLocalNotificationAttr.BIG_PICTURE_URL] =
@@ -172,7 +177,7 @@ class _LocalNotificationPageState extends State {
}
}
- _localNotificationRepeat() async {
+ void _localNotificationRepeat() async {
try {
Map repeatedNotification = _constructNotificationMap();
repeatedNotification[HMSLocalNotificationAttr.REPEAT_TYPE] =
@@ -185,7 +190,7 @@ class _LocalNotificationPageState extends State {
}
}
- _localNotificationScheduled() async {
+ void _localNotificationScheduled() async {
try {
Map scheduledNotification = _constructNotificationMap();
scheduledNotification[HMSLocalNotificationAttr.FIRE_DATE] =
@@ -199,30 +204,30 @@ class _LocalNotificationPageState extends State {
}
}
- _channelBlocked() async {
+ void _channelBlocked() async {
bool blocked = await Push.channelBlocked(
'huawei-hms-flutter-push-channel-id-4-default');
showResult("channelBlocked", blocked.toString());
}
- _channelExists() async {
+ void _channelExists() async {
bool exists = await Push.channelExists(
'huawei-hms-flutter-push-channel-id-4-default');
showResult("channelExists", exists.toString());
}
- _getChannels() async {
+ void _getChannels() async {
List channels = await Push.getChannels();
showResult("getChannels", channels.toString());
}
- _deleteChannel() async {
+ void _deleteChannel() async {
String result = await Push.deleteChannel(
"huawei-hms-flutter-push-channel-id-4-default");
showResult("deleteChannel", result);
}
- _getNotifications() async {
+ void _getNotifications() async {
List notifications = await Push.getNotifications();
showResult(
"getNotifications",
@@ -232,7 +237,7 @@ class _LocalNotificationPageState extends State {
print("getNotification result: " + notifications.toString());
}
- _getScheduledNotifications() async {
+ void _getScheduledNotifications() async {
List scheduledNotifications = await Push.getScheduledNotifications();
showResult("getScheduledNotifications",
scheduledNotifications.length.toString() + " scheduled notifications");
@@ -240,12 +245,13 @@ class _LocalNotificationPageState extends State {
scheduledNotifications.toString());
}
- showResult(String name, [String msg = "Button pressed."]) {
+ void showResult(String name, [String msg = "Button pressed."]) {
appendLog("[" + name + "]" + ": " + msg);
+ print("[" + name + "]" + ": " + msg);
if (msg.isNotEmpty) Push.showToast(msg);
}
- appendLog([String msg = "Button pressed."]) {
+ void appendLog([String msg = "Button pressed."]) {
setState(() {
logTextController.text = msg + "\n" + logTextController.text;
});
@@ -258,7 +264,7 @@ class _LocalNotificationPageState extends State {
}
Widget customTextField(TextEditingController controller, String hintText,
- {EdgeInsets customPadding}) {
+ {EdgeInsets? customPadding}) {
return Padding(
padding: customPadding ?? padding,
child: Container(
@@ -295,18 +301,19 @@ class _LocalNotificationPageState extends State {
);
}
- Widget customButton(String label, Function callback, {Color color}) {
+ Widget customButton(String label, Function() callback, {Color? color}) {
return Expanded(
flex: 5,
child: Padding(
padding: padding.copyWith(top: 0.0, bottom: 0.0),
- child: RaisedButton(
- padding: EdgeInsets.zero,
- color: color,
+ child: ElevatedButton(
onPressed: callback,
+ style: ElevatedButton.styleFrom(
+ primary: color ?? Colors.grey.shade300,
+ ),
child: Text(
label,
- style: TextStyle(fontSize: 12),
+ style: TextStyle(fontSize: 12, color: Colors.black87),
),
),
),
@@ -401,8 +408,8 @@ class _LocalNotificationPageState extends State {
children: [
customButton(
'cancelAllNotifications',
- () => Push.cancelAllNotifications()
- .then((_) => showResult("cancelAllNotifications", ""))),
+ () => Push.cancelAllNotifications().then(
+ (_) => showResult("cancelAllNotifications", "Success"))),
customButton('getNotifications', () => _getNotifications()),
],
),
@@ -410,8 +417,8 @@ class _LocalNotificationPageState extends State {
children: [
customButton(
'cancelScheduledNotifications',
- () => Push.cancelScheduledNotifications().then(
- (_) => showResult("cancelScheduledNotifications", ""))),
+ () => Push.cancelScheduledNotifications().then((_) =>
+ showResult("cancelScheduledNotifications", "Success"))),
customButton('getScheduledNotifications',
() => _getScheduledNotifications()),
],
@@ -420,8 +427,8 @@ class _LocalNotificationPageState extends State {
children: [
customButton(
'cancelNotificationsWithTag',
- () => Push.cancelNotificationsWithTag('hms_tag').then(
- (_) => showResult("cancelNotificationsWithTag", ""))),
+ () => Push.cancelNotificationsWithTag('hms_tag').then((_) =>
+ showResult("cancelNotificationsWithTag", "Success"))),
customButton('getChannels', () => _getChannels()),
],
),
@@ -429,8 +436,8 @@ class _LocalNotificationPageState extends State {
children: [
customButton(
'cancelNotifications',
- () => Push.cancelNotifications()
- .then((_) => showResult("cancelNotifications", ""))),
+ () => Push.cancelNotifications().then(
+ (_) => showResult("cancelNotifications", "Success"))),
customButton('deleteChannel', () => _deleteChannel()),
],
),
diff --git a/flutter-hms-push/example/lib/main.dart b/flutter-hms-push/example/lib/main.dart
index 627cc7d5..ae120de0 100644
--- a/flutter-hms-push/example/lib/main.dart
+++ b/flutter-hms-push/example/lib/main.dart
@@ -20,11 +20,11 @@ import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
-import 'package:huawei_push/model/remote_message.dart';
-import 'package:huawei_push/local_notification/local_notification.dart';
-import 'package:huawei_push/push.dart';
+import 'package:huawei_push/huawei_push_library.dart';
+import 'package:huawei_push_example/multi_sender_page.dart';
+
import 'custom_intent_page.dart';
-import 'local_notification.dart';
+import 'local_notification_page.dart';
void main() {
runApp(MaterialApp(home: MyApp()));
@@ -36,8 +36,8 @@ class MyApp extends StatefulWidget {
}
class _MyAppState extends State {
- TextEditingController logTextController;
- TextEditingController topicTextController;
+ late TextEditingController logTextController;
+ late TextEditingController topicTextController;
final padding = EdgeInsets.symmetric(vertical: 1.0, horizontal: 16);
@@ -49,21 +49,25 @@ class _MyAppState extends State {
}
void _onTokenError(Object error) {
- PlatformException e = error;
- showResult("TokenErrorEvent", e.message);
+ PlatformException e = error as PlatformException;
+ showResult("TokenErrorEvent", e.message!);
}
static void backgroundMessageCallback(RemoteMessage remoteMessage) async {
- String data = remoteMessage.data;
-
- Push.localNotification({
- HMSLocalNotificationAttr.TITLE: '[Headless] DataMessage Received',
- HMSLocalNotificationAttr.MESSAGE: data
- });
+ String? data = remoteMessage.data;
+ if (data != null) {
+ print("Background message is received, sending local notification.");
+ Push.localNotification({
+ HMSLocalNotificationAttr.TITLE: '[Headless] DataMessage Received',
+ HMSLocalNotificationAttr.MESSAGE: data
+ });
+ } else {
+ print("Background message is received. There is no data in the message.");
+ }
}
void _onMessageReceived(RemoteMessage remoteMessage) {
- String data = remoteMessage.data;
+ String? data = remoteMessage.data;
if (data != null) {
Push.localNotification({
HMSLocalNotificationAttr.TITLE: 'DataMessage Received',
@@ -84,11 +88,11 @@ class _MyAppState extends State {
}
void _onRemoteMessageSendError(Object error) {
- PlatformException e = error;
+ PlatformException e = error as PlatformException;
showResult("RemoteMessageSendError", "Error: " + e.toString());
}
- void _onNewIntent(String intentString) {
+ void _onNewIntent(String? intentString) {
// For navigating to the custom intent page (deep link) the custom
// intent that sent from the push kit console is:
// app://app2
@@ -97,7 +101,7 @@ class _MyAppState extends State {
showResult('CustomIntentEvent: ', intentString);
List parsedString = intentString.split("://");
if (parsedString[1] == "app2") {
- SchedulerBinding.instance.addPostFrameCallback((timeStamp) {
+ SchedulerBinding.instance?.addPostFrameCallback((timeStamp) {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => CustomIntentPage()));
});
@@ -106,20 +110,24 @@ class _MyAppState extends State {
}
void _onIntentError(Object err) {
- PlatformException e = err;
+ PlatformException e = err as PlatformException;
print("Error on intent stream: " + e.toString());
}
void _onNotificationOpenedApp(dynamic initialNotification) {
- showResult("onNotificationOpenedApp", initialNotification.toString());
- print("[onNotificationOpenedApp]" + initialNotification.toString());
+ if (initialNotification != null) {
+ showResult("onNotificationOpenedApp", initialNotification.toString());
+ print("[onNotificationOpenedApp]" + initialNotification.toString());
+ }
}
@override
void initState() {
super.initState();
+ Push.enableLogger();
logTextController = new TextEditingController();
topicTextController = new TextEditingController();
+ Push.disableLogger();
initPlatformState();
}
@@ -130,7 +138,7 @@ class _MyAppState extends State {
Push.onNotificationOpenedApp.listen(_onNotificationOpenedApp);
var initialNotification = await Push.getInitialNotification();
_onNotificationOpenedApp(initialNotification);
- String intent = await Push.getInitialIntent();
+ String? intent = await Push.getInitialIntent();
_onNewIntent(intent);
Push.onMessageReceivedStream
.listen(_onMessageReceived, onError: _onMessageReceiveError);
@@ -147,8 +155,8 @@ class _MyAppState extends State {
@override
void dispose() {
- logTextController?.dispose();
- topicTextController?.dispose();
+ logTextController.dispose();
+ topicTextController.dispose();
super.dispose();
}
@@ -163,12 +171,12 @@ class _MyAppState extends State {
}
void getId() async {
- String result = await Push.getId();
+ String? result = await Push.getId();
showResult("getId", result);
}
void getAAID() async {
- String result = await Push.getAAID();
+ String? result = await Push.getAAID();
showResult("getAAID", result);
}
@@ -178,7 +186,7 @@ class _MyAppState extends State {
}
void getOdid() async {
- String result = await Push.getOdid();
+ String? result = await Push.getOdid();
showResult("getOdid", result);
}
@@ -187,6 +195,11 @@ class _MyAppState extends State {
showResult("getCreationTime", result);
}
+ void deleteToken() async {
+ String result = await Push.deleteToken("");
+ showResult("deleteToken", result);
+ }
+
void deleteAAID() async {
String result = await Push.deleteAAID();
showResult("deleteAAID", result);
@@ -230,7 +243,7 @@ class _MyAppState extends State {
void isAutoInitEnabled() async {
bool result = await Push.isAutoInitEnabled();
- showResult("isAutoInitEnabled", result ? "Enabled" : "Disabled");
+ showResult("isAutoInitEnabled", result.toString());
}
void getInitialNotification() async {
@@ -239,8 +252,8 @@ class _MyAppState extends State {
}
void getInitialIntent() async {
- final String initialIntent = await Push.getInitialIntent();
- showResult("getInitialIntent", initialIntent ?? '');
+ final String? initialIntent = await Push.getInitialIntent();
+ showResult("getInitialIntent", initialIntent);
}
void getAgConnectValues() async {
@@ -254,9 +267,13 @@ class _MyAppState extends State {
});
}
- void showResult(String name, [String msg = "Button pressed."]) {
+ void showResult(String name, [String? msg = "Button pressed."]) {
+ if (msg == null) {
+ msg = "";
+ }
appendLog("[" + name + "]" + ": " + msg);
- if (msg.isNotEmpty) Push.showToast("[" + name + "]: " + msg);
+ print("[" + name + "]" + ": " + msg);
+ Push.showToast("[" + name + "]: " + msg);
}
void appendLog([String msg = "Button pressed."]) {
@@ -270,18 +287,22 @@ class _MyAppState extends State {
Function func,
String txt, {
double fontSize = 16.0,
- Color color,
+ Color? color,
}) {
return Expanded(
flex: flex,
child: Padding(
padding: padding,
- child: RaisedButton(
- onPressed: func,
- color: color,
+ child: ElevatedButton(
+ onPressed: () {
+ func();
+ },
+ style: ElevatedButton.styleFrom(
+ primary: color ?? Colors.grey.shade300,
+ ),
child: Text(
txt,
- style: TextStyle(fontSize: fontSize),
+ style: TextStyle(fontSize: fontSize, color: Colors.black87),
),
),
),
@@ -317,6 +338,14 @@ class _MyAppState extends State {
'Local Notification',
color: Colors.blue),
]),
+ Row(children: [
+ expandedButton(
+ 5,
+ () => Navigator.of(context).push(MaterialPageRoute(
+ builder: (context) => MultiSenderPage())),
+ 'Multi Sender Page',
+ color: Colors.yellow),
+ ]),
Row(children: [
expandedButton(5, () => turnOnPush(), 'TurnOnPush', fontSize: 20),
expandedButton(5, () => turnOffPush(), 'TurnOffPush',
@@ -334,7 +363,7 @@ class _MyAppState extends State {
fontSize: 20)
]),
Row(children: [
- expandedButton(5, () => Push.deleteToken(""), 'DeleteToken',
+ expandedButton(5, () => deleteToken(), 'DeleteToken',
fontSize: 20),
expandedButton(5, () => deleteAAID(), 'DeleteAAID', fontSize: 20)
]),
diff --git a/flutter-hms-push/example/lib/multi_sender_page.dart b/flutter-hms-push/example/lib/multi_sender_page.dart
new file mode 100644
index 00000000..dd997549
--- /dev/null
+++ b/flutter-hms-push/example/lib/multi_sender_page.dart
@@ -0,0 +1,259 @@
+/*
+ Copyright 2020-2021. Huawei Technologies Co., Ltd. All rights reserved.
+
+ Licensed under the Apache License, Version 2.0 (the "License")
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+import 'package:flutter/material.dart';
+import 'package:huawei_push/huawei_push_library.dart';
+
+class MultiSenderPage extends StatefulWidget {
+ MultiSenderPage({Key? key}) : super(key: key);
+
+ @override
+ _MultiSenderPageState createState() => _MultiSenderPageState();
+}
+
+class _MultiSenderPageState extends State {
+ @override
+ void initState() {
+ super.initState();
+ Push.getMultiSenderTokenStream
+ .listen(_onMultiSenderTokenReceived, onError: _onMultiSenderTokenError);
+ }
+
+ void _onMultiSenderTokenReceived(Map multiSenderTokenEvent) {
+ showResult('onMultiSenderTokenReceived', multiSenderTokenEvent.toString());
+ }
+
+ void _onMultiSenderTokenError(dynamic error) {
+ showResult('onMultiSenderTokenError', error.toString());
+ }
+
+ TextEditingController logTextController = TextEditingController();
+ final padding = EdgeInsets.symmetric(vertical: 1.0, horizontal: 10);
+ final TextStyle _textStyle = TextStyle(fontSize: 16);
+ Widget customTextField(TextEditingController controller, String hintText,
+ {EdgeInsets? customPadding}) {
+ return Padding(
+ padding: customPadding ?? padding,
+ child: Container(
+ child: TextField(
+ controller: controller,
+ style: TextStyle(fontWeight: FontWeight.bold),
+ textAlign: TextAlign.center,
+ decoration: InputDecoration(
+ focusedBorder: OutlineInputBorder(
+ borderSide: BorderSide(color: Colors.blueAccent, width: 1.0),
+ ),
+ enabledBorder: OutlineInputBorder(
+ borderSide: BorderSide(color: Colors.blueGrey, width: 1.0),
+ ),
+ contentPadding: EdgeInsets.zero,
+ hintText: hintText,
+ hintStyle: TextStyle(fontWeight: FontWeight.normal),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget labelText(String text) {
+ return Expanded(
+ flex: 3,
+ child: Padding(
+ padding: padding,
+ child: Text(
+ text,
+ style: _textStyle.copyWith(fontWeight: FontWeight.bold),
+ ),
+ ),
+ );
+ }
+
+ void _clearLog() {
+ setState(() {
+ logTextController.text = "";
+ });
+ }
+
+ Widget customButton(String label, Function() callback, {Color? color}) {
+ return Expanded(
+ flex: 5,
+ child: Padding(
+ padding: padding.copyWith(top: 0.0, bottom: 0.0),
+ child: ElevatedButton(
+ onPressed: callback,
+ style: ElevatedButton.styleFrom(
+ primary: color ?? Colors.grey.shade300,
+ ),
+ child: Text(
+ label,
+ style: TextStyle(fontSize: 12, color: Colors.black87),
+ ),
+ ),
+ ),
+ );
+ }
+
+ void showResult(String name, [String? msg = "Button pressed."]) {
+ if (msg == null) {
+ msg = "";
+ }
+ appendLog("[" + name + "]" + ": " + msg);
+ print("[" + name + "]" + ": " + msg);
+ Push.showToast("[" + name + "]: " + msg);
+ }
+
+ void appendLog([String msg = "Button pressed."]) {
+ setState(() {
+ logTextController.text = msg + "\n" + logTextController.text;
+ });
+ }
+
+ void isSupportProfile() async {
+ showResult(
+ 'isSupportProfile', (await HmsProfile.isSupportProfile()).toString());
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return Scaffold(
+ appBar: AppBar(
+ title: Text(
+ 'Push Kit Demo - Multi-Sender',
+ style: TextStyle(fontSize: 16),
+ ),
+ ),
+ body: ListView(
+ shrinkWrap: true,
+ children: [
+ Row(
+ children: [
+ customButton(
+ 'isSupportProfile',
+ () => isSupportProfile(),
+ ),
+ ],
+ ),
+ Row(
+ children: [
+ customButton(
+ 'addProfile',
+ () => HmsProfile.addProfile(
+ HmsProfile.HUAWEI_PROFILE, "profile001")
+ .then(
+ (_) => showResult("addProfile", "Success"),
+ onError: (e) => showResult("addProfile Error:", e.toString()),
+ ),
+ ),
+ ],
+ ),
+ Row(
+ children: [
+ customButton(
+ 'addMultiSenderProfile',
+ () => HmsProfile.addMultiSenderProfile("",
+ HmsProfile.HUAWEI_PROFILE, "multiSenderProfile001")
+ .then(
+ (_) => showResult("addMultiSenderProfile", "Success"),
+ onError: (e) =>
+ showResult("addMultiSenderProfile Error:", e.toString()),
+ ),
+ ),
+ ],
+ ),
+ Row(
+ children: [
+ customButton(
+ 'deleteProfile',
+ () => HmsProfile.deleteProfile("profile001").then(
+ (_) => showResult("deleteProfile", "Success"),
+ onError: (e) =>
+ showResult("deleteProfile Error:", e.toString()),
+ ),
+ ),
+ ],
+ ),
+ Row(
+ children: [
+ customButton(
+ 'deleteMultiSenderProfile',
+ () => HmsProfile.deleteMultiSenderProfile(
+ "", "multiSenderProfile001")
+ .then(
+ (_) => showResult("deleteMultiSenderProfile", "Success"),
+ onError: (e) => showResult(
+ "deleteMultiSenderProfile Error:", e.toString()),
+ ),
+ ),
+ ],
+ ),
+ // Enter the sender app's project id to the subjectId parameter to get the Multi-Sender push token.
+ Row(
+ children: [
+ customButton(
+ 'getMultiSenderToken',
+ () => Push.getMultiSenderToken("").then(
+ (_) => showResult("getMultiSenderToken", "Success"),
+ onError: (e) =>
+ showResult("getMultiSenderToken Error:", e.toString()),
+ ),
+ ),
+ ],
+ ),
+ // Enter the sender app's project id to the subjectId parameter to delete the obtained Multi-Sender push token.
+ Row(
+ children: [
+ customButton(
+ 'deleteMultiSenderToken',
+ () => Push.deleteMultiSenderToken("").then(
+ (_) => showResult("deleteMultiSenderToken", "Success"),
+ onError: (e) =>
+ showResult("deleteMultiSenderToken Error:", e.toString()),
+ ),
+ ),
+ ],
+ ),
+ Row(
+ children: [customButton('clearLog', () => _clearLog())],
+ ),
+ Padding(
+ padding: padding.copyWith(top: 10.0, bottom: 10.0),
+ child: Divider(
+ height: 1.0,
+ thickness: 2.0,
+ ),
+ ),
+ Padding(
+ padding: padding,
+ child: TextField(
+ controller: logTextController,
+ keyboardType: TextInputType.multiline,
+ maxLines: 15,
+ readOnly: true,
+ decoration: new InputDecoration(
+ focusedBorder: OutlineInputBorder(
+ borderSide: BorderSide(color: Colors.blueAccent, width: 3.0),
+ ),
+ enabledBorder: OutlineInputBorder(
+ borderSide: BorderSide(color: Colors.blueGrey, width: 3.0),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/flutter-hms-push/example/pubspec.yaml b/flutter-hms-push/example/pubspec.yaml
index e70399f0..c1ffa21c 100644
--- a/flutter-hms-push/example/pubspec.yaml
+++ b/flutter-hms-push/example/pubspec.yaml
@@ -1,9 +1,9 @@
name: huawei_push_example
description: Demonstrates how to use the Huawei Push plugin.
-version: 5.0.2+304
+version: 5.1.1+301
environment:
- sdk: ">=2.1.0 <3.0.0"
+ sdk: '>=2.12.0 <3.0.0'
dependencies:
flutter:
diff --git a/flutter-hms-push/ios/huawei_push.podspec b/flutter-hms-push/ios/huawei_push.podspec
index af558dbe..ec031364 100644
--- a/flutter-hms-push/ios/huawei_push.podspec
+++ b/flutter-hms-push/ios/huawei_push.podspec
@@ -4,7 +4,7 @@
#
Pod::Spec.new do |s|
s.name = 'huawei_push'
- s.version = '5.0.2+304'
+ s.version = '5.1.1.301'
s.summary = 'HUAWEI Push Kit plugin for Flutter.'
s.description = <<-DESC
HUAWEI Push Kit plugin for Flutter that exposes all the functionality provided by the HUAWEI Push Kit SDK.
diff --git a/flutter-hms-push/lib/constants/channel.dart b/flutter-hms-push/lib/constants/channel.dart
deleted file mode 100644
index 0270edae..00000000
--- a/flutter-hms-push/lib/constants/channel.dart
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- Copyright 2020-2021. Huawei Technologies Co., Ltd. All rights reserved.
-
- Licensed under the Apache License, Version 2.0 (the "License")
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- https://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-*/
-
-/// API Constant Event and Method Channel Name Definitions ///
-const String TOKEN_CHANNEL = "com.huawei.flutter.push/token";
-const String REMOTE_MESSAGE_RECEIVE_CHANNEL =
- "com.huawei.flutter.push/remote_message_receive";
-const String REMOTE_MESSAGE_SEND_STATUS_CHANNEL =
- "com.huawei.flutter.push/remote_message_send_status";
-const String REMOTE_MESSAGE_NOTIFICATION_INTENT_CHANNEL =
- "com.huawei.flutter.push/remote_message_notification_intent";
-const String NOTIFICATION_OPEN_CHANNEL =
- "com.huawei.flutter.push/notification_open";
-const String LOCAL_NOTIFICATION_CLICK_CHANNEL =
- "com.huawei.flutter.push/local_notification_click";
-const String METHOD_CHANNEL = "com.huawei.flutter.push/method";
-const String BACKGROUND_MESSAGE_CHANNEL = "com.huawei.flutter.push/background";
diff --git a/flutter-hms-push/lib/huawei_push_library.dart b/flutter-hms-push/lib/huawei_push_library.dart
new file mode 100644
index 00000000..d80dcac8
--- /dev/null
+++ b/flutter-hms-push/lib/huawei_push_library.dart
@@ -0,0 +1,20 @@
+/*
+ Copyright 2020-2021. Huawei Technologies Co., Ltd. All rights reserved.
+
+ Licensed under the Apache License, Version 2.0 (the "License")
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+export 'src/cli/cli_export.dart';
+export 'src/constants/constants_export.dart' show ResultCodes;
+export 'src/local_notification/local_notification.dart';
+export 'src/model/remote_message.dart';
diff --git a/flutter-hms-push/lib/src/cli/cli_export.dart b/flutter-hms-push/lib/src/cli/cli_export.dart
new file mode 100644
index 00000000..4deec047
--- /dev/null
+++ b/flutter-hms-push/lib/src/cli/cli_export.dart
@@ -0,0 +1,20 @@
+/*
+ Copyright 2020-2021. Huawei Technologies Co., Ltd. All rights reserved.
+
+ Licensed under the Apache License, Version 2.0 (the "License")
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+export 'fcm_push_proxy.dart';
+export 'hms_profile.dart';
+export 'proxy_settings.dart';
+export 'push.dart';
diff --git a/flutter-hms-push/lib/src/cli/fcm_push_proxy.dart b/flutter-hms-push/lib/src/cli/fcm_push_proxy.dart
new file mode 100644
index 00000000..f13f6f4e
--- /dev/null
+++ b/flutter-hms-push/lib/src/cli/fcm_push_proxy.dart
@@ -0,0 +1,25 @@
+/*
+ Copyright 2020-2021. Huawei Technologies Co., Ltd. All rights reserved.
+
+ Licensed under the Apache License, Version 2.0 (the "License")
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+import 'package:huawei_push/src/constants/channel.dart';
+
+/// Provides the package for you to aggregate the push capability of FCM.
+class FcmPushProxy {
+ /// Initializes the push capability of FCM.
+ static Future init() async {
+ return await methodChannel.invokeMethod("initFcmPushProxy");
+ }
+}
diff --git a/flutter-hms-push/lib/src/cli/hms_profile.dart b/flutter-hms-push/lib/src/cli/hms_profile.dart
new file mode 100644
index 00000000..cecd3476
--- /dev/null
+++ b/flutter-hms-push/lib/src/cli/hms_profile.dart
@@ -0,0 +1,69 @@
+/*
+ Copyright 2020-2021. Huawei Technologies Co., Ltd. All rights reserved.
+
+ Licensed under the Apache License, Version 2.0 (the "License")
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+import 'package:huawei_push/src/constants/channel.dart';
+
+/// A class for checking whether to display messages for the user based on the account.
+///
+/// Supported devices: phones and tablets
+/// Supported operating systems: EMUI 9.1.0 or later and Android 9.0 or later
+class HmsProfile {
+ /// Account Type Constant.
+ ///
+ /// HUAWEI ID that you transfer by [addProfile] or [addMultiSenderProfile] in HmsProfile to verify the account.
+ static const int HUAWEI_PROFILE = 1;
+
+ /// Account Type Constant.
+ ///
+ /// Account different than the HUAWEI ID, which you transfer by [addProfile] or [addMultiSenderProfile] in HmsProfile to verify the account.
+ static const int CUSTOM_PROFILE = 2;
+
+ /// Account Type Constant.
+ ///
+ /// Undefined account type.
+ static const UNDEFINED_PROFILE = -1;
+
+ /// Checks whether the device supports account verification.
+ static Future isSupportProfile() async {
+ return await methodChannel.invokeMethod('isSupportProfile');
+ }
+
+ /// Adds the relationship between the user and app on the device.
+ static Future addProfile(int type, String profileId) async {
+ return await methodChannel
+ .invokeMethod('addProfile', {'type': type, 'profileId': profileId});
+ }
+
+ /// Adds the relationships between the user and apps on the device in the multi-sender scenario.
+ static Future addMultiSenderProfile(
+ String subjectId, int type, String profileId) async {
+ return await methodChannel.invokeMethod('addMultiSenderProfile',
+ {'subjectId': subjectId, 'type': type, 'profileId': profileId});
+ }
+
+ /// Deletes the relationship between the user and app on the device.
+ static Future deleteProfile(String profileId) async {
+ return await methodChannel
+ .invokeMethod('deleteProfile', {'profileId': profileId});
+ }
+
+ /// Deletes the relationships between the user and apps on the device in the multi-sender scenario.
+ static Future deleteMultiSenderProfile(
+ String subjectId, String profileId) async {
+ return await methodChannel.invokeMethod(
+ 'deleteProfile', {'subjectId': subjectId, 'profileId': profileId});
+ }
+}
diff --git a/flutter-hms-push/lib/src/cli/proxy_settings.dart b/flutter-hms-push/lib/src/cli/proxy_settings.dart
new file mode 100644
index 00000000..ed5d9a7a
--- /dev/null
+++ b/flutter-hms-push/lib/src/cli/proxy_settings.dart
@@ -0,0 +1,25 @@
+/*
+ Copyright 2020-2021. Huawei Technologies Co., Ltd. All rights reserved.
+
+ Licensed under the Apache License, Version 2.0 (the "License")
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+import 'package:huawei_push/src/constants/channel.dart';
+
+/// A class provided by the aggregation capability package for setting basic attributes.
+class ProxySettings {
+ /// Sets a country/region code. This method is available only for Huawei-developed apps.
+ static Future setCountryCode(String countryCode) async {
+ methodChannel.invokeMethod("setCountryCode", {"countryCode": countryCode});
+ }
+}
diff --git a/flutter-hms-push/lib/push.dart b/flutter-hms-push/lib/src/cli/push.dart
similarity index 82%
rename from flutter-hms-push/lib/push.dart
rename to flutter-hms-push/lib/src/cli/push.dart
index 574b4d60..b6265ba6 100644
--- a/flutter-hms-push/lib/push.dart
+++ b/flutter-hms-push/lib/src/cli/push.dart
@@ -20,43 +20,29 @@ import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
-import 'package:huawei_push/model/remote_message.dart';
+import 'package:huawei_push/src/constants/constants_export.dart';
+import 'package:huawei_push/src/model/remote_message.dart';
-import './constants/Channel.dart' as Channel;
-import './constants/Method.dart' as Method;
-import 'constants/Code.dart';
+import 'package:huawei_push/src/constants/channel.dart';
+import 'package:huawei_push/src/constants/method.dart' as Method;
class Push {
- /// Constant Method and Event Channel definitions for communicating with native platform
- static const MethodChannel methodChannel =
- const MethodChannel(Channel.METHOD_CHANNEL);
- static const EventChannel tokenEventChannel =
- EventChannel(Channel.TOKEN_CHANNEL);
- static const EventChannel remoteMessageReceiveEventChannel =
- EventChannel(Channel.REMOTE_MESSAGE_RECEIVE_CHANNEL);
- static const EventChannel remoteMessageSendStatusEventChannel =
- EventChannel(Channel.REMOTE_MESSAGE_SEND_STATUS_CHANNEL);
- static const EventChannel remoteMessageNotificationIntentEventChannel =
- EventChannel(Channel.REMOTE_MESSAGE_NOTIFICATION_INTENT_CHANNEL);
- static const EventChannel notificationOpenEventChannel =
- EventChannel(Channel.NOTIFICATION_OPEN_CHANNEL);
- static const EventChannel localNotificationClickEventChannel =
- EventChannel(Channel.LOCAL_NOTIFICATION_CLICK_CHANNEL);
-
/// Enables the function of receiving notification messages.
///
/// Returns the corresponding Push SDK Result Code's Description
static Future turnOnPush() async {
- final String result = await methodChannel.invokeMethod(Method.turnOnPush);
- return Code[result];
+ final String result =
+ await methodChannel.invokeMethod(Method.turnOnPush) ?? '-1';
+ return ResultCodes[result];
}
/// Disables the function of receiving notification messages.
///
/// Returns the corresponding Push SDK Result Code's Description
static Future turnOffPush() async {
- final String result = await methodChannel.invokeMethod(Method.turnOffPush);
- return Code[result];
+ final String result =
+ await methodChannel.invokeMethod(Method.turnOffPush) ?? '-1';
+ return ResultCodes[result];
}
/// Before applying for a token, an app calls this method to obtain its unique AAID.
@@ -65,14 +51,14 @@ class Push {
/// If the AAID of the app changes, a new token will be generated next time when
/// the app applies for a token. If an app needs to report statistics events,
/// it must carry the AAID as its unique ID.
- static Future getId() async {
- final String result = await methodChannel.invokeMethod(Method.getId);
+ static Future getId() async {
+ final String? result = await methodChannel.invokeMethod(Method.getId);
return result;
}
/// Obtains an AAID of Push SDK
- static Future getAAID() async {
- final String result = await methodChannel.invokeMethod(Method.getAAID);
+ static Future getAAID() async {
+ final String? result = await methodChannel.invokeMethod(Method.getAAID);
return result;
}
@@ -83,8 +69,8 @@ class Push {
}
/// Obtains an open device ID (ODID) in asynchronous mode.
- static Future getOdid() async {
- final String result = await methodChannel.invokeMethod(Method.getOdid);
+ static Future getOdid() async {
+ final String? result = await methodChannel.invokeMethod(Method.getOdid);
return result;
}
@@ -113,18 +99,23 @@ class Push {
/// Deletes a local AAID and its generation timestamp.
static Future deleteAAID() async {
final String result = await methodChannel.invokeMethod(Method.deleteAAID);
- return Code[result];
+ return ResultCodes[result];
}
/// Deletes the push token.
- ///
- /// Result of this method will be returned to the **onError** callback of the
- /// Token Stream.
- static Future deleteToken(String scope) async {
+ static Future deleteToken(String scope) async {
Map args = {};
args.putIfAbsent("scope", () => scope);
+ String result = await methodChannel.invokeMethod(Method.deleteToken, args);
+ return ResultCodes[result];
+ }
- methodChannel.invokeMethod(Method.deleteToken, args);
+ /// Deletes a token that a target app developer applies for a sender to integrate
+ /// Push Kit in the multi-sender scenario.
+ static Future deleteMultiSenderToken(String subjectId) async {
+ String result = await methodChannel
+ .invokeMethod(Method.deleteToken, {'subjectId': subjectId});
+ return ResultCodes[result];
}
/// Obtains the stream of [tokenEventChannel].
@@ -134,6 +125,15 @@ class Push {
static Stream get getTokenStream =>
tokenEventChannel.receiveBroadcastStream().cast();
+ /// Obtains the stream of [multiSenderTokenEventChannel].
+ ///
+ /// The stream emits the requested push token and errors thrown with the Push
+ /// SDK [Code] values in the multi-sender scenario.
+ static Stream