import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
public class MusicPlayer extends Service implements Runnable {
MediaPlayer player;
boolean flag = true;
private int duration;
private int currentPosition;
// getter, setter함수
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public int getCurrentPosition() {
return currentPosition;
}
public void setCurrentPosition(int currentPosition) {
this.currentPosition = currentPosition;
}
// thread 에 의해 실행되는 코드...
// Bind되는 순간부터 run이 실행되면서 매 초마다 현재 Position를 설정한다.
public void run() {
// run을 빠져나가면 thread는 끝난다.
// 장시간 해야되는건 주로 loop를 만들어 놓는다.
while(flag) // 음원이 끝나면 나가라.
{
setCurrentPosition(player.getCurrentPosition());
try {
// sleep은 항상 try~cath와 같이 쓰여야 한다.
Thread.sleep(1000); // milisecond unit
} catch (Exception e) {
// TODO: handle exception
}
}
}
@Override
public IBinder onBind(Intent arg) {
// TODO Auto-generated method stub
player = MediaPlayer.create(this, R.raw.part1);
setDuration(player.getDuration());
player.start();
// MediaPlayer의 음원 플레이 시간을 얻어내서 service의 데이터를
// 업데이트 시키는 작업을 하는 thread
//(null: 특별히 group값이 필요없음.
// this: thread 돌릴 source, player는 이름
Thread t = new Thread(null, this, "player");
t.start(); // bind되는 순간 PlayService의 run()이 시작됨.
return new MyBinder(); // bind될 객체 리턴해야됨.
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
player.stop(); // service 멈추기
flag = false; // thread가 멈출 수 있게 flag값 설정
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
// player = MediaPlayer.create(this, R.raw.kara);
// player.start();
// SD카드의 여러 음악프로그램중 어떤걸 play할 것인지?
// 음악이 끝났다는 신호를 받을 수 있다. 그러면 다음곡 실행시키기.
}
// Activity bind시 Activity에 전달시킬 객체
public class MyBinder extends Binder {
MusicPlayer getService() {
return MusicPlayer.this;
}
}
}
현재 이렇게 코드 구성했구요 ㅠㅠ
자동으루 part2라는 mp3 파일이 재생되도록 하고 싶습니당.!
안드로이드 초보라 ㅠㅠ 자세한 답변부탁드릴게요 ..



