How to calculate latency when using Firebase

Viewed 627

I have just started learning Android programming and I am using online resources to create a Chat application using Firebase. I have two users Alice and Bob and I would like to calculate the following : 1. when Alice sends a message to Bob, the time it takes for Alice's message to get updated to Firebase Database 2. end-to-end delay which is the total time between Alice sending her message and Bob receiving the message.

When uploading a message, I am uploading the system current time. I am unable to figure out how to calculate the end to end latency. Meaning, at which part of the code should I measure the stop time and take a difference between stop time and the time when the message was uploaded ? I am attaching my code below for your reference :

public class MainActivity extends AppCompatActivity {
    int SIGN_IN_REQUEST_CODE = 10;
    boolean right_side = true;
    int layout_resource = 0;
    private FirebaseListAdapter<ChatMessage> adapter;
    DatabaseReference db = FirebaseDatabase.getInstance().getReference();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView listofmessages = (ListView) findViewById(R.id.list_of_messages);
        adapter=new messageadapter(this,ChatMessage.class,R.layout.leftchat,FirebaseDatabase.getInstance().getReference());

        if (FirebaseAuth.getInstance().getCurrentUser() == null) {
            //sign in / sign up
            startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(), SIGN_IN_REQUEST_CODE);
        } else {//user is signed in already

            Toast.makeText(this, "Welcome" + FirebaseAuth.getInstance().getCurrentUser().getDisplayName(), Toast.LENGTH_LONG).show();
            displaychatmessages();
        }

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                EditText input_text = (EditText) findViewById(R.id.input);
                //        Toast.makeText(MainActivity.this,input_text.getText().toString(),Toast.LENGTH_LONG).show();
                //Read input field and upload to DB
                Log.d("where", "read the msg to push to db");

                db.push().setValue(new ChatMessage(input_text.getText().toString(),FirebaseAuth.getInstance().getCurrentUser().getDisplayName()));//FirebaseAuth.getInstance().getCurrentUser().getDisplayName()));
                Log.d("where", "pushed data to db");
                //  Toast.makeText(MainActivity.this,"message entered",Toast.LENGTH_LONG).show();;
                //clear input for next input
                input_text.setText("");
            }
        });
    }

    public void displaychatmessages() {
        ListView listofmessages = (ListView) findViewById(R.id.list_of_messages);
        adapter=new messageadapter(this,ChatMessage.class,R.layout.leftchat,FirebaseDatabase.getInstance().getReference());
        listofmessages.setAdapter(adapter);
    }

    @Override
    protected void onStart() {
        super.onStart();
        adapter.startListening();
    }

    @Override
    protected void onStop() {
        super.onStop();
        adapter.stopListening();
    }

    @Override
    protected void onActivityResult ( int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == SIGN_IN_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                Toast.makeText(this, "Successfully signed in.Welcome !", Toast.LENGTH_LONG).show();
                //display chat msg
                displaychatmessages();
            } else {
                Toast.makeText(this, "We couldnt sign you in. Good bye ! ", Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }
}

Message adapter class :

public class messageadapter extends FirebaseListAdapter<ChatMessage> {
    HashMap<String,String> timemap=new HashMap<String,String>();
    private MainActivity activity;
    long local_start, local_stop;

    public messageadapter(MainActivity activity, Class<ChatMessage>
            modelClass, int modelLayout,DatabaseReference ref) {
        // FirebaseListOptions<ChatMessage> options=
        super(new FirebaseListOptions.Builder<ChatMessage>()
            .setQuery(ref, modelClass)
            .setLayout(modelLayout)
            .build());
        //super(activity,modelClass,modelLayout,ref);
        this.activity=activity;
        local_start=System.currentTimeMillis();
    }

    @Override
    protected void populateView(View v, ChatMessage model, int position) {
        TextView messageText=(TextView)v.findViewById(R.id.message_text);
        TextView timedifference=(TextView)v.findViewById(R.id.time_difference);
        TextView messageTime=(TextView)v.findViewById(R.id.message_time);

        //set Text
        messageText.setText(model.getMessageText());

        android.text.format.DateFormat df=new android.text.format.DateFormat();
        messageTime.setText(df.format("dd-MM-yyyy (HH:mm:ss)",model.getMessageTime()));
        long milli,milli2,diff;
        if(timemap.containsKey(model.getMessageId())) {
            timedifference.setText(timemap.get(model.getMessageId()));

        } else { //local_stop=System.currentTimeMillis();
            milli=System.currentTimeMillis();
            milli2=model.getMillitime();
            diff=local_stop-local_start;
            timemap.put(model.getMessageId(),String.valueOf(local_start-milli2));
            timedifference.setText(String.valueOf(milli-milli2));
        }
    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        ChatMessage chatMessage=getItem(position);
        if(chatMessage.getMessageUser().equals(FirebaseAuth.getInstance().getCurrentUser().getDisplayName())) {
            view=activity.getLayoutInflater().inflate(R.layout.leftchat,viewGroup,false);
        } else {
            view=activity.getLayoutInflater().inflate(R.layout.rightchat,viewGroup,false);
        }

        populateView(view,chatMessage,position);
        return view;
    }

    @Override
    public int getViewTypeCount() {
        // return the total number of view types. this value should never change
        // at runtime
        return 2;
    }

    @Override
    public int getItemViewType(int position) {
        // return a value between 0 and (getViewTypeCount - 1)
        return position % 2;
    }
}

At the moment, the performance monitoring dashboard is not showing up any data and so I am trying to send multiple message to reach the required number of messages for Firebase to sample and show the data.

Any help to calculate the 2 time measurements would be greatly appreciated.. thanks !

0 Answers
Related