来电和播放音乐

时间:2014-08-04 19:54:22

标签: android

我需要为来电停止音乐,然后在通话结束后播放,而且这是我使用的代码,但不要工作音乐不停止我不知道这段代码有什么问题? 我希望在通话时停止音乐,只有铃声我想听,但现在音乐和铃声在同一时间播放

package com.test.test;

import java.io.IOException;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;


public class StreamService extends Service {
    private static final String TAG = "StreamService";
    MediaPlayer mp;
    boolean isPlaying;
    SharedPreferences prefs;
    SharedPreferences.Editor editor;
    Notification n;
    NotificationManager notificationManager;


    // Change this int to some number specifically for this app
    int notifId = 5315;

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

    @SuppressWarnings("deprecation")
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");

        // Init the SharedPreferences and Editor
        prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        editor = prefs.edit();

        // Set up the buffering notification
        notificationManager = (NotificationManager) getApplicationContext()
                .getSystemService(NOTIFICATION_SERVICE);
        Context context = getApplicationContext();

        String notifTitle = context.getResources().getString(R.string.app_name);
        String notifMessage = context.getResources().getString(R.string.buffering);

        n = new Notification();
        n.icon = R.drawable.ic_launcher;
        n.tickerText = "Buffering";
        n.when = System.currentTimeMillis();

        Intent nIntent = new Intent(context, MainActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(context, 0, nIntent, 0);

        n.setLatestEventInfo(context, notifTitle, notifMessage, pIntent);

        notificationManager.notify(notifId, n);

        // It's very important that you put the IP/URL of your ShoutCast stream here
        // Otherwise you'll get Webcom Radio
        String url = "http://3.187.5.93:9230/";
        mp = new MediaPlayer();
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            mp.setDataSource(url);
            mp.prepare();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            Log.e(TAG, "SecurityException");
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            Log.e(TAG, "IllegalStateException");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.e(TAG, "IOException");
        }   
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onStart(Intent intent, int startId) {
        Log.d(TAG, "onStart");
        mp.start();
        // Set the isPlaying preference to true
        editor.putBoolean("isPlaying", true);
        editor.commit();

        Context context = getApplicationContext();
        String notifTitle = context.getResources().getString(R.string.app_name);
        String notifMessage = context.getResources().getString(R.string.now_playing);

        n.icon = R.drawable.ic_launcher;
        n.tickerText = notifMessage;
        n.flags = Notification.FLAG_NO_CLEAR;
        n.when = System.currentTimeMillis();

        Intent nIntent = new Intent(context, MainActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(context, 0, nIntent, 0);

        n.setLatestEventInfo(context, notifTitle, notifMessage, pIntent);
        // Change 5315 to some nother number
        notificationManager.notify(notifId, n);
    }



    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy");
        mp.stop();
        mp.release();
        mp = null;
        editor.putBoolean("isPlaying", false);
        editor.commit();
        notificationManager.cancel(notifId);
    }

    private class PhoneCallListener extends PhoneStateListener {

        private boolean isPhoneCalling = false;

        // needed for logging
        String TAG = "PhoneCallListener";

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {

            if (TelephonyManager.CALL_STATE_RINGING == state) {
                // phone ringing
                Log.i(TAG, "RINGING, number: " + incomingNumber);
            }

            if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
                // active
                Log.i(TAG, "OFFHOOK");

                isPhoneCalling = true;
            }

            if (TelephonyManager.CALL_STATE_IDLE == state) {
                // run when class initial and phone call ended,
                // need detect flag from CALL_STATE_OFFHOOK
                Log.i(TAG, "IDLE");

                if (isPhoneCalling) {

                    Log.i(TAG, "restart app");

                    // restart call application
                    Intent i = getBaseContext().getPackageManager()
                            .getLaunchIntentForPackage(
                                    getBaseContext().getPackageName());
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                            | Intent.FLAG_ACTIVITY_CLEAR_TOP
                            | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(i);

                    isPhoneCalling = false;
                }

            }


    }
    }

}

1 个答案:

答案 0 :(得分:0)

 private OnAudioFocusChangeListener focusChangeListener =
              new OnAudioFocusChangeListener() {
                      public void onAudioFocusChange(int focusChange) {
                        switch (focusChange) {

                               case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) :
                               // Lower the volume while ducking.
                               mp.setVolume(0.2f, 0.2f);
                               break;
                               case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) :
                               mp.pause();
                               break;

                               case (AudioManager.AUDIOFOCUS_LOSS) :
                               mp.stop();

                               break;

                               case (AudioManager.AUDIOFOCUS_GAIN) :
                               // Return the volume to normal and resume if paused.
                               mp.setVolume(1f, 1f);
                               mp.start();
                               break;
                               default: break;
    }
    }
    };




    AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

            // Request audio focus for playback
            int result = am.requestAudioFocus(focusChangeListener,
            // Use the music stream.
            AudioManager.STREAM_MUSIC,
            // Request permanent focus.
            AudioManager.AUDIOFOCUS_GAIN);


            if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            // other app had stopped playing song now , so u can do u stuff now .

            }
                }
相关问题