How to pass values from a Class to Activity - Android

前端 未结 6 1277
误落风尘
误落风尘 2021-02-09 08:23

I have a newbie question about Class/Task/Activity. I\'m coming from C so I don\'t know if it\'s a good approach to do what I need.

I\'ve created a class:



        
6条回答
  •  旧巷少年郎
    2021-02-09 08:36

    You can use Callback for this purpose.

    Define some interface like

    public interface MyCustomInterface(){
        public void sendData(String str);
    }
    

    Now let your Activity implement this interface.

    public class MyActivity implements MyCustomInterface {
    
    @Override
    public void sendData(String str){
    
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
      @Override
      public void run() {
        recived_message.setText(str);
      }
    });
    }
    }
    

    Now in UDPServer.java, write the following code

    public class UDPServer {
    
    private MyCustomInterface interface;
    
    UDPServer(MyCustomInterface interface){
     this.interface = interface; 
    }
    
    }
    

    Now whenever you have some data available lets say a string, you can send it like this

    interface.sendData(str);
    

提交回复
热议问题