public?class?MyService?extends?Service?{ ????private?MediaPlayer?media; ????@Override ????public?void?onCreate()?{ ????????Log.i("msg",?"onCreate"); ????????media?=?MediaPlayer.create(this,?R.raw.aw); ????????media.setLooping(false); ????????try?{ ????????????media.prepare();//准备 ????????}?catch?(IllegalStateException?e)?{ ????????????//?TODO?Auto-generated?catch?block ????????????e.printStackTrace(); ????????}?catch?(IOException?e)?{ ????????????//?TODO?Auto-generated?catch?block ????????????e.printStackTrace(); ????????} ????????super.onCreate(); ????} ????@Override ????public?int?onStartCommand(Intent?intent,?int?flags,?int?startId)?{ ????????Log.i("msg",?"onStartCommand:?"+intent.getStringExtra("info")); ????????switch?(intent.getIntExtra("oop",?0))?{ ????????case?1://开始音乐 ????????????if(media?!=?null?&&?!media.isPlaying()?){ ????????????????media.start();//播放 ????????????} ????????????break; ????????case?2://重头开始 ????????????if(media?!=?null){???? ????????????????media.seekTo(0); //????????????????media.stop(); //????????????????media?=?MediaPlayer.create(this,?R.raw.aw); //????????????????try?{ //????????????????????media.prepare(); //????????????????}?catch?(IllegalStateException?e)?{ //????????????????????//?TODO?Auto-generated?catch?block //????????????????????e.printStackTrace(); //????????????????}?catch?(IOException?e)?{ //????????????????????//?TODO?Auto-generated?catch?block //????????????????????e.printStackTrace(); //????????????????} //????????????????media.start(); ????????????} ????????????break; ????????case?3://暂停 ????????????if(media?!=?null?&&?media.isPlaying()){ ????????????????media.pause(); ????????????} ????????????break; ????????default: ????????????break; ????????} ????????return?super.onStartCommand(intent,?flags,?startId); ????} ????@Override ????public?IBinder?onBind(Intent?intent)?{ ????????Log.i("msg",?"onBind"); ????????return?null; ????} ????@Override ????public?boolean?onUnbind(Intent?intent)?{ ????????Log.i("msg",?"onUnbind"); ????????return?super.onUnbind(intent); ????} ????@Override ????public?void?onDestroy()?{ ????????Log.i("msg",?"onDestroy"); ????????if(media?!=?null){ ????????????media.stop(); ????????????media.release();//释放 ????????????media?=?null; ????????} ????????super.onDestroy(); ????} } |