user279297
user279297

Reputation: 41

Stop App On Incomming Phone Call?

How would I stop music playing so call the OnPause if there is a incoming or outgoing call?

So once there is a call or they make a call it will stop the music by calling OnPause.

package com.beanie.samples.streaming;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import com.beanie.samples.streaming.R;
import com.beanie.samples.streaming.MyService;

import android.app.Activity;
import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

;



public class HomeActivity extends Activity implements OnClickListener {
      private static final String TAG = "MyServices";

    private final static String RADIO_STATION_URL = "http://195.154.237.162:8936/";

    private static final String START_STICKY = null;
      Button buttonPlay, buttonStopPlay;


        /** Called when the activity is first created.
         * Keep this here all the application will stop working */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            initializeUIElements();

            initializeMediaPlayer();

            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            buttonPlay = (Button) findViewById(R.id.buttonPlay);
            buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);

            buttonPlay.setOnClickListener(this);
            buttonStopPlay.setOnClickListener(this);
         }

    private ProgressBar playSeekBar;
    private MediaPlayer player;
    private InputStream recordingStream;
    private RecorderThread recorderThread;
    private boolean isRecording = false;

    private void initializeUIElements() {

        playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
        playSeekBar.setMax(100);
        playSeekBar.setVisibility(View.INVISIBLE);

        buttonPlay = (Button) findViewById(R.id.buttonPlay);
        buttonPlay.setOnClickListener(this);

        buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
        buttonStopPlay.setEnabled(false);
        buttonStopPlay.setOnClickListener(this);
      }

    public void getTelephonyOverview(final TelephonyManager telMgr) 
    { 

    int callState = telMgr.getCallState(); 
    String callStateString = "NA"; 
    switch (callState) { 
    case TelephonyManager.CALL_STATE_IDLE: 

    getLastCallLogEntry(Appinfo.this); 

    break;  
    case TelephonyManager.CALL_STATE_OFFHOOK: 
    Log.i("Call","started"); 
    break; 
    case TelephonyManager.CALL_STATE_RINGING: 
    Log.i("Call","ringing"); 
    break; 
    } 
    } 

    public void startPlaying() {
        buttonStopPlay.setEnabled(true);
        buttonPlay.setEnabled(false);

        playSeekBar.setVisibility(View.VISIBLE);

        player.prepareAsync();

        player.setOnPreparedListener(new OnPreparedListener() {

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

    }

    private void onBufferingUpdate(MediaPlayer mp, int percent) {

         playSeekBar.setSecondaryProgress(percent);
        Toast.makeText(this, "Buffering ", percent).show();


          Log.i("Buffering", "" + percent);
    }


    public void onClick(View v) {
        if (v == buttonPlay) {
            onBufferingUpdate(player, 0);
            Log.d(TAG, "onClick: starting srvice");
            startPlaying();
            player.setLooping(false); // Set looping
     }
       else if (v == buttonStopPlay) {

        Log.d(TAG, "onClick: stopping srvice");
            stopPlaying();

        }
    }

   private void stopPlaying() {
        if (player.isPlaying()) {
            player.stop();
            player.release();
            initializeMediaPlayer();
        }

        buttonPlay.setEnabled(true);
        buttonStopPlay.setEnabled(false);
        playSeekBar.setVisibility(View.INVISIBLE);

        stopRecording();
    }

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

    }


    private void startRecording() {

        BufferedOutputStream writer = null;
        try {
            URL url = new URL(RADIO_STATION_URL);
            URLConnection connection = url.openConnection();
            final String FOLDER_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + File.separator + "Songs";

            File folder = new File(FOLDER_PATH);
            if (!folder.exists()) {
                folder.mkdir();
            }

            writer = new BufferedOutputStream(new FileOutputStream(new File(FOLDER_PATH
                    + File.separator + "sample.mp3")));
            recordingStream = connection.getInputStream();

            final int BUFFER_SIZE = 100;

            byte[] buffer = new byte[BUFFER_SIZE];

            while (recordingStream.read(buffer, 0, BUFFER_SIZE) != -1 && isRecording) {
                writer.write(buffer, 0, BUFFER_SIZE);
                writer.flush();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                recordingStream.close();
                writer.flush();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void stopRecording() {

        try {
            isRecording = false;
            if (recordingStream != null) {
                recordingStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private class RecorderThread extends Thread {
        @Override
        public void run() {
            isRecording = true;
            startRecording();
        }

    };
}

Upvotes: 0

Views: 706

Answers (2)

Martin Marconcini
Martin Marconcini

Reputation: 27226

You don't need to do anything in your lifecycle methods to stop the music. Android provides you with a mechanism to handle these cases.

The mechanism is called Audio Focus. Apps request Audio Focus when they want to play audio (or video!). When another app needs audio, it requests the Audio Focus. And the subscribed parties receive a broadcast saying: Hey, you've lost the audio focus. If the focus was only temporarily lost (like when a notification comes and it plays a short audio beep) then the Broadcast says: Hey, you've lost the audio focus but duck the audio, I'll give it back in a moment. The idea in that case is that you lower (duck) your volume to 0.1 (for example) to let the other sound (beep) be louder.

After the "beep" from the notification is done, the broadcast says: hey, here's the audio focus you had earlier.

At this point if you're still playing, you'd restore the volume to what it was before.

That's the concept behind audio focus. It's perfectly explained in the Android Docs (and the Android Samples) albeit the Google code is rather messy and inconsistent, it does work out of the box. They do a lot of crappy abstraction and some strange code practices but irregardless of that, the code works fine.

The same goes for a phone call, you subscribe to it and tell your service to pause/resume the sound when there's a call in progress. Not when your app goes to the background (onpause) because that's unreliable and doesn't mean at all that you app went to the background.

Here's the Android Official Docs for Audio Focus.

Upvotes: 0

An SO User
An SO User

Reputation: 24998

how would I stop music playing so call the OnPause

onPause() and onStop() are lifecycle methods that will be called automatically; you do not call them manually. You should override them and add your code that would stop the music.

Upvotes: 1

Related Questions