Приложение WebView с html-элементом «аудио» — возможно в области уведомлений?

Когда вы посещаете веб-сайт в Chrome и воспроизводите элемент <audio>, Chrome добавляет уведомление с кнопкой воспроизведения/паузы в область уведомлений. Можно ли сделать то же самое с приложением веб-просмотра?

Мне удалось наладить работу в Android Studio, но я не могу понять, что такое уведомление

Любые указатели?

Изменить: вот пример того, что я имею в виду: https://developers.google.com/web/updates/2015/07/media-notifications Возможно ли это вообще?


person user1525    schedule 07.05.2017    source источник
comment
Мое лучшее предположение о том, что я собрал для той же проблемы, заключается в том, что вы должны использовать оценитьJavascript() и ввести/получить   -  person DrBrad    schedule 13.11.2017


Ответы (1)


Вот пример, который я сделал, он предназначен для StackOverflow, но для него нет документации. https://gist.github.com/DrBrad/7574712c6140ccc468212afa04d9e458

Поместите это в WebChromeClient.java

@Override
public void onProgressChanged(final WebView view, int newProgress){
    super.onProgressChanged(view, newProgress);
    if(newProgress == 100){

        String code = "var videoElement;" +
                "for(var i = 0; i < document.getElementsByTagName('video').length; i++){" +
                "    var vid = document.getElementsByTagName('video')[0];" +
                "    vid.onplay = function(){" +
                "        videoElement = vid;" +
                "        JSOUT.videoAction('true');" +
                "    };" +
                "    vid.onpause = function(){" +
                "        videoElement = vid;" +
                "        JSOUT.videoAction('false');" +
                "    };" +
                "}";
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            wv.evaluateJavascript(code, null);
        }else{
            wv.loadUrl("javascript:"+code);
        }
    }
}

Поместите это в JSInterface.java

public class JSInterface {

    public static boolean playing;

    @JavascriptInterface
    public void videoAction(String type){
        Log.e("Info", type);

        playing = Boolean.parseBoolean(type);

        if(playing){
            NotificationManager mNotificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification.Builder builder = new Notification.Builder(activity);
            Notification notification = builder.getNotification();
            notification.icon = R.drawable.icon;

            RemoteViews contentView = new RemoteViews(activity.getPackageName(), R.layout.custom_notification);
            notification.contentView = contentView;
            notification.flags |= Notification.FLAG_ONGOING_EVENT;

            contentView.setTextViewText(R.id.title, "Browser");
            contentView.setTextViewText(R.id.desc, "This is a description. - PLAYING");
            contentView.setImageViewResource(R.id.pausePlay, R.drawable.pause);

            PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(activity, 0, new Intent(activity, NotificationPausePlay.class), 0);
            contentView.setOnClickPendingIntent(R.id.pausePlay, pendingSwitchIntent);

            mNotificationManager.notify(99, notification);


        }else{
            NotificationManager mNotificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification.Builder builder = new Notification.Builder(activity);
            Notification notification = builder.getNotification();
            notification.icon = R.drawable.icon;

            RemoteViews contentView = new RemoteViews(activity.getPackageName(), R.layout.custom_notification);
            notification.contentView = contentView;
            notification.flags |= Notification.FLAG_ONGOING_EVENT;

            contentView.setTextViewText(R.id.title, "Browser");
            contentView.setTextViewText(R.id.desc, "This is a description. - PAUSED");
            contentView.setImageViewResource(R.id.pausePlay, R.drawable.play);

            PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(activity, 0, new Intent(activity, NotificationPausePlay.class), 0);
            contentView.setOnClickPendingIntent(R.id.pausePlay, pendingSwitchIntent);

            mNotificationManager.notify(99, notification);
        }
    }
}

Поместите это в NotificationPausePlay.java

public class NotificationPausePlay extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent){
        Log.e("Here", "I am here");

        if(playing){
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
                wv.evaluateJavascript("videoElement.pause();", null);
            }else{
                wv.loadUrl("javascript:videoElement.pause();");
            }

            NotificationManager mNotificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification.Builder builder = new Notification.Builder(activity);
            Notification notification = builder.getNotification();
            notification.icon = R.drawable.icon;

            RemoteViews contentView = new RemoteViews(activity.getPackageName(), R.layout.custom_notification);
            notification.contentView = contentView;
            notification.flags |= Notification.FLAG_ONGOING_EVENT;

            contentView.setTextViewText(R.id.title, "Browser");
            contentView.setTextViewText(R.id.desc, "This is a description. - PAUSED");
            contentView.setImageViewResource(R.id.pausePlay, R.drawable.play);

            PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(activity, 0, new Intent(activity, NotificationPausePlay.class), 0);
            contentView.setOnClickPendingIntent(R.id.pausePlay, pendingSwitchIntent);

            mNotificationManager.notify(99, notification);

            playing = false;
        }else{
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
                wv.evaluateJavascript("videoElement.play();", null);
            }else{
                wv.loadUrl("javascript:videoElement.play();");
            }

            NotificationManager mNotificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification.Builder builder = new Notification.Builder(activity);
            Notification notification = builder.getNotification();
            notification.icon = R.drawable.icon;

            RemoteViews contentView = new RemoteViews(activity.getPackageName(), R.layout.custom_notification);
            notification.contentView = contentView;
            notification.flags |= Notification.FLAG_ONGOING_EVENT;

            contentView.setTextViewText(R.id.title, "Browser");
            contentView.setTextViewText(R.id.desc, "This is a description. - PLAYING");
            contentView.setImageViewResource(R.id.pausePlay, R.drawable.play);


            PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(activity, 0, new Intent(activity, NotificationPausePlay.class), 0);
            contentView.setOnClickPendingIntent(R.id.pausePlay, pendingSwitchIntent);

            mNotificationManager.notify(99, notification);

            playing = true;
        }
    }
}

Поместите это в custom_notification.xml

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:background="#e6e6e6">

<ImageView
    android:layout_width="45dp"
    android:layout_height="45dp"
    android:id="@+id/icon"
    android:src="@drawable/icon"
    android:layout_centerVertical="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginRight="10dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/title"
    android:textSize="16dp"
    android:textStyle="bold"
    android:textColor="#000000"
    android:singleLine="true"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/icon"
    android:layout_toEndOf="@+id/icon"
    android:layout_toLeftOf="@+id/pausePlay"
    android:layout_toStartOf="@+id/pausePlay" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/desc"
    android:textSize="16dp"
    android:textColor="#5f5f5f"
    android:singleLine="true"
    android:layout_below="@+id/title"
    android:layout_toRightOf="@+id/icon"
    android:layout_toEndOf="@+id/icon"
    android:layout_toLeftOf="@+id/pausePlay"
    android:layout_toStartOf="@+id/pausePlay"/>

<ImageButton
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:id="@+id/pausePlay"
    android:scaleType="fitXY"
    android:background="#e6e6e6"
    android:layout_centerVertical="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

</RelativeLayout>

добавить это в веб-просмотр

wv.setWebChromeClient(new webChromeClient());    
wv.addJavascriptInterface(new JSInterface(), "JSOUT");

добавьте это в манифест в разделе ‹/activity>

<receiver android:name=".NotificationPausePlay" />
person DrBrad    schedule 13.11.2017
comment
Код в gist обновлен. Проверено, работает безупречно, хотя для повышения производительности требуется рефакторинг. Если вы зайдете в этот пост, вас также может заинтересовать игра в фоновом режиме как показано здесь - person Remy; 21.05.2019
comment
Спасибо :) У меня есть лучший обходной путь для фонового воспроизведения, если вы хотите, чтобы я тоже прислал вам суть. - person DrBrad; 23.05.2019
comment
Это было бы неплохо :-) Также вы можете обновить свой ответ здесь, указав лучшее решение. - person Remy; 23.05.2019
comment
Привет, @DrBrad, спасибо за это. но где я могу получить доступ к активности и wv в NotificationPausePlay.java? также игровая переменная не инициализирована. - person Marc Quebrar Tan; 27.10.2020
comment
Да, для вещей, которые не инициализированы, и я использовал для этого сопутствующий объект. Проверьте этот github.com/ rohangho/DemoDownloadPage/tree/Mp3Broadcast - person rohan ghosh; 28.10.2020
comment
@rohanghosh не работает с этим URL html5tutorial.info/html5-audio.php. когда я нажимаю кнопку воспроизведения на этом веб-сайте и приостанавливаю его с помощью управления уведомлениями, звук не приостанавливается. - person Marc Quebrar Tan; 29.10.2020
comment
вы также можете попробовать этот сайт: html.com/tags/audio - person Marc Quebrar Tan; 29.10.2020