Guest User

Untitled

a guest
Mar 22nd, 2012
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 13.35 KB | None | 0 0
  1. public class QuickBloxActivity extends Activity implements
  2.         ActionResultDelegate {
  3.     /** Called when the activity is first created. */
  4.  
  5.     ViewPager v;
  6.     private MapView mapView;
  7.     List<Address> addressList;
  8.     MapController mapController;
  9.     private Drawable marker;
  10.     private WhereAmI ownOverlay;
  11.     private MapPopUp mapPopUp;
  12.     private TimerTask task;
  13.     private Timer timer;
  14.     private ProgressBar mapUpdateProgress;
  15.     private Thread processLocationsDataThread;
  16.     ViewPagerAdapter updateview;
  17.  
  18.     @Override
  19.     public void onCreate(Bundle savedInstanceState) {
  20.         super.onCreate(savedInstanceState);
  21.         setContentView(R.layout.viewpageractivity);
  22.  
  23.         // Set the pager with an adapter
  24.         ViewPager view = (ViewPager) findViewById(R.id.viewpager);
  25.  
  26.         // Bind the title indicator to the adapter
  27.         TitlePageIndicator titleIndicator = (TitlePageIndicator) findViewById(R.id.indicator);
  28.         ViewPagerAdapter adapter = new ViewPagerAdapter(QuickBloxActivity.this);
  29.         view.setAdapter(adapter);
  30.         //updateview=ViewPagerAdapter.getInstance();
  31.         view.setCurrentItem(1);
  32.         titleIndicator.setViewPager(view);
  33.  
  34.        
  35.         /////Map implementing
  36.  
  37.         // Init Map
  38.         initMapView();
  39.  
  40.         // init progress wheel
  41.         mapUpdateProgress = (ProgressBar) findViewById(R.id.mapUpdate_progressBar);
  42.  
  43.         // init map popup
  44.         mapPopUp = new MapPopUp(this, (ViewGroup) mapView.getParent());
  45.  
  46.         // get a latitude and a longitude of the current user
  47.         LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  48.         LocationListener locListener = new LocationListener() {
  49.  
  50.             @Override
  51.             public void onStatusChanged(String provider, int status,
  52.                     Bundle extras) {
  53.                 Log.i("onStatusChanged", provider + String.valueOf(status));
  54.             }
  55.  
  56.             @Override
  57.             public void onProviderEnabled(String provider) {
  58.                 Log.i("onProviderEnabled", provider);
  59.             }
  60.  
  61.             @Override
  62.             public void onProviderDisabled(String provider) {
  63.             }
  64.  
  65.             // if a location of the device will be changed,
  66.             // send the data on the server
  67.             @Override
  68.             public void onLocationChanged(Location location) {
  69.                 if (location != null
  70.                         && Store.getInstance().getCurrentUser() != null) {
  71.  
  72.                     Log.i("onLocationChanged", "onLocationChanged");
  73.  
  74.                     // save current location
  75.                     Store.getInstance().setCurrentLocation(location);
  76.  
  77.                     String lat = Double.toString(location.getLatitude());
  78.                     String lng = Double.toString(location.getLongitude());
  79.  
  80.                     // create entity for current user
  81.                     List<NameValuePair> formparamsGeoUser = new ArrayList<NameValuePair>();
  82.                     formparamsGeoUser.add(new BasicNameValuePair(
  83.                             "geo_data[latitude]", lat));
  84.                     formparamsGeoUser.add(new BasicNameValuePair(
  85.                             "geo_data[longitude]", lng));
  86.                     if (Store.getInstance().getCurrentStatus() != null) {
  87.                         formparamsGeoUser.add(new BasicNameValuePair(
  88.                                 "geo_data[status]", Store.getInstance()
  89.                                         .getCurrentStatus()));
  90.                     }
  91.                     formparamsGeoUser.add(new BasicNameValuePair("token", Store
  92.                             .getInstance().getAuthToken()));
  93.  
  94.                     UrlEncodedFormEntity postEntityGeoDataUser = null;
  95.                     try {
  96.                         postEntityGeoDataUser = new UrlEncodedFormEntity(
  97.                                 formparamsGeoUser, "UTF-8");
  98.                     } catch (UnsupportedEncodingException e1) {
  99.                         e1.printStackTrace();
  100.                     }
  101.  
  102.                     //
  103.                     // make query
  104.                     Query.performQueryAsync(QueryMethod.Post,
  105.                             QBQueries.CREATE_GEODATA_QUERY,
  106.                             postEntityGeoDataUser, null, QuickBloxActivity.this,
  107.                             QBQueries.QBQueryType.QBQueryTypeCreateGeodata);
  108.  
  109.                     Log.i("SEND OWN LOCATION ON THE SERVER", "ON");
  110.                 } else {
  111.                     Log.i("SEND OWN LOCATION ON THE SERVER", "OFF");
  112.                 }
  113.  
  114.             }
  115.         };
  116.  
  117.         List<String> providers = locManager.getProviders(true);
  118.         for (String provider : providers) {
  119.  
  120.             // registration of the LocationListener.
  121.             locManager.requestLocationUpdates(provider,
  122.                     Consts.MAP_CHECK_OWN_POSITION_PERIOD, 10, locListener);
  123.  
  124.             Store.getInstance().setCurrentLocation(
  125.                     locManager.getLastKnownLocation(provider));
  126.         }
  127.  
  128.         marker = getResources().getDrawable(R.drawable.map_marker_other);
  129.         marker.setBounds(0, 0, marker.getIntrinsicWidth(),
  130.                 marker.getIntrinsicHeight());
  131.     }
  132.  
  133.     @Override
  134.     protected void onPause() {
  135.         super.onPause();
  136.         timer.cancel();
  137.         task.cancel();
  138.         timer = null;
  139.         task = null;
  140.     }
  141.  
  142.     @Override
  143.     protected void onResume() {
  144.         super.onResume();
  145.  
  146.         startTimer();
  147.  
  148.         // read a value which is established from CheckBoxPreference
  149.         if (Store.getInstance().getCurrentUser() != null) {
  150.             initMyLocation();
  151.         } else if (ownOverlay != null) {
  152.             mapView.getOverlays().remove(ownOverlay);
  153.             ownOverlay = null;
  154.         }
  155.     }
  156.  
  157.     @Override
  158.     protected void onStart() {
  159.         super.onStart();
  160.         FlurryAgent.onStartSession(this, Consts.FLURRY_API_KEY);
  161.         FlurryAgent.logEvent("run MapViewActivity");
  162.  
  163.     }
  164.  
  165.     @Override
  166.     protected void onStop() {
  167.         super.onStop();
  168.         FlurryAgent.onEndSession(this);
  169.     }
  170.  
  171.     private void initMapView() {
  172.         mapView = (MapView) findViewById(R.id.mapview);
  173.         mapController = mapView.getController();
  174.         mapView.setSatellite(true);
  175.         mapView.setBuiltInZoomControls(true);
  176.     }
  177.  
  178.     private void initMyLocation() {
  179.         if (ownOverlay != null) {
  180.             return;
  181.         }
  182.  
  183.         ownOverlay = new WhereAmI(this, mapView);
  184.         // to begin follow for the updates of the location
  185.         ownOverlay.enableMyLocation();
  186.         ownOverlay.enableCompass(); // it's no works in the emulator
  187.         ownOverlay.runOnFirstFix(new Runnable() {
  188.  
  189.             @Override
  190.             public void run() {
  191.                 // Show current location and change a zoom
  192.                 mapController.setZoom(2);
  193.  
  194.                 if (ownOverlay.getMyLocation() != null) {
  195.                     mapController.animateTo(ownOverlay.getMyLocation());
  196.                 }
  197.             }
  198.         });
  199.         mapView.getOverlays().add(ownOverlay);
  200.     }
  201.  
  202. //  @Override
  203. //  protected boolean isLocationDisplayed() {
  204. //      return true;
  205. //  }
  206. //
  207. //  @Override
  208. //  protected boolean isRouteDisplayed() {
  209. //      return false;
  210. //  }
  211.  
  212.     public void startTimer() {
  213.         timer = new Timer();
  214.         task = new TimerTask() {
  215.  
  216.             @Override
  217.             public void run() {
  218.                 updateMap();
  219.             }
  220.         };
  221.  
  222.         // each 1 min to do
  223.         timer.schedule(task, 0, Consts.MAP_UPDATE_PERIOD);
  224.     }
  225.  
  226.     // update map query
  227.     private void updateMap() {
  228.         if (mapUpdateProgress.getVisibility() == View.VISIBLE) {
  229.             return;
  230.         }
  231.  
  232.         // show progress wheel
  233.         QuickBloxActivity.this.runOnUiThread(new Runnable() {
  234.  
  235.             @Override
  236.             public void run() {
  237.                 mapUpdateProgress.setVisibility(View.VISIBLE);
  238.             }
  239.         });
  240.  
  241.         String query = QBQueries.GET_ALL_LOCATIONS_QUERY + "&token="
  242.                 + Store.getInstance().getAuthToken();
  243.  
  244.         // make query
  245.         Query.performQueryAsync(QueryMethod.Get, query, null, null, this,
  246.                 QBQueries.QBQueryType.QBQueryTypeGetAllLocations);
  247.     }
  248.  
  249.     @Override
  250.     public void completedWithResult(QBQueryType queryType, RestResponse response) {
  251.         // no internet connection
  252.         if (response == null) {
  253.             mapUpdateProgress.setVisibility(View.GONE);
  254.             AlertManager.showServerError(this,
  255.                     "Please check your internet connection");
  256.             return;
  257.         }
  258.  
  259.         switch (queryType) {
  260.         // CREATED
  261.         case QBQueryTypeCreateGeodata:
  262.             if (response.getResponseStatus() == ResponseHttpStatus.ResponseHttpStatus201) {
  263.                 Log.i("completedWithResult",
  264.                         "The current location has been added to the database");
  265.             } else {
  266.                 Log.e("completedWithResult",
  267.                         "The current location HAS NOT BEEN ADDED to the database!");
  268.             }
  269.  
  270.             break;
  271.  
  272.         // Ok
  273.         case QBQueryTypeGetAllLocations:
  274.             if (response.getResponseStatus() == ResponseHttpStatus.ResponseHttpStatus200) {
  275.  
  276.                 // remove 'page count' element
  277.                 final XMLNode data = response.getBody();
  278.                 // empty response
  279.                 if (data.getChildren() == null) {
  280.                     mapUpdateProgress.setVisibility(View.GONE);
  281.  
  282.                     return;
  283.                 }
  284.  
  285.                 final List<MapOverlayItem> locationsList = new ArrayList<MapOverlayItem>();
  286.  
  287.                 processLocationsDataThread = new Thread(new Runnable() {
  288.  
  289.                     public void run() {
  290.  
  291.                         // populate chats
  292.                         for (XMLNode child : data.getChildren()) {
  293.  
  294.                             // if user doesnt exist
  295.                             XMLNode userNode = child.findChild("user");
  296.                             if (userNode == null) {
  297.                                 continue;
  298.                             }
  299.  
  300.                             // skip own location
  301.                             if (Store.getInstance().getCurrentUser() != null
  302.                                     && userNode
  303.                                             .findChild("id")
  304.                                             .getText()
  305.                                             .equals(Store.getInstance()
  306.                                                     .getCurrentUser()
  307.                                                     .findChild("id").getText())) {
  308.                                 Store.getInstance().setCurrentStatus(
  309.                                         child.findChild("status").getText());
  310.                                 continue;
  311.                             }
  312.  
  313.                             int lat = (int) (Double.parseDouble(child
  314.                                     .findChild("latitude").getText()) * 1000000);
  315.                             int lng = (int) (Double.parseDouble(child
  316.                                     .findChild("longitude").getText()) * 1000000);
  317.  
  318.                             final MapOverlayItem overlayItem = new MapOverlayItem(
  319.                                     new GeoPoint(lat, lng), "", "");
  320.                             overlayItem.setUserStatus(child.findChild("status")
  321.                                     .getText());
  322.                             String name = child.findChild("user")
  323.                                     .findChild("full-name").getText();
  324.                             if (name.length() == 0) {
  325.                                 name = child.findChild("user")
  326.                                         .findChild("login").getText();
  327.                             }
  328.                             overlayItem.setUserName(name);
  329.                             locationsList.add(overlayItem);
  330.                         }
  331.  
  332.                         // there are no points
  333.                         if (locationsList.isEmpty()) {
  334.                             QuickBloxActivity.this.runOnUiThread(new Runnable() {
  335.  
  336.                                 @Override
  337.                                 public void run() {
  338.                                     mapUpdateProgress.setVisibility(View.GONE);
  339.                                 }
  340.                             });
  341.                             return;
  342.                         }
  343.  
  344.                         final ShowAllUsers whereAreUsers = new ShowAllUsers(
  345.                                 marker, locationsList);
  346.  
  347.                         // update map
  348.                         QuickBloxActivity.this.runOnUiThread(new Runnable() {
  349.  
  350.                             @Override
  351.                             public void run() {
  352.                                 // add overlays
  353.                                 mapView.getOverlays().clear();
  354.                                 mapView.getOverlays().add(whereAreUsers);
  355.                                 if (ownOverlay != null) {
  356.                                     mapView.getOverlays().add(ownOverlay);
  357.                                 }
  358.  
  359.                                 mapView.invalidate();
  360.  
  361.                                 mapUpdateProgress.setVisibility(View.GONE);
  362.                             }
  363.                         });
  364.                     }
  365.                 });
  366.  
  367.                 processLocationsDataThread.start();
  368.  
  369.             } else {
  370.                 mapUpdateProgress.setVisibility(View.GONE);
  371.  
  372.                 AlertManager.showServerError(this, "Error while updating map");
  373.             }
  374.             break;
  375.         }
  376.     }
  377.  
  378.     // Other Users overlays
  379.     class ShowAllUsers extends ItemizedOverlay<MapOverlayItem> {
  380.  
  381.         private List<MapOverlayItem> locations = new ArrayList<MapOverlayItem>();
  382.         private Drawable marker;
  383.  
  384.         public ShowAllUsers(Drawable marker, List<MapOverlayItem> overlayItems) {
  385.             super(marker);
  386.  
  387.             this.marker = marker;
  388.  
  389.             // populate items
  390.             for (MapOverlayItem overlayItem : overlayItems) {
  391.                 locations.add(overlayItem);
  392.                 populate();
  393.             }
  394.         }
  395.  
  396.         // a shadow of the marker
  397.         @Override
  398.         public void draw(Canvas canvas, MapView mapView, boolean shadow) {
  399.             super.draw(canvas, mapView, shadow);
  400.             boundCenterBottom(marker);
  401.         }
  402.  
  403.         @Override
  404.         protected MapOverlayItem createItem(int i) {
  405.             return locations.get(i);
  406.         }
  407.  
  408.         @Override
  409.         public int size() {
  410.             return locations.size();
  411.         }
  412.  
  413.         // tab on marker
  414.         @Override
  415.         protected boolean onTap(int i) {
  416.  
  417.             MapOverlayItem item = (MapOverlayItem) getItem(i);
  418.  
  419.             // set data
  420.             mapPopUp.setData(item.getUserName(), item.getUserFullName(),
  421.                     item.getUserStatus());
  422.  
  423.             // show popup
  424.             mapPopUp.show();
  425.  
  426.             return true;
  427.         }
  428.     }
  429.  
  430.     // Current User overlay
  431.     public class WhereAmI extends MyLocationOverlay {
  432.  
  433.         private Context mContext;
  434.         private float mOrientation;
  435.         private Rect markerRect;
  436.  
  437.         public WhereAmI(Context context, MapView mapView) {
  438.             super(context, mapView);
  439.             mContext = context;
  440.         }
  441.  
  442.         @Override
  443.         protected void drawMyLocation(Canvas canvas, MapView mapView,
  444.                 Location lastFix, GeoPoint myLocation, long when) {
  445.             // translate the GeoPoint to screen pixels
  446.             Point screenPts = mapView.getProjection()
  447.                     .toPixels(myLocation, null);
  448.  
  449.             // create a rotated copy of the marker
  450.             Bitmap arrowBitmap = BitmapFactory.decodeResource(
  451.                     mContext.getResources(), R.drawable.map_marker_my);
  452.             Matrix matrix = new Matrix();
  453.             matrix.postRotate(mOrientation);
  454.             Bitmap rotatedBmp = Bitmap.createBitmap(arrowBitmap, 0, 0,
  455.                     arrowBitmap.getWidth(), arrowBitmap.getHeight(), matrix,
  456.                     true);
  457.             // add the rotated marker to the canvas
  458.             canvas.drawBitmap(rotatedBmp, screenPts.x
  459.                     - (rotatedBmp.getWidth() / 2),
  460.                     screenPts.y - (rotatedBmp.getHeight() / 2), null);
  461.  
  462.             markerRect = new Rect(screenPts.x - (rotatedBmp.getWidth() / 2),
  463.                     screenPts.y - (rotatedBmp.getHeight() / 2), screenPts.x
  464.                             + (rotatedBmp.getWidth() / 2), screenPts.y
  465.                             + (rotatedBmp.getHeight() / 2));
  466.  
  467.             rotatedBmp.recycle();
  468.         }
  469.  
  470.         public void setOrientation(float newOrientation) {
  471.             mOrientation = newOrientation;
  472.         }
  473.  
  474.         @Override
  475.         public boolean onTap(GeoPoint p, MapView map) {
  476.  
  477.             Point tapPts = mapView.getProjection().toPixels(p, null);
  478.  
  479.             if (markerRect == null || tapPts == null) {
  480.                 return false;
  481.             }
  482.  
  483.             if (!markerRect.contains(tapPts.x, tapPts.y)) {
  484.                 return false;
  485.             }
  486.  
  487.             // show popup data
  488.             String status = Store.getInstance().getCurrentStatus();
  489.             if (status == null) {
  490.                 status = "<empty>";
  491.             }
  492.             mapPopUp.setData(
  493.                     Store.getInstance().getCurrentUser().findChild("login")
  494.                             .getText(), Store.getInstance().getCurrentUser()
  495.                             .findChild("full-name").getText(), status);
  496.  
  497.             // show popup
  498.             mapPopUp.show();
  499.  
  500.             return true;
  501.         }
  502.  
  503.     }
  504. }
Advertisement
Add Comment
Please, Sign In to add comment