Пользовательское уведомление/вибрация — Firebase — Wear OS — Android 8.0.0. API 26

Что у меня есть: отдельное приложение на Wear OS (Android 8+), API 26 и в Firebase.

Чего бы я добился (первое): я бы показывал пользовательское уведомление с пользовательским шаблоном вибрации.

Чего бы я достиг (второе): когда мое приложение находится в фоновом режиме, я бы автоматически открывал свое приложение или нажимал на уведомление (но с пользовательской вибрацией).

Я запускаю службу переднего плана с текущим уведомлением. Это постоянное уведомление работает очень хорошо и не имеет функций из Wear OS (поэтому код может работать на автономном Android). У меня есть некоторые проблемы с уведомлениями.

Не могу изменить виброуведомления и раскладку.

здесь мой FirebaseMessagingService

public class MyfirebaseMessagingService extends FirebaseMessagingService {

    public static String TAG = "MyFirebaseMsgService";

    private LocalBroadcastManager broadcaster;

    Uri NOTIFICATION_SOUND_URI = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + BuildConfig.APPLICATION_ID + "/" );
    long[] VIBRATE_PATTERN    = {0, 500};

    @Override
    public void onCreate() {
        super.onCreate();
        createNotificationChannel();

        broadcaster = LocalBroadcastManager.getInstance(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    private void createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = getString(R.string.default_notification_channel_id);

            CharSequence name = getString(R.string.default_notification_channel_id);
            String description = getString(R.string.channel_description);
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(channelId, name, importance);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }


    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {


        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Intent home = new Intent(getApplicationContext(), Splash.class);
        home.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(home);

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {

            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());

            Intent intent = new Intent("Data");
            intent.putExtra("messageFromCloud", remoteMessage.getNotification().getBody());
            broadcaster.sendBroadcast(intent);
            if (intent.getExtras() != null)
            {
                MyNotificationManager notification =  MyNotificationManager.getInstance(this);
                notification.displayNotification("title",remoteMessage.getNotification().getBody());

                RemoteMessage.Builder builder = new RemoteMessage.Builder("MyFirebaseMessagingService");

                for (String key : intent.getExtras().keySet())
                {
                    builder.addData(key, Objects.requireNonNull(intent.getExtras().get(key)).toString());
                }
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    NotificationManager mNotificationManager =
                            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                    int importance = NotificationManager.IMPORTANCE_HIGH;
                    NotificationChannel mChannel = new NotificationChannel(Constants.CHANNEL_ID, Constants.CHANNEL_NAME, importance);
                    mChannel.setDescription(Constants.CHANNEL_DESCRIPTION);
                    mChannel.enableLights(true);
                    mChannel.setLightColor(Color.RED);
                    mChannel.enableVibration(true);
      //                    mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
                    mNotificationManager.createNotificationChannel(mChannel);

                     Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
                    long[] newvibrationPattern = {0, 1000, 500, 50,
                                0, 1000, 500, 50,
                                0, 1000, 500, 50,
                                0, 1000, 500, 50,
                                0, 1000, 500, 50,
                                0, 1000, 500, 50};
                     //-1 - don't repeat
                     final int indexInPatternToRepeat = -1;
                     vibrator.vibrate(newvibrationPattern, indexInPatternToRepeat);
                }
                onMessageReceived(builder.build());
            }
        }
    }
}

person DoctorWho    schedule 20.05.2019    source источник
comment
Вы должны отредактировать свой вопрос, чтобы в первую очередь сосредоточиться на одной проблеме.   -  person Manoj Perumarath    schedule 20.05.2019
comment
хорошо, моя первая проблема это вибрация. Я хотел бы реализовать пользовательскую вибрацию, когда прибудет FCM   -  person DoctorWho    schedule 20.05.2019
comment
newvibrationPattern это ваш собственный шаблон вибрации? Что не так с этим шаблоном   -  person Manoj Perumarath    schedule 20.05.2019
comment
Да, это. Если приложение на переднем плане работает хорошо, но в фоновом режиме, когда я получаю уведомление, не работает   -  person DoctorWho    schedule 20.05.2019
comment
Это не сработает, потому что onMessageReceived не будет вызываться   -  person Manoj Perumarath    schedule 20.05.2019
comment
где мне нужно это назвать?   -  person DoctorWho    schedule 20.05.2019
comment
У вас это сработало? Есть ли образец приложения, которым вы могли бы поделиться?   -  person lcj    schedule 27.03.2020


Ответы (1)


Наконец-то мне удалось обойти нестандартную схему вибрации. Ваш код довольно грязный DoctorWho. Как и вы, я также пробовал различные комбинации с NotificationCompat.Builder и NotificationChannel, но ничего не получалось. Чтобы заставить работать пользовательские вибрации, у вас есть два варианта: не показывать уведомление и просто воспроизводить свою пользовательскую вибрацию, или вы можете показывать уведомление, но вам нужно будет реализовать его так, чтобы вибрации были отключены для того NotificationChannel, которое вы создаете уведомление. и включите 1-секундную задержку после воспроизведения пользовательской вибрации. Пример:

val notificationBuilder = NotificationCompat.Builder(this, "channelId")
...
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val chan = NotificationChannel(
                "channelId",
                "Default",
                NotificationManager.IMPORTANCE_HIGH
            )
            chan.enableVibration(false)
            notificationManager.createNotificationChannel(chan)
        }

и теперь вы можете запустить свой шаблон вибрации после задержки в 1 секунду:

Timer().schedule(1000) {
        vibrate(pattern)
}
private fun vibrate(pattern: LongArray) {
        val v = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator

        if (v.hasVibrator()) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                v.vibrate(VibrationEffect.createWaveform(pattern, -1))
            } else {
                //deprecated in API 26
                @Suppress("DEPRECATION")
                v.vibrate(pattern, -1)
            }
        }
    }

И не забудьте установить разрешение в манифесте:

<uses-permission android:name="android.permission.VIBRATE" />

Все это, кроме функции вибрации, входит в вашу функцию override fun onMessageReceived(msg: RemoteMessage).

person Yani2000    schedule 25.03.2021