MediaPlayer не завершает sh и останавливается во время уведомления - PullRequest
0 голосов
/ 05 мая 2020

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

 PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);

        @SuppressLint("InvalidWakeLockTag")
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TRAININGCOUNTDOWN");
        wl.acquire(10*60*1000L /*10 minutes*/);
        Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
                R.drawable.icon);
            Intent inteent = new Intent(context, MainActivity.class);
            inteent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, xx, inteent, PendingIntent.FLAG_UPDATE_CURRENT);
        xx = xx + 1;

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
                    .setSmallIcon(R.drawable.icon)
                    .setLargeIcon(icon)
                    .setContentTitle("بانگ")
                    .setContentText(notTitle)
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    // Set the intent that will fire when the user taps the notification
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true);



        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
      // notificationId is a unique int for each notification that you must define


        // Put here YOUR code.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId("com.c4kurd.bang");
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    "com.c4kurd.bang",
                    "بانگ",
                    NotificationManager.IMPORTANCE_HIGH
            );
            channel.enableVibration(true);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }


        assert notificationManager != null;
        int id = context.getResources().getIdentifier(cc(prefs.getString("voices","")), "raw", context.getPackageName());
//                Toast.makeText(context, prefs.getString("voices",""),Toast.LENGTH_SHORT).show();
        MediaPlayer mp= MediaPlayer.create(context, id);

        notificationManager.notify(xx, builder.setVibrate(new long[]{1000,1000}).build());
        mp.start();
        wl.release();



    }

Я не знаю, в чем проблема. Это потому, что mp.start () находится перед Wake Lock? Заранее спасибо.

1 Ответ

0 голосов
/ 05 мая 2020

ПО УМОЛЧАНИЮ : эта строка возвращает звук уведомления по умолчанию

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

ПОЛЬЗОВАТЕЛЬСКИЙ : Эта строка выбирает настраиваемый звук уведомления: (поместите это в RAW (ресурсы ) папка)

Uri notificationSound = Uri.parse("android.resource://"
            + context.getPackageName() + "/" + R.raw.my_custom_sound_file);

Выберите один из вышеперечисленных и добавьте его в свое уведомление: setSound(notificationSound)

NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
                .setSmallIcon(R.drawable.icon)
                .setLargeIcon(icon)
                .setContentTitle("Your Title")
                .setContentText("Your Content")
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setContentIntent(pendingIntent)
                .setSound(notificationSound)
                .setAutoCancel(true);

Удалите все лишние строки, которые вы использовали в своем собственном MediaPlayer.

...