narimetisaigopi

MainActivity.java handler UI communication

Feb 18th, 2020
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. package com.example.saigopinarimeti.helloworld;
  2.  
  3. import android.os.Handler;
  4. import android.os.Message;
  5. import android.support.v7.app.AppCompatActivity;
  6. import android.os.Bundle;
  7. import android.util.Log;
  8. import android.view.View;
  9. import android.widget.Button;
  10. import android.widget.TextView;
  11.  
  12. import java.text.SimpleDateFormat;
  13. import java.util.Date;
  14. import java.util.Locale;
  15.  
  16. public class MainActivity extends AppCompatActivity {
  17.  
  18.  
  19. TextView textView;
  20. Button fetchDate;
  21. @Override
  22. protected void onCreate(Bundle savedInstanceState) {
  23. super.onCreate(savedInstanceState);
  24. setContentView(R.layout.activity_main);
  25.  
  26. textView = findViewById(R.id.textview);
  27. fetchDate = findViewById(R.id.fetchdate);
  28.  
  29. fetchDate.setOnClickListener(new View.OnClickListener() {
  30. @Override
  31. public void onClick(View v) {
  32.  
  33. new Thread(runnable).start();
  34. }
  35. });
  36. }
  37.  
  38. Handler handler = new Handler(new Handler.Callback() {
  39. @Override
  40. public boolean handleMessage(Message msg) {
  41. Bundle bundle = msg.getData();
  42. String date = bundle.getString("data");
  43.  
  44. textView.setText("date is : "+date);
  45. return false;
  46. }
  47. });
  48.  
  49. Runnable runnable = new Runnable() {
  50. @Override
  51. public void run() {
  52. Message message = Message.obtain();
  53. Bundle bundle = new Bundle();
  54. bundle.putString("data",getCurrentTime());
  55. message.setData(bundle);
  56.  
  57. handler.sendMessage(message);
  58.  
  59. }
  60. };
  61.  
  62.  
  63.  
  64. private String getCurrentTime() {
  65. SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss MM/dd/yyyy", Locale.US);
  66. return dateFormat.format(new Date());
  67. }
  68.  
  69. }
Add Comment
Please, Sign In to add comment