음악
문제
activity_main.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"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="20dp"
android:text="음악 서비스 테스트" android:textSize="20sp" />
<Button
android:id="@+id/start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="시작" >
</Button>
<Button
android:id="@+id/stop"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="중지" >
</Button>
</LinearLayout>
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MusicServiceTest";
Button start, stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start=(Button)findViewById(R.id.start);
stop=(Button)findViewById(R.id.stop);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "onClick() start ");
startService(new Intent(getApplicationContext(),MusicService.class));
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "onClick() stop");
stopService(new Intent(getApplicationContext(), MusicService.class));
}
});
}
}
MusicService.java
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MusicService extends Service {
private static final String TAG = "MusicService";
MediaPlayer player;
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
Log.d(TAG, "onCreate()");
player = MediaPlayer.create(this, R.raw.old_pop);
player.setLooping(false); // Set looping
}
public void onDestroy() {
Toast.makeText(this, "Music Service가 중지되었습니다.", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy()");
player.stop();
}
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Music Service가 시작되었습니다.", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart()");
player.start();
return super.onStartCommand(intent, flags, startId);
}
}