In order to handle data message and show as custom notification with big image in HMS push kit (huawei) please follow structure below
- Open the build.gradle file in the root directory of your Android Studio project and do as below.
buildscript {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
classpath 'com.huawei.agconnect:agcp:1.3.1.300'
}
}
allprojects {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
}
Open the build.gradle file in the app directory of your project and Add build dependencies in the dependencies section
dependencies {
implementation 'com.huawei.hms:push:5.0.0.300'
}
Add the below service and meta-data in Android manifest file inside the application
<meta-data android:name="push_kit_auto_init_enabled" android:value="true"/>
<service android:exported="false" android:name=".PushMessage.PushService">
<intent-filter>
<action android:name="com.huawei.push.action.MESSAGING_EVENT"/>
</intent-filter>
</service>
After getting the notification please add the below code.
Sample Data Notification message
{
"message": "body message",
"Title": "welcome to our app",
"ImageURI": "http://api.androidhive.info/images/sample.jpg"
}
You can find the code snippet- onMessageReceived()
4.1. Get bitmap from the URL - Function
You can find the code snippet- generatePictureStyleNotification()
4.2. Handling the Notification
You can find the code snippet - showNotification()
Here is full code in PushService class
public class PushService extends HmsMessageService {
private static final String TAG = "PushService ";
private final static String ACTION = "com.huawei.hms.android.kitdemo.PushMessage.action";
private NotificationManager mNotificationManager;
private static final String CHANNEL1 = "channel1";
public static HashSet<String> mMessages = new HashSet<String>();
private String title, message, imageUrl, msgNotification;
private Bitmap mBitmap = null;
/**
* When an app calls the getToken method to apply for a token from the server,
* if the server does not return the token during current method calling, the server can return the token through this method later.
* This method callback must be completed in 10 seconds. Otherwise, you need to start a new Job for callback processing.
*
* @param token token
*/
@Override
public void onNewToken(String token) {
Log.i(TAG, "received refresh token:" + token);
// send the token to your app server.
if (!TextUtils.isEmpty(token)) {
refreshedTokenToServer(token);
}
System.out.println("Res PushService.onNewToken token - " + token);
}
private void refreshedTokenToServer(String token) {
Log.i(TAG, "sending token to server. token:" + token);
}
/**
* This method is used to receive downstream data messages.
* This method callback must be completed in 10 seconds. Otherwise, you need to start a new Job for callback processing.
*
* @param message RemoteMessage
*/
@Override
public void onMessageReceived(RemoteMessage message) {
Log.i(TAG, "onMessageReceived is called");
if (message == null) {
Log.e(TAG, "Received message entity is null!");
return;
}
String msgNoteBase = message.getData();
System.out.println(TAG + msgNoteBase);
Log.i(TAG, message.getData());
System.out.println(TAG + msgNoteBase);
// {"message":"Check message","Title":"Header","ImageURI":"http://api.androidhive.info/images/sample.jpg"}
new generatePictureStyleNotification(this, msgNoteBase).execute();
Boolean judgeWhetherIn10s = false;
// If the messages are not processed in 10 seconds, the app needs to use WorkManager for processing.
if (judgeWhetherIn10s) {
startWorkManagerJob(message);
} else {
// Process message within 10s
processWithin10s(message);
}
}
private void startWorkManagerJob(RemoteMessage message) {
Log.d(TAG, "Start new job processing.");
}
private void processWithin10s(RemoteMessage message) {
Log.d(TAG, "Processing now.");
}
@Override
public void onMessageSent(String msgId) {
Log.i(TAG, "onMessageSent called, Message id:" + msgId);
Intent intent = new Intent();
intent.setAction(ACTION);
intent.putExtra("method", "onMessageSent");
intent.putExtra("msg", "onMessageSent called, Message id:" + msgId);
sendBroadcast(intent);
}
@Override
public void onSendError(String msgId, Exception exception) {
Log.i(TAG, "onSendError called, message id:" + msgId + ", ErrCode:"
+ ((SendException) exception).getErrorCode() + ", description:" + exception.getMessage());
Intent intent = new Intent();
intent.setAction(ACTION);
intent.putExtra("method", "onSendError");
intent.putExtra("msg", "onSendError called, message id:" + msgId + ", ErrCode:"
+ ((SendException) exception).getErrorCode() + ", description:" + exception.getMessage());
sendBroadcast(intent);
}
@Override
public void onTokenError(Exception e) {
super.onTokenError(e);
}
// Show the Notification based on the device availabality on foreground or background
@RequiresApi(api = Build.VERSION_CODES.N)
private void showNotification(String msg) {
ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> services = activityManager.getRunningTasks(Integer.MAX_VALUE);
boolean isActivityFound = false;
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
final String packageName = getApplicationContext().getPackageName();
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
isActivityFound = true;
break;
}
}
if (isActivityFound) {
broadcastDialogIntent(msg);
} else {
mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = 1;
String channelId = CHANNEL1;
int importance = NotificationManager.IMPORTANCE_HIGH;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelId, importance);
mNotificationManager.createNotificationChannel(mChannel);
Intent notificationIntent = new Intent(getApplicationContext(), NavigationMainActivity.class);
Bundle passValue = new Bundle();
passValue.putString("msg", msg);
notificationIntent.setAction("android.intent.action.MAIN");
notificationIntent.addCategory("android.intent.category.LAUNCHER");
notificationIntent.putExtras(passValue);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder;
if (mBitmap != null) {
mBuilder = new NotificationCompat.Builder(getApplicationContext(), channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getResources().getString(R.string.app_name))
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(mBitmap)
.bigLargeIcon(mBitmap))
.setContentText(msg);
} else {
mBuilder = new NotificationCompat.Builder(getApplicationContext(), channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(msg);
}
mBuilder.setContentIntent(intent);
mNotificationManager.notify(notificationId, mBuilder.build());
} else {
Intent notificationIntent = new Intent(getApplicationContext(), NavigationMainActivity.class);
Bundle passValue = new Bundle();
passValue.putString("msg", msg);
notificationIntent.setAction("android.intent.action.MAIN");
notificationIntent.addCategory("android.intent.category.LAUNCHER");
notificationIntent.putExtras(passValue);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (mBitmap != null) {
mBuilder.setSmallIcon(R.mipmap.ic_launcher).setContentTitle(getString(R.string.app_name)).setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg)).setContentText(msg).setAutoCancel(true).setSound(soundUri)
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(mBitmap)
.bigLargeIcon(mBitmap));
} else {
mBuilder.setSmallIcon(R.mipmap.ic_launcher).setContentTitle(getString(R.string.app_name)).setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg)).setContentText(msg).setAutoCancel(true).setSound(soundUri);
}
mMessages.add(msg);
NotificationCompat.InboxStyle inBoxStyle = new NotificationCompat.InboxStyle();
inBoxStyle.setBigContentTitle(getString(R.string.app_name));
int total = mMessages.size();
if (total == 0) {
setBadge(this, 0);
} else {
setBadge(this, total);
}
Iterator iterator = mMessages.iterator();
while (iterator.hasNext()) {
inBoxStyle.addLine((CharSequence) iterator.next());
}
for (int i = 0; i < total; i++) {
inBoxStyle.addLine(mMessages.toString());
//inBoxStyle.addLine(mMessages.get(total - 1 - i));
}
mBuilder.setContentIntent(intent);
mBuilder.setStyle(inBoxStyle);
Notification notification = mBuilder.build();
mBuilder.setNumber(total);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(notificationId, notification);
}
}
}
/**
* Broadcast dialog intent.
*
* @param msg the msg
*/
public void broadcastDialogIntent(String msg) {
Intent intent = new Intent();
Bundle passValue = new Bundle();
passValue.putString("msg", msg);
intent.putExtras(passValue);
intent.setAction("com.hms.pushdemo.SHOW_DIALOG");
sendBroadcast(intent);
}
/**
* Sets badge.
*
* @param context the context
* @param count the count
*/
public static void setBadge(Context context, int count) {
String launcherClassName = getLauncherClassName(context);
if (launcherClassName == null) {
return;
}
Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
intent.putExtra("badge_count", count);
intent.putExtra("badge_count_package_name", context.getPackageName());
intent.putExtra("badge_count_class_name", launcherClassName);
context.sendBroadcast(intent);
}
/**
* Gets launcher class name.
*
* @param context the context
* @return the launcher class name
*/
public static String getLauncherClassName(Context context) {
PackageManager pm = context.getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resolveInfos) {
String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
if (pkgName.equalsIgnoreCase(context.getPackageName())) {
String className = resolveInfo.activityInfo.name;
return className;
}
}
return null;
}
// Get the bitmap from the URL using Glide, where you got from the Data message
private class generatePictureStyleNotification extends AsyncTask<String, Void, Bitmap> {
// {"message":"Check message",
// "Title":"Header",
// "ImageURI":"http://api.androidhive.info/images/sample.jpg"
// }
Context mContext;
public generatePictureStyleNotification(Context context, String msgNoteBase) {
super();
this.mContext = context;
try {
msgNotification = msgNoteBase;
JSONObject mJSONObject = new JSONObject(msgNoteBase);
message = mJSONObject.getString("message");
title = mJSONObject.getString("Title");
imageUrl = mJSONObject.getString("ImageURI");
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
protected Bitmap doInBackground(String... params) {
Glide.with(mContext)
.asBitmap()
.load(imageUrl)
.into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
mBitmap = resource;
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
return null;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
showNotification(message);
}
}
}
}
enter image description here