Read in another activity a variable that is updated in MainActivity

2

I have a function that runs every second. This function sends a request for information via socket to a device. This information is received in AsyncTask which does the calculations and updates some variables that are in MainActivity and are displayed on screen.

The problem is that I also need to display the contents of these variables in another activity . And that content has to keep pace with the changes that the variable receives every second.

I have to use the same variable that is in and MainActivity can not open a new socket because the first continues to receive the same data with another activity being displayed.

    
asked by anonymous 17.01.2017 / 15:11

1 answer

4

This is not the best approach.

If you have an operation (function) that is executed periodically and whose result you want to get in more than one place of your application, do not do it in an Activity. An Activity should not depend on another to perform its function.

Android provides the class Service for cases of this type. In a Service the operations are executed independently of the other components of the application, however, communication between them is possible.

In this case, a possible approach is to use a Bound Service linked) :

  

(...) A linked service allows components (such as activities) to be linked to the service, send requests, receive responses, and even establish interprocess communication (IPC). , Linked Services )

Example that uses a service to calculate the square root.

SqrCalculatorService.java

public class SqrCalculatorService extends Service {

    public static final int SQR_MSG = 0;
    public static final String SQR_RESULT = "sqrResult";

    public SqrCalculatorService() {
    }

    public static Intent makeIntent(Context context){
        return new Intent(context, SqrCalculatorService.class);
    }
    private final Messenger mCalculateMessenger = new Messenger(new CalculateHandler());

    private static class CalculateHandler extends Handler{

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case SQR_MSG:
                    double sqr = calculate(msg.arg1);
                    replyToCaller(msg.replyTo, sqr);
                    break;
                default:
                    super.handleMessage(msg);
            }
        }

        private static double calculate(int arg1) {
            return Math.sqrt(arg1);
        }

        private static void replyToCaller(Messenger msg, double sqr) {
            Message reply = Message.obtain(null, SQR_MSG);
            Bundle data = new Bundle();
            data.putDouble(SQR_RESULT, sqr);
            reply.setData(data);
            try {
                msg.send(reply);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mCalculateMessenger.getBinder();
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private Messenger mServiceMessenger = null;
    private TextView tvResultado;
    private EditText edValor;

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

        tvResultado = (TextView) findViewById(R.id.tvResultado);
        edValor = (EditText)findViewById(R.id.edValor);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if(mServiceMessenger == null){
            bindService(SqrCalculatorService.makeIntent(this),
                        srvConnection, Context.BIND_AUTO_CREATE);
        }
    }

    @Override
    protected void onStop() {
        unbindService(srvConnection);
        super.onStop();
    }

    private ServiceConnection srvConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {

            mServiceMessenger = new Messenger(iBinder);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

            mServiceMessenger = null;
        }
    };

    final Messenger mResultMessenger = new Messenger(new ResultHandler());

    private class ResultHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SqrCalculatorService.SQR_MSG:
                    Bundle data = msg.getData();
                    displaySQRResult(data);
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
        private void displaySQRResult(Bundle data) {
            double sqr = data.getDouble(SqrCalculatorService.SQR_RESULT);
            tvResultado.setText(Double.toString(sqr));
        }
    }

    public void onButtonClick(View v){
        int value = Integer.parseInt(edValor.getText().toString());
        Message msg = Message.obtain(null, SqrCalculatorService.SQR_MSG, value, 0);
        msg.replyTo = mResultMessenger;
        try {
            mServiceMessenger.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <TextView
        android:id="@+id/lbValor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Valor a calcular: "/>

    <EditText
        android:id="@+id/edValor"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@+id/lbValor"
        android:layout_toRightOf="@+id/lbValor"
        android:layout_alignBaseline="@+id/lbValor"/>
    <TextView
        android:id="@+id/lbResultado"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/lbValor"
        android:text="Resultado: "
        android:layout_marginTop="24dp"/>
    <TextView
        android:id="@+id/tvResultado"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@+id/lbResultado"
        android:layout_toRightOf="@+id/lbResultado"
        android:layout_alignBaseline="@+id/lbResultado"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/lbResultado"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="24dp"
        android:text="Calcular raiz quadrada"
        android:onClick="onButtonClick"/>
</RelativeLayout>

Service registration in AndroidManifest.xml

<application>
    ....
    ....
    <service
        android:name=".SqrCalculatorService"
        android:enabled="true"
        android:exported="true">
    </service>
</application>
    
17.01.2017 / 16:04