IT/Android

android - 음악플레이어, 서비스 (service), onStartCommand

노마드오브 2018. 11. 11. 00:30
package com.example.it.myapplication14_1;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

Intent intent;
Button btnStart, btnStop;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("서비스 테스트 예제");

intent = new Intent(this, MusicService.class);
btnStart = (Button) findViewById(R.id.btnStart);
btnStop = (Button) findViewById(R.id.btnStop);

btnStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startService(intent);
android.util.Log.i("서비스 테스트", "startService()");
}
});

btnStop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
stopService(intent);
android.util.Log.i("서비스 테스트", "stopService()");
}
});
}
}


package com.example.it.myapplication14_1;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;

public class MusicService extends Service {

MediaPlayer mp;

@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onCreate () {
android.util.Log.i("서비스 테스트","onCreate()");
super.onCreate();
}

@Override
public void onDestroy() {
android.util.Log.i("서비스 테스트","onDestroy()");
mp.stop();
super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
android.util.Log.i("서비스 테스트","onStartCommand()");
mp = MediaPlayer.create(this, R.raw.song1);
mp.setLooping(true);
mp.start();
return super.onStartCommand(intent, flags, startId);
}
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<Button
android:id="@+id/btnStart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="음악서비스 시작" />

<Button
android:id="@+id/btnStop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="음악서비스 중지" />

</LinearLayout>