2016-12-08 36 views
0

我正在使用後臺服務在我的應用程序的所有活動中運行背景音樂!問題是,當應用程序運行時,它工作正常,但是當我關閉它時,它會繼續播放音樂,直到我從設備上卸載它!即使在關閉應用程序時,我的Android應用程序中的背景音樂服務仍會繼續播放

您認爲這裏的問題是什麼?

下面的代碼是在我的後臺服務:

/** 
* Created by Naira on 12/5/2016. 
*/ 

public class Background_music extends Service { 
private static final String TAG = null; 
MediaPlayer player; 
public IBinder onBind(Intent arg0) { 

    return null; 
} 
@Override 
public void onCreate() { 
    super.onCreate(); 
    player = MediaPlayer.create(this, R.raw.music); 
    player.setLooping(true); // Set looping 
    player.setVolume(50,50); 

} 
public int onStartCommand(Intent intent, int flags, int startId) { 


    player.start(); 

    return START_STICKY; 
} 

public void onStart(Intent intent, int startId) { 
    // TO DO 
} 
public IBinder onUnBind(Intent arg0) { 
    // TO DO Auto-generated method 
    return null; 
} 

public void onStop() { 


} 
public void onPause() { 


} 
@Override 
public void onDestroy() { 
    player.stop(); 
    player.release(); 
    player = null; 
} 

@Override 
public void onLowMemory() { 

} 
} 

一個在這裏我第一次活動的代碼來運行它作爲一個意圖:

Intent svc=new Intent(this, Background_music.class); 
startService(svc); 

,當然我沒有把它聲明在我的清單=) 在此先感謝!

+0

你爲什麼使用START_STICKY TAG – Noorul

+0

即使你的活動沒有運行,服務也會運行。在關閉活動時停止服務。那就是所有 – Noorul

+0

@Naira Hashim:使用'BindingService'! – AndiGeeky

回答

1

在MainActivity的onDestroy()方法中,您必須停止服務。

@Override 
    protected void onDestroy() { 
     super.onDestroy(); 
     if(isMyServiceRunning(Background_music.class)) 
     { 
      stopService(new Intent(this, Background_music.class)); 
     } 
    } 


private boolean isMyServiceRunning(Class<?> serviceClass) { 
     ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); 
     for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { 
      if (serviceClass.getName().equals(service.service.getClassName())) { 
       return true; 
      } 
     } 
     return false; 
    } 

希望這可以幫助你。

+0

非常感謝!它幫助了我很多= D(爲你而奮鬥) –

+0

非常歡迎你。編碼 –

相關問題