Android - 背景音频服务部队关闭

时间:2015-12-09 10:59:46

标签: android

我正在为Android设备开发音频流应用程序,我对处理背景音频服务有一些问题。

我的应用程序的预期行为是音频源将连续播放,即使设备处于待机模式且屏幕关闭,但有时候背景音频服务会在没有任何明显原因的情况下中断。

要解决此问题,我已使用START_STICKY选项启动了该服务。

通过这种方式,即使服务因任何原因被关闭,服务也会重新启动,但现在我无法通过强制关闭应用程序来关闭服务,有时服务会重新启动,即使我想要关闭它!

有人能建议我正确的方法来处理这份工作吗?

这是我的代码:

首先,我已在 MainActivity 中声明了意图:

Intent playbackServiceIntent;

MainActivity onCreate()方法内,我已注册该服务:

playbackServiceIntent = new Intent(this, BackgroundAudioService.class);

通过播放按钮启动音频服务:

startService(playbackServiceIntent);

通过停止按钮

停止服务
stopService(playbackServiceIntent); 

我已经覆盖了 MainActivity onDestroy()方法:

@Override
    public void onDestroy() {

            stopService(playbackServiceIntent); 
            //stopService(new Intent(this,BackgroundAudioService.class));           

            super.onDestroy();
}

最后, BackgroundAudioService 类定义如下:

public class BackgroundAudioService extends Service implements OnCompletionListener {


public MediaPlayer mediaPlayer;
public WifiLock wifiLock;   
PhoneStateListener mPhoneStateListener;


@Override
public IBinder onBind(Intent intent) {      

    return null;
}

@Override
public void onCreate() {

    mediaPlayer = new MediaPlayer();        // raw/s.mp3
    mediaPlayer.setOnCompletionListener(this);      
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);  

    try {

        mediaPlayer.setDataSource(url);     

    } catch (Exception e) {
        // TODO Auto-generated catch block          
        e.printStackTrace();         
    }       

    wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
            .createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");

    wifiLock.acquire();             

    mediaPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
        public void onBufferingUpdate(MediaPlayer mp, int percent) {                    

        }
    });


    mPhoneStateListener = new PhoneStateListener()
    {
        protected boolean mWasPlayingWhenCalled = false;

        @Override
        public void onCallStateChanged(int state, String incomingNumber)
        {
            if( state == TelephonyManager.CALL_STATE_RINGING )
            { // Incoming call: Pause music

                mediaPlayer.pause();
                mWasPlayingWhenCalled = true;
            }

            else if(state == TelephonyManager.CALL_STATE_IDLE )
            {  // Not in call: Play music
                if( mWasPlayingWhenCalled )
                {
                    mediaPlayer.start();
                    mWasPlayingWhenCalled = false;                  
                }
            }
            else if( state == TelephonyManager.CALL_STATE_OFFHOOK )
            { // A call is dialing, active or on hold

                mediaPlayer.pause();
                mWasPlayingWhenCalled = true;                   
            }                   

            super.onCallStateChanged(state, incomingNumber);
        }
    };      


    TelephonyManager mgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
    mgr.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}


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

    if (!mediaPlayer.isPlaying()) {             

        mediaPlayer.prepareAsync();
        mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
            public void onPrepared(MediaPlayer mp) {
                mediaPlayer.start();

                Intent intent = new Intent();
                intent.setAction("com.my_app.CUSTOM_INTENT");
                sendBroadcast(intent);
            }
        });

        Time t=new Time();
        t.setToNow();   
    }

    return START_STICKY;        
}

public void onDestroy() {
    if (mediaPlayer.isPlaying()) {
        mediaPlayer.stop();     
    }
    wifiLock.release();
    mediaPlayer.release();      


    TelephonyManager mgr1 = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    if(mgr1 != null) {
        mgr1.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
    }       

    Time t=new Time();
    t.setToNow();           
}

public void onCompletion(MediaPlayer _mediaPlayer) {
    stopSelf();
    Time t=new Time();
    t.setToNow();       
}

}

0 个答案:

没有答案