Service Example

 background daemon 방식의 서비스 예제이다. 웹 서핑과 음악 감상을 동시에 하는 앱을 만들고자 한다면 백그라운드 서비스를 통해 음악을 재생하면 된다.


 하기 예제는 서비스를 실행하면 핸들러에 의해서 1초 단위로 run() 함수가 실행된다. 마지막 run() 호출 후 1초 이내에 서비스를 종료하면 onDestroy()가 호출되어 mIsRunning이 false가 된다. 서비스를 manifest에 추가해주는 것도 잊지말자.


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.serviceexmaple.mystoryg.serviceexample">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<service
android:name=".MyService"
android:enabled="true"
android:exported="true"></service>
</application>

</manifest> 


activity_main.xml

 <?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:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.serviceexmaple.mystoryg.serviceexample.MainActivity">

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<Button
android:id="@+id/start_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Service" />

<Button
android:id="@+id/stop_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop Service" />
</LinearLayout>

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<TextView
android:id="@+id/view_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>


MainActivity.java

 package com.serviceexmaple.mystoryg.serviceexample;


import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
public static final String TAG = MainActivity.class.getSimpleName();

ComponentName mServiceName;
TextView mTextView;
// Intent mIntent;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mTextView = (TextView) findViewById(R.id.view_service);

Button start = (Button) findViewById(R.id.start_service);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSrv();
}
});

Button stop = (Button) findViewById(R.id.stop_service);
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopSrv();
}
});
}


private void startSrv() {
// mIntent = new Intent(this, MyService.class);
// mServiceName = startService(mIntent);
mServiceName = startService(new Intent(this, MyService.class));
Log.d(TAG, "mServiceName = " + mServiceName.toString());
mTextView.append("Service Start.\n");
}

private void stopSrv() {
if (null == mServiceName) {
mTextView.append("Service is not start.\n");
return;
}
Intent intent = new Intent();
intent.setComponent(mServiceName);
// if(stopService(mIntent)) {
if (stopService(intent)) {
mTextView.append("Service Stop.\n");
} else {
mTextView.append("Service is already stop.\n");
}
}
}


MyService.class

package com.serviceexmaple.mystoryg.serviceexample;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service implements Runnable {
public static final String TAG = MyService.class.getSimpleName();
private int mStartId;
private Handler mHandler;
private boolean mIsRunning;

public MyService() {
}

@Override
public void onCreate() {
Log.i(TAG, "onCreate()");
super.onCreate();

mIsRunning = false;
mHandler = new Handler();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "startId = " + startId);
mStartId = startId;
if (!mIsRunning) {
mHandler.postDelayed(this, 1000);
mIsRunning = true;
}
return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
Log.i(TAG, "onDestroy()");
mIsRunning = false;
super.onDestroy();
}

@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public void run() {
if (!mIsRunning) {
Log.i(TAG, "It run after call onDestroy()");
} else {
Log.i(TAG, "run()");
mHandler.postDelayed(this, 1000);
}
}

} 


실행 결과 log

12-17 17:24:34.700 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/ViewRootImpl: ViewRoot's Touch Event : ACTION_DOWN

12-17 17:24:34.789 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/ViewRootImpl: ViewRoot's Touch Event : ACTION_UP

12-17 17:24:34.794 11136-11136/com.serviceexmaple.mystoryg.serviceexample D/MainActivity: mServiceName = ComponentInfo{com.serviceexmaple.mystoryg.serviceexample/com.serviceexmaple.mystoryg.serviceexample.MyService}

12-17 17:24:34.795 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: onCreate()

12-17 17:24:34.807 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: startId = 1

12-17 17:24:35.810 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: run()

12-17 17:24:36.812 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: run()

12-17 17:24:37.814 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: run()

12-17 17:24:38.816 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: run()

12-17 17:24:39.819 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: run()

12-17 17:24:40.345 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/ViewRootImpl: ViewRoot's Touch Event : ACTION_DOWN

12-17 17:24:40.453 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/ViewRootImpl: ViewRoot's Touch Event : ACTION_UP

12-17 17:24:40.459 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: onDestroy()

12-17 17:24:40.820 11136-11136/com.serviceexmaple.mystoryg.serviceexample I/MyService: It run after call onDestroy() 


+ Recent posts