Приложение WebView с html ‹audio› елемент – възможно ли е в областта за уведомяване?

Когато посетите уебсайт в Chrome и възпроизведете елемент <audio>, chrome добавя известие с btn за възпроизвеждане/пауза в областта за известия. Възможно ли е да направите същото с приложение за уеб изглед?

Успях да накарам нещата да работят в Android Studio, но не мога да разбера нещо с известията

Някакви насоки?

Редактиране: Ето пример за това, което имам предвид: https://developers.google.com/web/updates/2015/07/media-notifications Това изобщо възможно ли е?


person user1525    schedule 07.05.2017    source източник
comment
Най-доброто ми предположение за това, което съм събрал за същия проблем, е, че трябва да използвате evaluateJavascript() и инжектиране/получаване   -  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