티스토리 뷰

Android/Service

Service (2) - started service

parkho79 2018. 8. 28. 15:25
728x90



startService 구현

  

1. Service 구현

public class PhService extends Service
{
MediaPlayer mMediaPlayer;
@Override
public void onCreate() {
super.onCreate();
mMediaPlayer = MediaPlayer.create(this, R.raw.sample);
mMediaPlayer.setLooping(false);
}
@Override
public int onStartCommand(Intent a_intent, int a_flags, int a_startId) {
final int result = super.onStartCommand(a_intent, a_flags, a_startId);
mMediaPlayer.start();
return result;
}
@Override
public void onDestroy() {
super.onDestroy();
mMediaPlayer.stop();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
view raw PhService.java hosted with ❤ by GitHub



2. Manifest 등록

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.parkho.servicesample">
<application
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity android:name=".PhMainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".PhService" />
</application>
</manifest>



3. Layout 생성

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn_start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="24.00dp"
android:text="@string/start_service" />
<Button
android:id="@+id/btn_stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="24.00dp"
android:text="@string/stop_service" />
</LinearLayout>
view raw layout.xml hosted with ❤ by GitHub



4. MainActivity

public class PhMainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 서비스 시작
Button btnStart = findViewById(R.id.btn_start);
btnStart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), PhService.class);
startService(intent);
}
});
// 서비스 종료
Button btnStop = findViewById(R.id.btn_stop);
btnStop.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), PhService.class);
stopService(intent);
}
});
}
}



위 예제는 하단 link 에서 확인할 수 있다.

https://github.com/parkho79/ServiceSample



bindSetvice 구현은 3편에서 다룬다.



728x90

'Android > Service' 카테고리의 다른 글

[Android O] Not allowed to start service Intent  (2) 2018.10.19
Service (4) - bindService  (0) 2018.10.16
Service (3) - bound service  (0) 2018.10.10
Service (1)  (1) 2018.08.21
댓글