Advertisement
Guest User

Untitled

a guest
Apr 1st, 2017
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.17 KB | None | 0 0
  1. package com.hfad.drogomierz;
  2.  
  3. import android.app.Activity;
  4. import android.content.ComponentName;
  5. import android.content.Context;
  6. import android.content.Intent;
  7. import android.content.ServiceConnection;
  8. import android.os.Bundle;
  9. import android.os.Handler;
  10. import android.os.IBinder;
  11. import android.widget.TextView;
  12.  
  13. public class MainActivity extends Activity {
  14.  
  15.     private OdometerService odometer;
  16.     private boolean bound = false;
  17.  
  18.     private ServiceConnection connection = new ServiceConnection() {
  19.         @Override
  20.         public void onServiceConnected(ComponentName componentName, IBinder binder) {
  21.             OdometerService.OdometerBinder odometerBinder =
  22.                     (OdometerService.OdometerBinder) binder;
  23.             odometer = odometerBinder.getOdometer();
  24.             bound = true;
  25.         }
  26.         @Override
  27.         public void onServiceDisconnected(ComponentName componentName) {
  28.             bound = false;
  29.         }
  30.     };
  31.  
  32.     @Override
  33.     protected void onCreate(Bundle savedInstanceState) {
  34.         super.onCreate(savedInstanceState);
  35.         setContentView(R.layout.activity_main);
  36.         watchMileage();
  37.     }
  38.  
  39.     @Override
  40.     protected void onStart() {
  41.         super.onStart();
  42.         Intent intent = new Intent(this, OdometerService.class);
  43.         bindService(intent, connection, Context.BIND_AUTO_CREATE);
  44.     }
  45.  
  46.     @Override
  47.     protected void onStop() {
  48.         super.onStop();
  49.         if (bound) {
  50.             unbindService(connection);
  51.             bound = false;
  52.         }
  53.     }
  54.  
  55.     private void watchMileage() {
  56.         final TextView distanceView = (TextView)findViewById(R.id.distance);
  57.         final Handler handler = new Handler();
  58.         handler.post(new Runnable() {
  59.             @Override
  60.             public void run() {
  61.                 double distance = 0.0;
  62.                 if (odometer != null) {
  63.                     distance = odometer.getDistance();
  64.                 }
  65.                 String distanceStr = String.format("%1$,.2f kilometra", distance);
  66.                 distanceView.setText(distanceStr);
  67.                 handler.postDelayed(this, 1000);
  68.             }
  69.         });
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement