How To Update Activity Every Time The Data Had Been Changed In Service
I'm writing my first Android app and it's supposed to count steps (via accelerometer, source code from http://www.gadgetsaint.com/android/create-pedometer-step-counter-android/) So
Solution 1:
There are three ways to complete it.
- Broadcast
- Interface
- BindService
BindService
In your
MyServiceConnection
add this:public MyService myService;
and in your
OnServiceConnected
method add this underBinder = service as MyServiceBinder;
:myService=Binder.Service; myService.SetActivity(mainActivity);
In your
MyService
class add this (so you can getMainActivity
instance in your service):MainActivity mainActivity; publicvoidSetActivity(MainActivity activity){ this.mainActivity = activity; }
and add
mainActivity.UpdateUI();
in yourStep(long timeNs)
method, so you can update your UI.In your
MainActivity
replaceprivate void UpdateUI()
withpublic void UpdateUI()
.
Interface
Add
IUpdate
interfacepublicinterfaceIUpdate { voidUpdate(); }
In your
MyService
add this:IUpdate update; publicvoidSetIUpdate(IUpdate update){ this.update = update; }
and add
this.update.Update();
in yourStep(long timeNs)
method.Implement the
IUpdate
interface in yourMyServiceConnection
class, so it will like this:publicclassMyServiceConnection : Java.Lang.Object, IServiceConnection,IUpdate { MainActivity mainAtivity; publicMyServiceConnection(MainActivity activity) { IsConnected = false; Binder = null; mainActivity = activity; } publicbool IsConnected { get; privateset; } public MyServiceBinder Binder { get; privateset; } public MyService myService; publicvoidOnServiceConnected(ComponentName name, IBinder service) { Binder = service as MyServiceBinder; myService=Binder.Service; myService.SetIUpdate(this); //myService.SetActivity(mainActivity); IsConnected = this.Binder != null; string message = "onSecondServiceConnected - "; if (IsConnected) { message = message + " bound to service " + name.ClassName; } else { message = message + " not bound to service " + name.ClassName; } mainActivity.textSpeed.Text = message; } publicvoidOnServiceDisconnected(ComponentName name) { IsConnected = false; Binder = null; } publicvoidUpdate() { mainActivity.UpdateUI(); } }
Broadcast
This is what you have already known.
Post a Comment for "How To Update Activity Every Time The Data Had Been Changed In Service"