【问题标题】:Webview audio play on background后台播放 Webview 音频
【发布时间】:2015-05-27 02:10:15
【问题描述】:

大家好 ;) 我有一个大问题: 如何让 webview 继续在后台播放音频? 这是我的MainActivity代码(有无用的代码,我知道,我正在调整它)

package com.radio.radiostar;

import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.widget.Button;

import java.io.IOException;

    public class MainActivity extends ActionBarActivity implements OnClickListener {

    private final static String RADIO_STATION_URL = "";

    private Button buttonPlay;

    private Button buttonStopPlay;

    private MediaPlayer player;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WebView wv = (WebView) findViewById(R.id.webView1);

        WebSettings webSettings = wv.getSettings();
        wv.getSettings().setJavaScriptEnabled(true);
        wv.getSettings().setAppCacheEnabled(true);
        webSettings.setBuiltInZoomControls(false);

        wv.loadUrl("http://www.ustream.tv/embed/679978?v=3&wmode=direct");

        initializeUIElements();

        initializeMediaPlayer();
    }

    private void initializeUIElements() {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        boolean initialDialogDisplayed = preferences.getBoolean("InitialDialog", false);
        if (!initialDialogDisplayed) {
            Editor editor = preferences.edit();
            editor.putBoolean("InitialDialog", true);
            editor.commit();

            // Display the dialog here
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(" Attenzione");
            builder.setMessage(" Benvenuti nell'App Radio Star! Questa app necessita di una connessione ad internet per riprodurre la diretta, basata sul sito web di telesardegnanetwork."
                    + "Abilitate quindi una rete WiFi, o una rete dati, prima di premere il tasto Play."
                    + "Grazie per l'attenzione! ")
                    .setPositiveButton("Okay", new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int id) {
                        }
                    }).show();
        }
    }

    public void onClick(View v) {
        if (v == buttonPlay) {
            startPlaying();
            Context context = getApplicationContext();
            CharSequence text = "In Connessione...";
            int duration = android.widget.Toast.LENGTH_LONG;
            android.widget.Toast toast = android.widget.Toast.makeText(context, text, duration);
            toast.show();
            Intent intent = new Intent(this, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentTitle("Radio Star")
                    .setContentText("In Diretta")
                    .setContentIntent(pendingIntent);
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, mBuilder.build());

        }
        else if (v == buttonStopPlay) {
            stopPlaying();
            Intent svc = new Intent(this, BackgroundSoundService.class);
            startService(svc);
        }
    }

    private void startPlaying() {
        if (player.isPlaying()) {
            buttonPlay.setVisibility(View.INVISIBLE);
        }
        buttonStopPlay.setEnabled(true);
        buttonPlay.setEnabled(false);
        buttonPlay.setVisibility(View.INVISIBLE);

        player.prepareAsync();

        player.setOnPreparedListener(new OnPreparedListener() {
            public void onPrepared(MediaPlayer mp) {
                player.start();
            }
        });
    }

    private void stopPlaying() {
        if (player.isPlaying()) {
            player.stop();
            player.release();
            initializeMediaPlayer();
            NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
            notificationManager.cancel(0);
        }

        buttonPlay.setEnabled(true);
        buttonStopPlay.setEnabled(false);

        buttonPlay.setVisibility(View.VISIBLE);
    }

    private void initializeMediaPlayer() {
        player = new MediaPlayer();
        try {
            player.setDataSource(RADIO_STATION_URL);
        }
        catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        catch (IllegalStateException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }

        player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {

            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                Log.i("Buffering", "" + percent);
            }
        });
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(false);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        startActivity(new Intent(MainActivity.this, SecondActivity.class));   // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

有人可以帮助我吗? 谢谢大家 ;)

【问题讨论】:

  • 还有什么问题?请以更好的方式解释您的问题。
  • @joao2fast4u Ustream 不提供直接的音频流 url(页面上有关于 Oauth 的内容,但我认为这很复杂),所以我必须将播放器加载为 webview。问题是在这种模式下我没有后台服务(在这个应用程序上使用旧方法实现),因为 webview 有不同的规则(我想)。所以我的问题是当 ustream 播放器处于活动状态时如何让我的应用在后台运行;)

标签: android webview


【解决方案1】:

我认为对于 Android,应用(您的活动)一旦不在主屏幕上就会被杀死。 (有关Android Life Cycle的更多信息,请参阅文档)

在后台运行您的应用的一种方法是将其作为Services 运行。

或者您可以使用here 提到的这个hack 从webView 发回URL:

1) 在 Android 应用中捕捉onJsAlert
2)然后使用webView.loadUrl("javascript:alert(functionThatReturnsMusicURL)")触发网页中的JS返回你的歌曲地址。

然后你可以启动一个意图,在默认音乐播放器中打开歌曲,像这样“在后台播放”:

Uri musicUri = Uri.parse("yourMusicURL");
Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW); 
myIntent.setDataAndType(musicUri, "audio/*"); 
startActivity(intent);

【讨论】:

  • 您认为这也适用于 ustream 播放器吗?因为他们不提供任何直接流 url
  • intent 方法在这种情况下不起作用。但是你仍然可以尝试做一个服务来做到这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多