Android Open Source - example Stream Service






From Project

Back to project page example.

License

The source code is released under:

Apache License

If you think the Android project example listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package id.pratama.example.streamingaudio.service;
//ww w . ja  va 2 s.c  om
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;

import id.pratama.example.streamingaudio.MainActivity;
import id.pratama.example.streamingaudio.R;

/**
 * Created by pratama on 4/22/14.
 */
public class StreamService extends Service implements
        MediaPlayer.OnCompletionListener,
        MediaPlayer.OnPreparedListener,
        MediaPlayer.OnErrorListener,
        MediaPlayer.OnBufferingUpdateListener {

    /**
     * for educational only
     */
    // public static final String URL_STREAM = "http://jkt.jogjastreamers.com:8000/jisstereo?s=02766";

    // radio UNISI
    public static final String URL_STREAM = "http://202.162.32.23:8000";

    // notification
    private static final int NOTIFICATION_ID = 1;
    private PhoneStateListener phoneStateListener;
    private TelephonyManager telephonyManager;
    private boolean isPausedInCall = false;
    private NotificationCompat.Builder builder;

    //intent
    private Intent bufferIntent;

    public static final String BROADCAST_BUFFER = "id.pratama.example.streamingaudio.broadcastbuffer";

    private MediaPlayer mediaPlayer = new MediaPlayer();

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("create", "service created");

        bufferIntent = new Intent(BROADCAST_BUFFER);

        mediaPlayer.setOnCompletionListener(this);
        mediaPlayer.setOnPreparedListener(this);
        mediaPlayer.setOnErrorListener(this);
        mediaPlayer.setOnBufferingUpdateListener(this);

        mediaPlayer.reset();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("play", "play streaming");

        telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        phoneStateListener = new PhoneStateListener() {
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                switch (state) {
                    case TelephonyManager.CALL_STATE_OFFHOOK:
                    case TelephonyManager.CALL_STATE_RINGING:
                        if (mediaPlayer != null) {
                            pauseMedia();
                            isPausedInCall = true;
                        }
                        break;
                    case TelephonyManager.CALL_STATE_IDLE:
                        if (mediaPlayer != null) {
                            if (isPausedInCall) {
                                isPausedInCall = false;
                                playMedia();
                            }
                        }
                        break;
                }
            }
        };

        telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);

        initNotification();

        mediaPlayer.reset();

        /**
         * play media
         */
        if (!mediaPlayer.isPlaying()) {
            try {
                Log.d("streamm", "" + URL_STREAM);
                mediaPlayer.setDataSource(URL_STREAM);

                // sent to UI radio is buffer
                sendBufferingBroadcast();

                mediaPlayer.prepareAsync();
            } catch (IllegalArgumentException e) {
                Log.d("error", e.getMessage());
            } catch (IllegalStateException e) {
                Log.d("error", e.getMessage());
            } catch (IOException e) {
                Log.d("error", e.getMessage());
            }
        }

        return START_STICKY;
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) {
    }


    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        stopMedia();
        stopSelf();
    }


    @Override
    public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
        switch (what) {
            case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
                Toast.makeText(this, "Error not valid playback", Toast.LENGTH_SHORT).show();
                break;
            case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
                Toast.makeText(this, "Error server died", Toast.LENGTH_SHORT).show();
                break;
            case MediaPlayer.MEDIA_ERROR_UNKNOWN:
                Toast.makeText(this, "Error unknown", Toast.LENGTH_SHORT).show();
                break;
        }
        return false;
    }


    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        // sent to UI, audio has buffered
        sendBufferCompleteBroadcast();

        playMedia();
    }


    private void pauseMedia() {
        if (mediaPlayer.isPlaying())
            mediaPlayer.pause();
    }

    private void playMedia() {
        if (!mediaPlayer.isPlaying()) {
            mediaPlayer.start();
        }
    }

    private void stopMedia() {
        if (mediaPlayer.isPlaying())
            mediaPlayer.stop();
    }

    /**
     * sent buffering
     */
    private void sendBufferingBroadcast() {
        bufferIntent.putExtra("buffering", "1");
        sendBroadcast(bufferIntent);
    }

    /**
     * sent buffering complete
     */
    private void sendBufferCompleteBroadcast() {
        bufferIntent.putExtra("buffering", "0");
        sendBroadcast(bufferIntent);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("tag", "remove notification");
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.release();
        }

        if (phoneStateListener != null) {
            telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
        }

        cancelNotification();
    }

    /**
     * show notificaiton
     */
    private void initNotification() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        PendingIntent intent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
        builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("Stream Radio")
                .setContentText("895 JIZ fm");
        builder.setContentIntent(intent);
        builder.setOngoing(true);
        notificationManager.notify(NOTIFICATION_ID, builder.build());

    }

    /**
     * cancel notification
     */
    private void cancelNotification() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(NOTIFICATION_ID);
        builder.setOngoing(false);
    }


}




Java Source Code List

com.pratamawijaya.example_gson.ApplicationTest.java
com.pratamawijaya.example_gson.MainActivity.java
com.pratamawijaya.examplebuildflavor.ApplicationTest.java
com.pratamawijaya.examplebuildflavor.MainActivity.java
com.pratamawijaya.exampledynamicedittext.ApplicationTest.java
com.pratamawijaya.exampledynamicedittext.MainActivity.java
com.pratamawijaya.examplefragment.ApplicationTest.java
com.pratamawijaya.examplefragment.MyActivity.java
com.pratamawijaya.examplefragment.MyFragment.java
com.pratamawijaya.examplefusedlocation.ApplicationTest.java
com.pratamawijaya.examplefusedlocation.MainActivity.java
com.pratamawijaya.exampleinstagram.ApplicationTest.java
com.pratamawijaya.exampleinstagram.BaseActivity.java
com.pratamawijaya.exampleinstagram.BaseApplication.java
com.pratamawijaya.exampleinstagram.MainActivity.java
com.pratamawijaya.exampleinstagram.authentication.InstagramApp.java
com.pratamawijaya.exampleinstagram.authentication.InstagramWebviewAuthActivity.java
com.pratamawijaya.examplepallete.ApplicationTest.java
com.pratamawijaya.examplepallete.MainActivity.java
com.pratamawijaya.examplepallete.adapter.CoverAdapter.java
com.pratamawijaya.examplepallete.model.CoverItem.java
com.pratamawijaya.exampleparse.ApplicationTest.java
com.pratamawijaya.exampleparse.BaseApplication.java
com.pratamawijaya.exampleparse.MainActivity.java
com.pratamawijaya.examplerealmio.ApplicationTest.java
com.pratamawijaya.examplerealmio.InsertDataActivity.java
com.pratamawijaya.examplerealmio.MainActivity.java
com.pratamawijaya.examplerealmio.ReadDataActivity.java
com.pratamawijaya.examplerealmio.User.java
com.pratamawijaya.exampleretrofit.ApplicationTest.java
com.pratamawijaya.exampleretrofit.MyActivity.java
id.pratama.example.cardslib.MainActivity.java
id.pratama.example.facebooklogin.MainActivity.java
id.pratama.example.streamingaudio.CobaSaja.java
id.pratama.example.streamingaudio.MainActivity.java
id.pratama.example.streamingaudio.Test.java
id.pratama.example.streamingaudio.service.StreamService.java
id.pratama.example.streamingaudio.utils.Utils.java
id.pratama.example.volley.MainActivity.java
it.gmariotti.cardslib.library.Constants.java
it.gmariotti.cardslib.library.internal.CardArrayAdapter.java
it.gmariotti.cardslib.library.internal.CardArrayMultiChoiceAdapter.java
it.gmariotti.cardslib.library.internal.CardCursorAdapter.java
it.gmariotti.cardslib.library.internal.CardExpand.java
it.gmariotti.cardslib.library.internal.CardGridArrayAdapter.java
it.gmariotti.cardslib.library.internal.CardGridCursorAdapter.java
it.gmariotti.cardslib.library.internal.CardHeader.java
it.gmariotti.cardslib.library.internal.CardThumbnail.java
it.gmariotti.cardslib.library.internal.Card.java
it.gmariotti.cardslib.library.internal.ViewToClickToExpand.java
it.gmariotti.cardslib.library.internal.base.BaseCardArrayAdapter.java
it.gmariotti.cardslib.library.internal.base.BaseCardCursorAdapter.java
it.gmariotti.cardslib.library.internal.base.BaseCard.java
it.gmariotti.cardslib.library.internal.base.CardUIInferface.java
it.gmariotti.cardslib.library.internal.multichoice.DefaultOptionMultiChoice.java
it.gmariotti.cardslib.library.internal.multichoice.MultiChoiceAdapterHelperBase.java
it.gmariotti.cardslib.library.internal.multichoice.MultiChoiceAdapter.java
it.gmariotti.cardslib.library.internal.multichoice.OptionMultiChoice.java
it.gmariotti.cardslib.library.internal.overflowanimation.BaseCardOverlayAnimation.java
it.gmariotti.cardslib.library.internal.overflowanimation.BaseOverflowAnimation.java
it.gmariotti.cardslib.library.internal.overflowanimation.TwoCardOverlayAnimation.java
it.gmariotti.cardslib.library.utils.BitmapUtils.java
it.gmariotti.cardslib.library.utils.CacheUtil.java
it.gmariotti.cardslib.library.view.BaseCardView.java
it.gmariotti.cardslib.library.view.CardGridView.java
it.gmariotti.cardslib.library.view.CardListView.java
it.gmariotti.cardslib.library.view.CardView.java
it.gmariotti.cardslib.library.view.base.CardViewInterface.java
it.gmariotti.cardslib.library.view.component.CardHeaderView.java
it.gmariotti.cardslib.library.view.component.CardShadowView.java
it.gmariotti.cardslib.library.view.component.CardThumbnailView.java
it.gmariotti.cardslib.library.view.listener.SwipeDismissListViewTouchListener.java
it.gmariotti.cardslib.library.view.listener.SwipeDismissViewTouchListener.java
it.gmariotti.cardslib.library.view.listener.UndoBarController.java
it.gmariotti.cardslib.library.view.listener.UndoCard.java
me.pratama.examplebetterpickers.ApplicationTest.java
me.pratama.examplebetterpickers.MainActivity.java
me.pratama.examplelayoutforandroiddev.ApplicationTest.java
me.pratama.examplelayoutforandroiddev.MainActivity.java
me.pratama.examplelayoutforandroiddev.SoalActivity.java
me.pratama.examplelayoutforandroiddev.entity.Soal.java
me.pratama.examplematerial.ApplicationTest.java
me.pratama.examplematerial.BaseActivity.java
me.pratama.examplematerial.MainActivity.java
me.pratama.examplematerial.interpolator.CubicBezierInterpolator.java
me.pratama.examplematerial.model.Singer.java
me.pratama.examplematerial.ui.FabActivity.java
me.pratama.examplematerial.ui.RecyclerViewActivity.java
me.pratama.examplematerial.ui.adapter.RecyclerAdapter.java