应用程序被杀时音乐背景服务错误

时间:2018-03-09 04:35:23

标签: android service audio-player android-music-player

我正在播放音乐,我想在后台播放它但是有一个错误,当我杀了应用程序音乐重新开始,我也检查了一些吐司,再次调用服务类的oncreate方法,我该怎么办?那样做

public class MyMusicService extends Service {

    MediaPlayer mediaPlayer;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public MyMusicService() {
        super();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(getApplicationContext(),"oncreate",Toast.LENGTH_SHORT).show();

        if (mediaPlayer!= null)
        {
            mediaPlayer.release();
        }

        mediaPlayer =MediaPlayer.create(this,R.raw.song);
        mediaPlayer.setLooping(true);


    }

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

        Toast.makeText(getApplicationContext(),"start",Toast.LENGTH_SHORT).show();

        mediaPlayer.start();

         return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Toast.makeText(getApplicationContext(),"destroy",Toast.LENGTH_SHORT).show();
        super.onDestroy();
        mediaPlayer.stop();
        mediaPlayer.release();


    }
}

0 个答案:

没有答案