Android Firebase推送通知自动弹出

时间:2018-04-11 07:41:05

标签: android firebase firebase-cloud-messaging

我是Android应用程序开发的新手。我使用google firebase实现了我的应用程序的推送通知。通知并且非常准确,但问题是它没有自动弹出。是否有任何方法可以弹出通知?。经过这么多次搜索,我意识到使用通知渠道来实现这一点,但我没有得到任何合适的解决方案?请有人帮助我吗?答案将不胜感激。我在此提供通知。我正在使用的课程。

Notification.utils

public class NotificationUtils {

private static String TAG = NotificationUtils.class.getSimpleName();

private Context mContext;

public NotificationUtils(Context mContext) {
    this.mContext = mContext;

}

public void showNotificationMessage(String title,String body, String message, String timeStamp, Intent intent) {
    showNotificationMessage(title,body, message, timeStamp, intent, null);
}

public void showNotificationMessage(final String title,String body, final String message, final String timeStamp, Intent intent, String imageUrl) {
    // Check for empty push message
    if (TextUtils.isEmpty(message))
        return;


    // notification icon
    final int icon = R.mipmap.ic_launcher;
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
   // Intent PendingIntent = new Intent(mContext, ChatActivity.class);
    final PendingIntent resultPendingIntent =
            PendingIntent.getActivity(
                    mContext,
                    0,
                    intent,
                    PendingIntent.FLAG_CANCEL_CURRENT
            );

    final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            mContext);

    final Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
            + "://" + mContext.getPackageName() + "/raw/notification");

    if (!TextUtils.isEmpty(imageUrl)) {

        if (imageUrl != null && imageUrl.length() > 4 && Patterns.WEB_URL.matcher(imageUrl).matches()) {

            Bitmap bitmap = getBitmapFromURL(imageUrl);

            if (bitmap != null) {
                showBigNotification(bitmap, mBuilder, icon, title,body, message, timeStamp, resultPendingIntent, alarmSound);
            } else {
                showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
            }
        }
    } else {
        showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
        playNotificationSound();
    }
}


private void showSmallNotification(NotificationCompat.Builder mBuilder, int icon, String title, String body, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
   // inboxStyle.addLine(message);
    Notification notification;
    notification = mBuilder.setSmallIcon(icon).setTicker(title)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentText(body)
            .setContentIntent(resultPendingIntent)
            .setSound(alarmSound)
            .setStyle(inboxStyle)
            .setWhen(getTimeMilliSec(timeStamp))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setDefaults(NotificationCompat.DEFAULT_ALL)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
            .build();

    NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(Config.NOTIFICATION_ID, notification);
}

private void showBigNotification(Bitmap bitmap, NotificationCompat.Builder mBuilder, int icon, String title,String body, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {
    NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
    bigPictureStyle.setBigContentTitle(title);
    bigPictureStyle.setSummaryText(Html.fromHtml(message).toString());
    bigPictureStyle.bigPicture(bitmap);
    Notification notification;
    notification = new NotificationCompat.Builder(mContext, Constants.ProfileFragment.CHANNEL_ID).setSmallIcon(icon).setTicker(title)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentIntent(resultPendingIntent)
            .setSound(alarmSound)
            .setDefaults(NotificationCompat.DEFAULT_ALL)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
            .setContentText(body)
            .build();

    NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(Config.NOTIFICATION_ID_BIG_IMAGE, notification);
}

/**
 * Downloading push notification image before displaying it in
 * the notification tray
 */
public Bitmap getBitmapFromURL(String strURL) {
    try {
        URL url = new URL(strURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

// Playing notification sound
public void playNotificationSound() {
    try {
        Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
                + "://" + mContext.getPackageName() + "/raw/notification");
        Ringtone r = RingtoneManager.getRingtone(mContext, alarmSound);
        r.play();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * Method checks if the app is in background or not
 */
public static boolean isAppIsInBackground(Context context) {
    boolean isInBackground = true;
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                for (String activeProcess : processInfo.pkgList) {
                    if (activeProcess.equals(context.getPackageName())) {
                        isInBackground = false;
                    }
                }
            }
        }
    } else {
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;
        if (componentInfo.getPackageName().equals(context.getPackageName())) {
            isInBackground = false;
        }
    }

    return isInBackground;
}

// Clears notification tray messages
public static void clearNotifications(Context context) {
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancelAll();
}

public static long getTimeMilliSec(String timeStamp) {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
        Date date = format.parse(timeStamp);
        return date.getTime();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return 0;
}
}

 2. MyFirebaseMessagingService.class
 public class MyFirebaseMessagingService extends FirebaseMessagingService {
public  int total=0;
private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();

private NotificationUtils notificationUtils;
int badge;

public static final String NOTIFICATION_REPLY = "NotificationReply";
public static final String CHANNNEL_ID = "Bawabba";
public static final String CHANNEL_NAME = "Bawabba";


public static final String KEY_INTENT_MORE = "keyintentmore";
public static final String KEY_INTENT_HELP = "keyintenthelp";

public static final int REQUEST_CODE_MORE = 100;
public static final int REQUEST_CODE_HELP = 101;
public static final int NOTIFICATION_ID = 200;

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.e(TAG, "From: " + remoteMessage.getFrom());
    System.out.println("Arjun from : " + remoteMessage.getFrom());
    System.out.println("Arjun toSt : " + remoteMessage.toString());

    System.out.println("Arjun :: handleNotification");
    total = ObjectFactory.getInstance().getAppPreference(getApplicationContext()).getUnreadMessage();
    System.out.println("Arjun :: totalUNREADmessage " + total);
    total++;
    ObjectFactory.getInstance().getAppPreference(getApplicationContext()).saveUnreadMessage(total);
    ObjectFactory.getInstance().getAppPreference(getApplicationContext()).saveNewMessageArrived(true);


    NotificationCompat.Builder builder = new  NotificationCompat.Builder(this,CHANNNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(remoteMessage.getData().get("title"))
            .setContentText(remoteMessage.getData().get("body"))
            .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setAutoCancel(true);


    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    manager.notify(123, builder.build());

    if (remoteMessage == null)
        return;

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
        handleNotification(remoteMessage.getNotification().getBody());
        handleNotification(remoteMessage.getNotification().getTitle());
    }
    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        remoteMessage.getNotification().getTitle();
        remoteMessage.getNotification().getBody();

        Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
        badge = Integer.parseInt(remoteMessage.getData().get("badge"));
        Log.e("notificationNUmber",":"+badge);
        // setBadge(getApplicationContext(), badge);

        try {
            JSONObject json = new JSONObject(remoteMessage.getData().toString());
            handleDataMessage(json);
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        String id = "id_product";
        // The user-visible name of the channel.
        CharSequence name = "Bawabba";
        // The user-visible description of the channel.
        String description = remoteMessage.getData().get("body");
        int importance = NotificationManager.IMPORTANCE_HIGH;
        @SuppressLint("WrongConstant") NotificationChannel mChannel = new NotificationChannel(id, name, importance);
        // Configure the notification channel.
        mChannel.setDescription(description);
        mChannel.enableLights(true);
        // Sets the notification light color for notifications posted to this
        // channel, if the device supports this feature.
        mChannel.setLightColor(Color.RED);
        notificationManager.createNotificationChannel(mChannel);
    }


}
private void handleNotification(String message) {
    try {
        if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the push message
            Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

            // play notification sound
            NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
            notificationUtils.playNotificationSound();
            EventBus.getDefault().post(new MessageEvent("Comes from showUnreadMessages!"));
        } else {
            // If the app is in background, firebase itself handles the notification
        }
    } catch (Exception e) {
        System.out.println("Arjun :: error " + e.getMessage());
    }
}


private void handleDataMessage(JSONObject json) {

    Log.e(TAG, "push json: " + json.toString());

    try {
        JSONObject data = json.getJSONObject("data");
        String title = data.getString("title");
        String body = data.getString("body");
        String message = data.getString("message");
        boolean isBackground = data.getBoolean("is_background");
        String imageUrl = data.getString("image");
        String timestamp = data.getString("timestamp");
        JSONObject payload = data.getJSONObject("payload");

        Log.e(TAG, "title: " + title);
        Log.e(TAG, "body: " + body);
        Log.e(TAG, "message: " + message);
        Log.e(TAG, "isBackground: " + isBackground);
        Log.e(TAG, "payload: " + payload.toString());
        Log.e(TAG, "imageUrl: " + imageUrl);
        Log.e(TAG, "timestamp: " + timestamp);


        if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the push message
            Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);
            pushNotification.putExtra("title", title);
            pushNotification.putExtra("body", body);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

            // play notification sound
            NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
            notificationUtils.playNotificationSound();
        } else {
            // app is in background, show the notification in notification tray
            Intent resultIntent = new Intent(getApplicationContext(), ChatActivity.class);
            resultIntent.putExtra("message", message);

            // check for image attachment
            if (TextUtils.isEmpty(imageUrl)) {
                showNotificationMessage(getApplicationContext(), title,body, message, timestamp, resultIntent);
            } else {
                // image is present, show notification with image
                showNotificationMessageWithBigImage(getApplicationContext(), title,body, message,timestamp,resultIntent, imageUrl);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "Json Exception: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }

}

private void showNotificationMessage(Context context, String title, String body, String message,String timeStamp, Intent intent) {
    notificationUtils = new NotificationUtils(context);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationUtils.showNotificationMessage(title,body ,message, timeStamp, intent);
}

private void showNotificationMessageWithBigImage(Context context, String title,String body, String message, String timeStamp, Intent intent, String imageUrl) {
    notificationUtils = new NotificationUtils(context);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationUtils.showNotificationMessage(title,body, message, timeStamp, intent, imageUrl);
}
}

2 个答案:

答案 0 :(得分:1)

根据通知,您需要设置振动或铃声以进行单挑操作。但是,这是一个快速入侵,不需要VIBRATE权限来生成平视通知:

notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
if (Build.VERSION.SDK_INT >= 21) notificationBuilder.setVibrate(new long[0]);
  1. 因为棒棒糖不起作用动手通知Android
  2. 不要滥用抬头通知。请参阅此处了解何时使用抬头通知:
  3. MAX:用于关键和紧急通知,提醒用户注意时间紧迫或需要解决的条件才能继续执行特定任务。
  4. HIGH:主要用于重要的通信,例如包含对用户特别感兴趣的内容的消息或聊天事件。高优先级通知会触发抬头通知显示。
  5.   

    MAX用于关键和紧急通知,提醒用户注意时间紧迫或需要解决的条件才能继续执行特定任务。

         

    HIGH主要用于重要通信,例如消息或聊天事件,其内容对用户特别有用。高优先级通知会触发抬头通知显示。

         

    DEFAULT用于所有不属于此处描述的任何其他优先级的通知,以及应用程序是否优先处理其自己的通知

         

    LOW用于您希望通知用户但不太紧急的通知。低优先级通知往往显示在列表的底部,这使得它们成为公共或无向社交更新等内容的良好选择:用户已要求收到有关它们的通知,但这些通知不应优先于紧急或直接沟通。

         

    MIN用于上下文或背景信息,例如天气信息或上下文位置信息。最低优先级通知不会出现在状态栏中。用户在扩展通知阴影时会发现它们。

答案 1 :(得分:0)

如果应用程序在后台,那么您需要管理背景和前景的状态

1您通过以下条件查看应用状态

  public static boolean isAppIsInBackground(Context context) {
    boolean isInBackground = true;
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                for (String activeProcess : processInfo.pkgList) {
                    if (activeProcess.equals(context.getPackageName())) {
                        isInBackground = false;
                    }
                }
            }
        }
    } else {
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;
        if (componentInfo.getPackageName().equals(context.getPackageName())) {
            isInBackground = false;
        }
    }

    return isInBackground;
}

之后,您可以检查推送通知类

中的条件
 if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in the foreground, broadcast the push message

        } else {
            // app is in background, show the notification in notification tray                             
          showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);                                                       
            }

然后申请下面的代码......

 public void showNotificationMessage(final String title, final String message, final String timeStamp, Intent intent, String imageUrl) {
    // Check for empty push message
    if (TextUtils.isEmpty(message))
        return;


    // notification icon
    final int icon = R.mipmap.noti_logo;
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setAction(Long.toString(System.currentTimeMillis()));
    final PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext);
    final Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE+ "://" + mContext.getPackageName() + "/raw/notification");*/

    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

     showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);

}

 private void showSmallNotification(NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

    inboxStyle.addLine(message);

    Notification notification;
    notification = mBuilder.setSmallIcon(icon).setTicker(title)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentIntent(resultPendingIntent)
            .setStyle(inboxStyle)
            .setSound(alarmSound)
            .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
            .setSmallIcon(R.mipmap.noti_logo)
            .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
            .setContentText(message)
            .build();

    NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(Constants.NOTIFICATION_ID, notification);
    Constants.NOTIFICATION_ID++;
}

如果它不能使用,那么也会使用CHECK APP背景应用程序条件

private void test() {
Intent intent;
intent = new Intent(this, SplashScreenActivity.class);
Bundle bundle = new Bundle();
bundle.putBoolean("isDisplayAlert", true);
bundle.putString("NOTIFICATION_DATA", "data");
intent.putExtras(bundle);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),
        new Random().nextInt(), intent,
        PendingIntent.FLAG_UPDATE_CURRENT);

Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_location)
        .setContentTitle("Title")
        .setContentText("Body")
        .setAutoCancel(true)
        .setSound(defaultSoundUri)
        .setOnlyAlertOnce(true)
        .setFullScreenIntent(pendingIntent, true);

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

notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
notificationBuilder.setVibrate(new long[0]);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());                                                   
      }