728x90
반응형
<?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="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnStart"
android:text="서비스 시작"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnStop"
android:text="서비스 중지"/>
</LinearLayout>
package kr.co.servicelifecycle;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
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);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.drawable.ic_launcher);
setTitle("서비스 생명주기 확인");
intent = new Intent(this, MusicService.class);
btnStart = findViewById(R.id.btnStart);
btnStop = findViewById(R.id.btnStop);
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startService(intent);
Log.i("서비스 테스트", "startService()");
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stopService(intent);
Log.i("서비스 테스트", "stopService()");
}
});
}
}
package kr.co.servicelifecycle;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
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() {
Log.i("서비스 테스트", "onCreate()");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("서비스 테스트", "onStartCommand()");
mp = MediaPlayer.create(this, R.raw.vlv);
mp.setLooping(true);
mp.start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.i("서비스 테스트", "onDestroy()");
mp.stop();
super.onDestroy();
}
}
728x90
반응형
'App > Android Java' 카테고리의 다른 글
Android_Java(36) - UsingMediaStore (0) | 2022.02.23 |
---|---|
Android_Java(35) - BatteryStatus (0) | 2022.02.23 |
Android_Java(33) - MusicService (0) | 2022.02.23 |
Android_Java(32) - ImageDownload (0) | 2022.02.15 |
Android_Java(31) - AsyncTask (0) | 2022.02.15 |
댓글