안드로이드
안드로이드 스튜디오 -서비스
이즈흐
2022. 5. 26. 14:48
오늘은 서비스에 대해 알아보겠습니다.
서비스의 생명주기
화면이 종료되어도 계속되는 음악 서비스 만들기
MainActivity
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Intent intent;
Button btnStart,btnStop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("서비스 테스트 예제");
intent = new Intent(this , MusicService.class);
btnStart=(Button) findViewById(R.id.button);
btnStop=(Button) findViewById(R.id.button2);
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startService(intent);
android.util.Log.e("서비스 텟흐트","startService()");
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stopService(intent);
android.util.Log.e("서비스 텟흐트","stopService()");
}
});
}
}
MusicService.java
package com.example.myapplication;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
public class MusicService extends Service {
MediaPlayer mp;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
android.util.Log.e("서비스 테스트","onCreate()");
super.onCreate();
}
@Override
public void onDestroy() {
android.util.Log.e("종료 테스트","onDestory()");
mp.stop();
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
android.util.Log.e("시작 테스트","onStartCommand()");
mp=MediaPlayer.create(this,R.raw.song1);
mp.setLooping(true);
mp.start();
return super.onStartCommand(intent, flags, startId);
}
}
activitymain.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="start" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="stop" />
</LinearLayout>
간단한 설명
728x90
반응형
LIST