티스토리 뷰
안드로이드 배경음악 돌리기 (서비스 사용)
배경음악을 넣고싶은데 엑티비티간 이동하면서 불편함이 많아 서비스로 돌려보았다.
1. 서비스 클래스 하나를 만든다 ( MusicService .java )
public class MusicService extends Service {
public MediaPlayer mp;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onStart(Intent intent, int startId) {
Log.i("Example", "Service onStart()");
super.onStart(intent, startId);
mp = MediaPlayer.create(this, R.raw.자신의음악파일명); (음악파일명은 ogg가 좋다고한다 (필자의 블로그 왼쪽에 pc탭을 눌르면 mp3 등등 파일변환하는방법을 포스팅해두었다)
mp.setLooping(true); // 반복 재생 설정 (true와 false로 조정 가능)
//리스너등록
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { public void onPrepared(MediaPlayer mp) {
//재생 사운드 출력을 시작할 준비가되었을 때
mp.start();
}
});
}
public void onDestroy() {
Log.i("Example", "Service onDestroy()");
super.onDestroy();
mp.pause();
mp.reset();
//해지리스너등록
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
public void onCompletion(MediaPlayer mp)
{
mp.release();
}
});
}
}
-----------------------
2, 매니패스트의 액티비티 안에 아래의 서비스 내용을 추가해준다
<service android:name=".MusicService" >
<intent-filter>
<action android:name="액션이름으로 패키지명을넣음" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
--------------
3. 이제 배경음을 컨트롤하고싶은 액티비티에서
음악을 재생하고싶다면
startService(new Intent("액션이름으로 패키지명을넣음""));
음악을 멈추고싶다면
stopService(new Intent("액션이름으로 패키지명을넣음""));
'It' 카테고리의 다른 글
백분율, 백분률, 올바르다, 옳바르다 (0) | 2022.11.20 |
---|---|
성 장애 치료 (0) | 2022.11.19 |
소셜 커머스의 시장에서 B2B 서비스 모델 / 소셜 커머스가 주목받는 이유 / 그루폰 (0) | 2022.10.06 |
인터넷 소비자 비용(가격관련 기본사항) (0) | 2022.09.02 |
디지털 제품의 대표적인 예 (0) | 2022.09.02 |