코드네임 :
📱 모바일프로그래밍 - 서비스 📱 본문
[서비스]
: 사용자의 인터페이스 없이 백그라운드에서 실행되는 컴포넌트
- 배경음악, 앱의 업데이트를 주기적으로 검사 등

[서비스의 생명주기]

**서비스 추가 방법**

화면이 종료되어도 계속되는 음악서비스
(이 앱에서 나가도 계속된다고)
MainActivity.java
Intent intent;
~~~ OnCreate ~~~
        //intent 변수안에 intent 객체 넣어주기
        //지금 여기서(현재액티비티) 일어난 일들을 MusicService로 보낼거임
        intent = new Intent(this, MusicService.class);
        binding.btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //intent에 해당하는 서비스를 시작해라 (즉 MusicService라는 이름의 서비스 시작)
                //// MusicService 클래스의 onStartCommand() 메서드가 호출됨
                startService(intent);
                //서비스가 시작된 시점에 로그남기기
                Log.i("Service Test", "startService");
            }
        });
        binding.btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //intent에 해당하는 서비스 멈춤
                //// 서비스가 실행 중이면, MusicService 클래스의 onDestroy() 메서드가 호출됨
                stopService(intent);
                Log.i("Service Test", "stopService");
            }
        });
MusicService.java
public class MusicService extends Service {
    //음악 플레이 객체 추가
    MediaPlayer mp;
    public MusicService() {
    }
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
    //메소드 추가하자
    @Override
    public void onCreate() {
        super.onCreate();
        //로그남기기
        Log.i("Service Test", "onCreate");
        //mp에 mediaplayre 객체 만들기
        //this에 Resource/raw/song1연결
        mp = MediaPlayer.create(this, R.raw.song3);
        //반복하는것은 사실이랍니다(true)
        mp.setLooping(true);
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("Service Test", "onStart");
        //음악시작하기
        mp.start();
        return super.onStartCommand(intent, flags, startId);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("Service Test", "onDestroy");
        //음악 멈추기
        mp.stop();
    }
}
'👾Android > Android_JAVA' 카테고리의 다른 글
| 📱 모바일프로그래밍 - 콘텐트프로바이더 📱 (0) | 2024.12.08 | 
|---|---|
| 📱 모바일프로그래밍 - 브로드캐스트 리시버 📱 (1) | 2024.12.07 | 
| 📱 모바일프로그래밍 - 과제 2📱 (1) | 2024.12.02 | 
| 📱 모바일프로그래밍 - 뷰바인딩 📱 (0) | 2024.11.28 | 
| 📱 모바일프로그래밍 - 어댑터뷰 : 뷰페이저 (예제 포함 - 이건 시험기간에 적어봐라.,.)📱 (0) | 2024.11.21 | 
 
                   
                   
                  