在接听电话上停止应用程序?

时间:2014-02-23 02:03:35

标签: java android

如何停止播放音乐,如果有来电或去电,请拨打OnPause?

因此,一旦有电话或拨打电话,它将通过呼叫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();
        }

    };
}

2 个答案:

答案 0 :(得分:1)

  

如何停止播放音乐,请调用OnPause

onPause()onStop()是将自动调用的生命周期方法;你不要手动打电话。你应该覆盖它们并添加阻止音乐的代码。

答案 1 :(得分:0)

您不需要在生命周期方法中执行任何操作来停止音乐。 Android为您提供了处理这些案例的机制。

该机制称为Audio Focus。应用程序在想要播放音频(或视频!)时请求音频焦点。当另一个应用程序需要音频时,它会请求音频焦点。订阅方收到广播说:嘿,你已经失去了音频焦点。如果焦点只是暂时丢失(就像通知到来并播放一个短暂的音频哔哔声)那么广播说:嘿,你已经失去了音频焦点但是放弃了音频,我马上就会把它还给你。 在这种情况下的想法是你将你的音量降低(低)到0.1(例如)让另一个声音(嘟嘟声)响亮。

在通知发出“嘟嘟”声之后,广播说:嘿,这是你之前的音频焦点。

此时如果你还在玩,你可以将音量恢复到以前的状态。

这是音频焦点背后的概念。它在Android Docs(以及Android Samples)中得到了完美的解释,尽管Google代码相当混乱且不一致,但它确实可以开箱即用。他们做了很多糟糕的抽象和一些奇怪的代码实践,但不管怎样,代码工作得很好。

同样适用于电话,您订阅并告诉您的服务在正在进行通话时暂停/恢复声音。不是当你的应用程序进入后台(暂停)时,因为它不可靠,并不意味着你的应用程序进入后台。

这是Android Official Docs for Audio Focus

相关问题