Webview音频播放背景

时间:2015-03-23 21:56:38

标签: android webview

Hy guys;) 我有一个很大的问题: 如何让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);
    }
}

有人可以帮帮我吗? 谢谢你们;)

1 个答案:

答案 0 :(得分:0)

我认为对于Android,app(你的活动)一旦不在主屏幕上就会被杀死。 (有关Android Life Cycle

的更多信息,请参阅文档

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

或者您可以使用提到的here提及的webView发回来的网址:

  

1)抓住Android App中的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);