Skip to content Skip to sidebar Skip to footer

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 under Binder = service as MyServiceBinder;:

    myService=Binder.Service;
    myService.SetActivity(mainActivity);
    
  • In your MyService class add this (so you can get MainActivity instance in your service):

    MainActivity mainActivity;
    public void SetActivity(MainActivity activity) {
    this.mainActivity = activity;
    }
    

    and add mainActivity.UpdateUI(); in your Step(long timeNs) method, so you can update your UI.

  • In your MainActivity replace private void UpdateUI() with public void UpdateUI().


Interface

  • Add IUpdate interface

    public interface IUpdate
    {
        void Update();
    }
    
  • In your MyService add this:

    IUpdate update;
    public void SetIUpdate(IUpdate update) {
        this.update = update;
    }
    

    and add this.update.Update(); in your Step(long timeNs) method.

  • Implement the IUpdate interface in your MyServiceConnection class, so it will like this:

    public class MyServiceConnection : Java.Lang.Object, IServiceConnection,IUpdate
    {
         MainActivity mainAtivity;
    
        public MyServiceConnection(MainActivity activity)
    {
        IsConnected = false;
        Binder = null;
        mainActivity = activity;
    }
    
    public bool IsConnected { get; private set; }
    public MyServiceBinder Binder { get; private set; }
    public MyService myService;
    
    public void OnServiceConnected(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;
    }
    
    public void OnServiceDisconnected(ComponentName name)
    {
        IsConnected = false;
        Binder = null;
    }
    
    public void Update()
    {
        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"