Пользовательский тон уведомления не работает, когда приложение находится в фоновом режиме - PullRequest
0 голосов
/ 28 апреля 2019

Я пытаюсь использовать пользовательский тон уведомления.Тональный сигнал работает нормально, когда приложение работает, но тональный сигнал по умолчанию воспроизводится, когда приложение работает в фоновом режиме.Также вибрация не работает, когда уведомление получено, когда приложение не активно

Я пытался сделать следующее:

Мой класс службы сообщений.

public class MyFirebaseMessagingService extends FirebaseMessagingService{

private static final String TAG = "MyFirebaseMsgService";
Utilities utils = new Utilities();
Notification notification;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    if (remoteMessage.getData() != null) {
        sendNotification(remoteMessage.getData().get("message"));
        Log.e(TAG,remoteMessage.getData().get("message"));
    }else{
        utils.print(TAG,"FCM Notification failed");
    }
}
private void sendNotification(String messageBody) {
    long[] v = {500,1000};

    if (!isAppIsInBackground(getApplicationContext())) {

        utils.print(TAG,"foreground");
        Log.e(TAG,"Notifcation"+messageBody);
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("push", true);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                    PendingIntent.FLAG_ONE_SHOT);


            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText(messageBody)
                    .setAutoCancel(false)
                    .setVibrate(v)
                    .setContentIntent(pendingIntent);

            notificationBuilder.setSmallIcon(getNotificationIcon(notificationBuilder), 1);

        notification = notificationBuilder.build();
        notification.sound=Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.alert_tone);
        notification.defaults=Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE;

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

            notificationManager.notify(0, notification);
    }
    else{
        if(messageBody.equalsIgnoreCase("New Incoming Ride")){
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
          PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                   PendingIntent.FLAG_ONE_SHOT);

            Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText(messageBody)
                    .setAutoCancel(false)
                    .setVibrate(v)
                    .setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.alert_tone))
                   .setContentIntent(pendingIntent);

            notificationBuilder.setSmallIcon(getNotificationIcon(notificationBuilder), 1);
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notification = notificationBuilder.build();
            notification.defaults=Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE;
            notification.sound=Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.alert_tone);
            notificationManager.notify(0, notification);
        }
        else{
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("push", true);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                    PendingIntent.FLAG_ONE_SHOT);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText(messageBody)
                    .setAutoCancel(false)
                    .setVibrate(v)
                    .setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.alert_tone))
                   .setContentIntent(pendingIntent);

            notificationBuilder.setSmallIcon(getNotificationIcon(notificationBuilder), 1);
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notification = notificationBuilder.build();
            notification.sound=Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.alert_tone);
            notificationManager.notify(0, notification);
        }
    }
}

private int getNotificationIcon(NotificationCompat.Builder notificationBuilder) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
        notificationBuilder.setColor(ContextCompat.getColor(getApplicationContext(),R.color.colorPrimary));
        return  R.mipmap.ic_launcher;
    }else {
        return R.mipmap.ic_launcher;
    }
}
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;

1 Ответ

1 голос
/ 29 апреля 2019

Вы можете отправить уведомление в ваше приложение для пользователя, связанного с пожарной базой, отправив уведомление, когда ваше приложение закрыто, на основании некоторых параметров перейдите в пожарную базу.

Прежде чем делать это, сначала убедитесь, что ваш проект добавлен в базу Fire, в противном случае добавьте ваш проект в базу Fire с именем пакета, отпечатком и файлом google_services.json в папке приложения вашего проекта.

Пожарная база Cloud Messaging

он будет отправлять уведомление в ваше приложение, если оно закрыто, тогда оно позволяет пользователю открывать приложение с помощью нажатого уведомления, и если вы хотите показать уведомление пользователю, чтобы направить его в другие приложения с той же учетной записью, когда приложение будет использоваться как будет с этим кодом:

Создайте свой первый класс MyFirebaseMessagingService

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String NOTIFICATION_ID_EXTRA = "notificationId";
private static final String IMAGE_URL_EXTRA = "imageUrl";
private static final String ADMIN_CHANNEL_ID ="admin_channel";
private NotificationManager notificationManager;


@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    if (remoteMessage.getData().size()>0){

        Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
        notificationIntent.setData(Uri.parse(remoteMessage.getData().get("applink")));
        PendingIntent pi = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        final PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0 /* Request code */, notificationIntent,
                PendingIntent.FLAG_ONE_SHOT);

        int notificationId = new Random().nextInt(60000);
        Bitmap bitmap = getBitmapfromUrl(remoteMessage.getData().get("imageurl"));

        Intent likeIntent = new Intent(this,LikeService.class);
        likeIntent.putExtra(NOTIFICATION_ID_EXTRA,notificationId);
        likeIntent.putExtra(IMAGE_URL_EXTRA,remoteMessage.getData().get("message"));
        PendingIntent likePendingIntent = PendingIntent.getService(this,
                notificationId+1,likeIntent, PendingIntent.FLAG_ONE_SHOT);

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

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

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {

            setupChannels();

        }

        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
                        .setLargeIcon(bitmap)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle(remoteMessage.getData().get("title"))
                        .setStyle(new NotificationCompat.BigPictureStyle()
                                .setSummaryText(remoteMessage.getData().get("message"))
                                .bigPicture(bitmap))/*Notification with Image*/
                        .setContentText(remoteMessage.getData().get("message"))
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .addAction(R.drawable.icon,
                                getString(R.string.notification_add_to_cart_button),likePendingIntent)
                        .setContentIntent(pendingIntent);

        notificationManager.notify(notificationId, notificationBuilder.build());


    }

}


@RequiresApi(api = Build.VERSION_CODES.O)
private void setupChannels(){
    CharSequence adminChannelName = getString(R.string.notifications_admin_channel_name);
    String adminChannelDescription = getString(R.string.notifications_admin_channel_description);

    NotificationChannel adminChannel;
    adminChannel = new NotificationChannel(ADMIN_CHANNEL_ID, adminChannelName, NotificationManager.IMPORTANCE_LOW);
    adminChannel.setDescription(adminChannelDescription);
    adminChannel.enableLights(true);
    adminChannel.setLightColor(Color.RED);
    adminChannel.enableVibration(true);
    if (notificationManager != null) {
        notificationManager.createNotificationChannel(adminChannel);
    }
}



public Bitmap getBitmapfromUrl(String imageUrl) {
    try {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        return BitmapFactory.decodeStream(input);

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}


    }

Создайте другой класс FirebaseIDService , чтобы получить службу идентификатора экземпляра пожарной базы

public class FirebaseIDService extends FirebaseInstanceIdService {


public static final String FIREBASE_TOKEN = "firebase token";

@Override
public void onTokenRefresh() {
    super.onTokenRefresh();

    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    SharedPreferences preferences =
            PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    preferences.edit().putString(FIREBASE_TOKEN, refreshedToken).apply();

}

Сделать имя класса LikeService

public class LikeService extends Service {

private static final String NOTIFICATION_ID_EXTRA = "notificationId";
private static final String IMAGE_URL_EXTRA = "imageUrl";
@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}
    }

Для поддержки уведомлений в Oreo с помощью firebase не забудьте создать каналы, и эти каналы инициализируются в вашей первой активности запуска .

в создание первого проекта запуска вашего проекта включите эти каналы;

   String channelId = "1";
    String channel2 = "2";

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

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(channelId,
                "Channel 1", NotificationManager.IMPORTANCE_HIGH);

        notificationChannel.setDescription("This is BNT");
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.enableVibration(true);
        notificationChannel.setShowBadge(true);
        notificationManager.createNotificationChannel(notificationChannel);

        NotificationChannel notificationChannel2 = new NotificationChannel(channel2,
                "Channel 2",NotificationManager.IMPORTANCE_MIN);

        notificationChannel.setDescription("This is bTV");
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.enableVibration(true);
        notificationChannel.setShowBadge(true);
        notificationManager.createNotificationChannel(notificationChannel2);

    }

Теперь вы должны поместить класс обслуживания Firebase в Mainfest под приложением tag:

      <service android:name=".activities.services.MyFirebaseMessagingService"
        android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>

            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            <action android:name="com.google.android.c2dm.intent.RECEIVE"/>

        </intent-filter>

    </service>

    <service android:name=".activities.services.FirebaseIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>

Теперь запустите ваше приложение на своем устройстве, прежде чем push-уведомления с помощью fire base убедитесь, что ваш код правильно интегрирован, затем запустите app: и перейдите к отправке сообщений об облачной базе:

положить данные, как на фото, в соответствии с вашим приложением: когда оно закрыто:

enter image description here

если ваше приложение используется, тогда будут отображаться ваши заранее записанные данные, данные о вашем рекламном приложении с той же учетной записью, не используйте здесь другое приложение учетной записи,

убедитесь, что ваш ключ должен быть таким же, как в предыдущем классе, как onMessagede Получено в MyFirebaseMessagingService class

Также, если вам нужны какие-либо учебные пособия , используйте это

как

title, message, applink, imageurl

enter image description here

...