Fabio Pinna
Fabio Pinna

Reputation: 75

Webview audio play on background

Hy guys ;) I have a big question: How can i let a webview continue playing audio in background? Here is my code of MainActivity (there is useless code, i know, i'm adjusting it)

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);
    }
}

Can someone maybe help me? Thanks guys ;)

Upvotes: 2

Views: 3764

Answers (1)

kaho
kaho

Reputation: 4784

I think for Android, app (your activity) get kill once it is not on the main screen. (Refer to the doc for more info about Android Life Cycle)

One way to run your app in background is to run it as Services.

Or you can send the URL back from the webView using this hack mentioned here:

1) catch the onJsAlert in the Android App.
2) then use webView.loadUrl("javascript:alert(functionThatReturnsMusicURL)") to trigger the JS in the web page to return your song address.

Then you can launch an intent to open the song in the default music player like this to "play it in the background":

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

Upvotes: 1

Related Questions