user3739754
user3739754

Reputation: 23

How to stop audio playback when a phone call arrives in Android

hello im new to android and im doing a simple online radio app for my church the poblem is that i need the playback service to stop and restart when the phone gets a call and end it so far i can stop the service just fine but when it gets started again just crashes so i dont know what im doing wrong

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.res.Resources;
import android.os.IBinder;
import android.os.PowerManager.WakeLock;
import android.support.v4.app.NotificationCompat;
import com.spoledge.aacdecoder.MultiPlayer;


public class RadioService extends Service{


     WakeLock wakelock;
     //TelephonyManager teleManager= null;
     //PhoneStateListener listener;
     NotificationManager mNotificationManager;
     public static MultiPlayer aacPlayer;
     public static String radio;
     private static Boolean isTuning;

    // private TeleListener myListener = null;



     @Override
        public IBinder onBind(Intent intent) {
            // TODO Auto-generated method stub
            return null;
        }


     @Override
     public void onCreate(){
            super.onCreate();
            setTuning(false);

            setRadio(getString(R.string.rhema));
            aacPlayer = new MultiPlayer();





    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId){

        setTuning(true);

                setTuning(true);

            aacPlayer.playAsync(radio);
            //CallReceiver.setTuning(true);

            Resources r= getResources();
            String[] Notify = r.getStringArray(R.array.PlayNotify);
            // prepare intent which is triggered if the
            // notification is selected

            Intent inten = new Intent(this, PlayerActivity.class);
            PendingIntent pIntent = PendingIntent.getActivity(this, 0, inten, 0);

            // build notification
            // the addAction re-use the same intent to keep the example short
            NotificationCompat.Builder n  = new NotificationCompat.Builder(this)
                    .setContentTitle(Notify[0])
                    .setContentText(Notify[1])
                    .setSmallIcon(R.drawable.noti_icon)
                    .setContentIntent(pIntent)
                    .setAutoCancel(true)
                    .setOngoing(true)
                    .setContentIntent(pIntent);

            Notification hola = n.build();
            startForeground(100, hola);

            //startForeground(startId, notification);
        return START_STICKY;
    }

     @Override
        public void onDestroy() {
            // TODO Auto-generated method stub
            pause();


            //CallReceiver.setTuning(false);
            super.onDestroy();

        }
    public static boolean getTuning() {
        return isTuning;
    }
    public void setTuning(boolean Tuning) {
        isTuning = Tuning;
    }
    public void setRadio(String r){
        radio = r;
    }

    public void PlayNotify(){
        Resources r= getResources();
        String[] Notify = r.getStringArray(R.array.PlayNotify);
        // prepare intent which is triggered if the
        // notification is selected

        Intent intent = new Intent(this, RadioService.class);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

        // build notification
        // the addAction re-use the same intent to keep the example short
        NotificationCompat.Builder n  = new NotificationCompat.Builder(this)
                .setContentTitle(Notify[0])
                .setContentText(Notify[1])
                .setSmallIcon(R.drawable.noti_icon)
                .setContentIntent(pIntent)
                .setAutoCancel(true);

        n.setOngoing(true);   
        n.setContentIntent(pIntent);
        //NotificationManager mNotificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            // mId allows you to update the notification later on.
            mNotificationManager.notify(100, n.build()); 
    }

    public static void play(){
        aacPlayer.playAsync(radio);

    }
    public static void pause(){
        aacPlayer.stop();

    }

}

and this is the broadcast

    import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

public class CallReceiver extends BroadcastReceiver{
    TelephonyManager telManager;
    Context context;
    public static boolean Tuning = false;
    PlayerActivity mainActivity;
    NotificationManager mNotificationManager;

@Override
public void onReceive(Context context, Intent intent) {


            mainActivity=new PlayerActivity();


    this.context=context;

    telManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
    telManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);

}

private final PhoneStateListener phoneListener = new PhoneStateListener() {

    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        try {
            switch (state) {
            case TelephonyManager.CALL_STATE_RINGING: {
                //PAUSE
                if(Tuning){

                    context.stopService(new Intent(context,RadioService.class));
                    }

            break;
            }
            case TelephonyManager.CALL_STATE_OFFHOOK: {
                if(Tuning){

                    context.stopService(new Intent(context,RadioService.class));
                }

            break;
            }
            case TelephonyManager.CALL_STATE_IDLE: {
                //PLAY
                if(Tuning){

                    showNotification(context);
                    context.stopService(new Intent(context,RadioService.class));}
            break;
            }
            default: { }
            }
            } catch (Exception ex) {

            }
        }

    };

    public static void setTuning(boolean r){

        Tuning = r;
    }
    private void showNotification(Context context) {
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
                new Intent(context, PlayerActivity.class), 0);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.noti_icon)
                .setContentTitle("Rhema Stereo")
                .setContentText("Vuelve a Sintonizarnos.");
        mBuilder.setContentIntent(contentIntent);
        mBuilder.setDefaults(Notification.DEFAULT_SOUND);
        mBuilder.setAutoCancel(true);
        NotificationManager mNotificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(1, mBuilder.build());}

 }

the weir thing is that from the activities i can start and stop the service just fine but here i can only stop it. So for now im using a notification to get back to an activity and restart the service

Upvotes: 2

Views: 2190

Answers (2)

matiash
matiash

Reputation: 55350

If I may, I would suggest another approach for this problem. You state that:

i need the playback service to stop and restart when the phone gets a call

However, the issue is more complex. You should also stop playback, for example, when a notification arrives, or if another music player is started by the user. Instead of having to monitor all these posibilities independently, Android provides built-in support for this concept -- it's called the audio focus. In broad terms, it means that only one app can have audio focus at one point in time, and that you should relinquish if it asked to.

This behavior can be obtained by using an OnAudioFocusChangeListener.

Basically, you must:

  • Request audio focus before starting playback.
  • Only start playback if you effectively obtain it.
  • Abandon focus when you stop playback.
  • Handle audio focus loss (either by lowering volume or stopping playback altogether).

Please check the Managing Audio Focus article in the Android documentation.

Upvotes: 3

Joe Sebin
Joe Sebin

Reputation: 450

you need to add this snippet in your current activity

IntentFilter receiverFilter = new IntentFilter(
        Intent.ACTION_HEADSET_PLUG);
BootBroadcast receiver = new BootBroadcast();
registerReceiver(receiver, receiverFilter);

then the same need to register in the receiver manifest.xml

eg:

<receiver
            android:name="YOUR_ACTION_STRING.BootCompletedReceiver"
            android:enabled="true"
            android:exported="false" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

Also add this flag inside BootBroadcast class

newIntent .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Upvotes: 0

Related Questions