Files
assistant-android/app/src/main/java/com/gh/base/GHUmengNotificationService.java

86 lines
3.1 KiB
Java

package com.gh.base;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import com.gh.common.util.EntranceUtils;
import com.gh.gamecenter.R;
import com.umeng.message.UmengMessageService;
import org.android.agoo.common.AgooConstants;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class GHUmengNotificationService extends UmengMessageService {
public static final String ACTION_UMENG = "com.gh.gamecenter.UMENG";
public final String[] notificationTags = {"GH_UMENG_TAG_1", "GH_UMENG_TAG_2", "GH_UMENG_TAG_3"};
public static final int NOTIFICATION_ID = 2015;
@Override
public void onMessage(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager)
context.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
String message = intent.getStringExtra(AgooConstants.MESSAGE_BODY);
if (true) { // 显示到通知栏
Intent targetIntent = new Intent(ACTION_UMENG);
targetIntent.putExtra(EntranceUtils.KEY_DATA, message); // todo 传输数据
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 111, // todo requestCode
targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
final Notification notification = new NotificationCompat.Builder(context, "")
.setSmallIcon(R.drawable.logo)
.setTicker("setTicker")
.setContentTitle("setContentTitle")
.setContentText("setContentText")
.setContentIntent(pendingIntent)
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
if (notificationManager != null) {
notificationManager.notify(getNotificationTag(context), NOTIFICATION_ID, notification);
}
} else { // 其他处理
}
}
/**
* 规则:最多三条消息,以旧换新
*
* @return NotificationTag
*/
private String getNotificationTag(Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor edit = sp.edit();
Map<Long, String> timeTagMap = new HashMap<>();
for (String tag : notificationTags) {
long time = sp.getLong(tag, 0);
if (time == 0) {
edit.putLong(tag, System.currentTimeMillis()).apply();
return tag;
} else {
timeTagMap.put(time, tag);
}
}
Long minTime = Collections.min(timeTagMap.keySet());
String tag = timeTagMap.get(minTime);
edit.putLong(tag, System.currentTimeMillis()).apply();
return TextUtils.isEmpty(tag) ? notificationTags[0] : tag;
}
}