簡體   English   中英

即使關閉應用程序,我在Android應用程序中的背景音樂服務仍可以繼續播放

[英]My background music service in Android app keeps on playing even when I close the app

我正在使用后台服務在所有活動中為我的應用運行背景音樂! 問題是,當該應用運行時,它可以正常運行,但是當我關閉它時,它將繼續播放音樂,直到從設備上將其卸載為止!

您如何看待這里的問題?

這是我的后台服務中的代碼:

/**
* 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運行的代碼:

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

而且,當然我確實在清單中聲明了它=)預先感謝!

在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;
    }

希望這對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM