(자마린추천교육)자마린.안드로이드 바운드 서비스 실습, Xamarin.Android Bound Service 실습
Xamarin.Android Bound Service 실습
n 환영 메시지를 Xamarin.Android의 바운드 서비스를 이용하여 출력하는 Xamarin.Android App을 만들어 보자. 이름을 입력하고 “HELLO 호출” 버튼을 클릭하면 서비스의 hello() 메소드를 호출하여 화면에 결과를 출력하는 예제이다.
n Xamarin.Android, Blank App으로 “BoundServiceDemo”라는 프로젝트 생성
n 전체 프로젝트 구조
n [Resources\layout\activity_main.axml] : 컨트롤 이름 주의!
n Resources\values\strings.xml
<resources>
<string name="app_name">BoundServiceDemo</string>
<string name="action_settings">Settings</string>
<string name="name_message">이름을 입력하세요.</string>
<string name="btnGetHello">hello 호출</string>
<string name="btnStop">서비스로부터 언바운드</string>
<string name="btnReStart">서비스에 다시 바운드</string>
<string name="service_not_connected">서비스 연결 실패!</string>
</resources>
|
n [IHello.cs]
namespace BoundServiceDemo
{
public interface IHello
{
string hello(string name);
}
}
|
n [Hello.cs]
namespace BoundServiceDemo
{
class Hello : IHello
{
public string hello(string name)
{
return $"안녕~ {name}";
}
}
}
|
n [HelloBinder.cs]
using Android.OS;
namespace BoundServiceDemo
{
// 바인더는 클라이언트가 서비스와 통신하는 데 사용하는 API를 제공한다.
// 바인더를 통해 안드로이드 서비스에 바인딩 하고 메소드를 호출할 수 있다.
// Android.OS.IBinder를 구현한 Binder를 상속받으면 된다.
// 클라이언트가 서비스에 바인딩되면 Android.OS.IBinder 객체를 통해 통신이 이루어지는데
// HelloBinder가 클라이언트와 서비스와 상호 작용할 수 있는 인터페이스를 담당한다.
public class HelloBinder : Binder, IHello
{
public HelloService Service { get; private set; }
public HelloBinder(HelloService service)
{
this.Service = service;
}
public string hello(string name)
{
return Service?.hello(name);
}
}
}
|
n [HelloServiceConnection.cs]
using Android.Util;
using Android.OS;
using Android.Content;
namespace BoundServiceDemo
{
// 서비스에 대한 연결이 변경된 경우(클라이언트가 서비스에 연결되거나 연결이 끊어진 경우)
// 클라이언트에게 알리기 위해 Android에서 호출하는 콜백 메서드를 제공한다.
// ServiceConnection은 클라이언트가 서비스와 직접 상호 작용하는 데 사용할 수있는
// 객체에 대한 참조를 제공하고 이 참조를 바인더(Binder)라고 한다.
public class HelloServiceConnection : Java.Lang.Object, IServiceConnection, IHello
{
static readonly string TAG = typeof(HelloServiceConnection).FullName;
MainActivity activity;
public bool IsConnected { get; private set; }
public HelloBinder Binder { get; private set; }
public HelloServiceConnection(MainActivity activity)
{
IsConnected = false;
Binder = null;
this.activity = activity;
}
public void OnServiceConnected(ComponentName name, IBinder service)
{
Binder = service as HelloBinder;
IsConnected = this.Binder != null;
string message = "OnServiceConnected :: ";
Log.Debug(TAG, $"OnServiceConnected {name.ClassName}");
if(IsConnected)
{
message = message + " bound to service " + name.ClassName;
this.activity.UpdateUiForBoundService();
}
else
{
message = message + " not bound to service " + name.ClassName;
this.activity.UpdateUiForUnboundService();
}
Log.Info(TAG, message);
activity.messageTextView.Text = message;
}
public void OnServiceDisconnected(ComponentName name)
{
Log.Debug(TAG, $"OnServiceDisConnected {name.ClassName}");
IsConnected = false;
Binder = null;
activity.UpdateUiForUnboundService();
}
public string hello(string name)
{
if (!IsConnected) return null;
return Binder?.hello(name);
}
}
}
|
n [HelloService.cs]
using Android.App;
using Android.Content;
using Android.OS;
using Android.Util;
namespace BoundServiceDemo
{
// 안드로이드 서비스 클래스 : 서비스할 작업을 기술
[Service(Name = "example.xamarin.HelloService")]
public class HelloService : Service, IHello
{
static readonly string TAG = typeof(HelloService).FullName;
IHello h;
public IBinder Binder { get; private set; }
public override void OnCreate()
{
base.OnCreate();
Log.Debug(TAG, "OnCreate...");
//서비스 메소드를 가진 객체 생성
h = new Hello();
}
//반드시 구현해야 되는 메소드
public override IBinder OnBind(Intent intent)
{
Log.Debug(TAG, " OnBind...");
this.Binder = new HelloBinder(this);
return this.Binder;
}
public override bool OnUnbind(Intent intent)
{
Log.Debug(TAG, " OnUnBind...");
return base.OnUnbind(intent);
}
public override void OnDestroy()
{
Log.Debug(TAG, " OnDestroy...");
Binder = null;
h = null;
base.OnDestroy();
}
//서비스 메소드
public string hello(string name)
{
return h?.hello(name);
}
}
}
|
n [MainActivity.cs]
using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Widget;
using Android.Content;
using System;
namespace BoundServiceDemo
{
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
Button btnGetHello;
Button btnStopService;
Button btnReStartService;
EditText nameEditText;
internal TextView messageTextView;
HelloServiceConnection serviceConnection;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
btnGetHello = FindViewById<Button>(Resource.Id.btnGetHello);
btnGetHello.Click += btnGetHello_Click;
btnStopService = FindViewById<Button>(Resource.Id.btnStop);
btnStopService.Click += btnStopService_Click;
btnReStartService = FindViewById<Button>(Resource.Id.btnReStart);
btnReStartService.Click += btnReStartService_Click;
messageTextView = FindViewById<TextView>(Resource.Id.message);
nameEditText = FindViewById<EditText>(Resource.Id.txtName);
}
protected override void OnStart()
{
base.OnStart();
if (serviceConnection == null) serviceConnection = new HelloServiceConnection(this);
DoBindService();
}
protected override void OnResume()
{
base.OnResume();
if (serviceConnection.IsConnected) UpdateUiForBoundService();
else UpdateUiForUnboundService();
}
protected override void OnPause()
{
btnGetHello.Click -= btnGetHello_Click;
btnReStartService.Click -= btnReStartService_Click;
btnStopService.Click -= btnStopService_Click;
base.OnPause();
}
protected override void OnStop()
{
DoUnBindService();
base.OnStop();
}
internal void UpdateUiForBoundService()
{
btnGetHello.Enabled = true;
btnReStartService.Enabled = false;
btnStopService.Enabled = true;
}
internal void UpdateUiForUnboundService()
{
btnGetHello.Enabled = false;
btnReStartService.Enabled = true;
btnStopService.Enabled = false;
}
//GetHello 버튼 클릭
void btnGetHello_Click(object sender, EventArgs e)
{
if (serviceConnection.IsConnected)
messageTextView.Text = serviceConnection.Binder.Service.hello(nameEditText.Text);
else
messageTextView.SetText(Resource.String.service_not_connected);
}
//StopService 버튼 클릭
void btnStopService_Click(object sender, EventArgs e)
{
DoUnBindService();
UpdateUiForUnboundService();
}
//ReStartService 버튼 클릭
void btnReStartService_Click(object sender, EventArgs e)
{
DoBindService();
UpdateUiForBoundService();
}
void DoUnBindService()
{
UnbindService(serviceConnection);
btnReStartService.Enabled = true;
messageTextView.Text = "";
}
void DoBindService()
{
Intent intent = new Intent(this, typeof(HelloService));
BindService(intent, serviceConnection, Bind.AutoCreate);
messageTextView.Text = "";
}
}
}
|
n 실행화면
댓글 없음:
댓글 쓰기