Java tutorial
package com.woofy.haifa; import helper.HttpLib; import helper.HttpLib.PlayerList; import helper.Tools; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.Vector; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.location.Location; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.os.SystemClock; import android.preference.PreferenceManager; import android.support.v4.app.FragmentActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener; import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener; import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener; import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener; import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener; import com.google.android.gms.maps.Projection; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.Circle; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.Polygon; import com.google.gson.Gson; @TargetApi(Build.VERSION_CODES.GINGERBREAD) public class MapActivity extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, SensorEventListener { Handler mHandler = new Handler(); private Marker meet; static boolean background = false; public static Bitmap lastbitmap = null; CountDownTimer counttimer = null; Circle zz1, zz2, zz3; private static final int GPS_ERRORDIALOG_REQUEST = 9001; // private static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9002; static GoogleMap mMap; private static final float DEFAULTZOOM = 15; private static final String LOGTAG = "Maps"; private static final int RESULT = -1; static int game_counter = 0; LocationRequest mLocationRequest; GoogleApiClient mLocationClient; ArrayList<Marker> markers = new ArrayList<Marker>(); Polygon shape; Marker self = null; ArrayList<Marker> PersonMarkers = new ArrayList<Marker>();; private long show_people_last_updated = 0; public static JSONArray show_people_JSON; Set<String> selected_markers = new HashSet<String>(); private float[] mRotationMatrix = new float[16]; private float mDeclination = 0; private SensorManager mSensorManager; private Sensor mAccelerometer; boolean rotation_on = true; float bearing = 0; boolean track = false; boolean game_on = false; private long last_updated = 0; public static Map<String, Bitmap> pic_map; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR); pic_map = new HashMap<String, Bitmap>(); // background = false; if (servicesOK()) { setContentView(R.layout.activity_map); Intent service = new Intent(this, MessageService.class); startService(service); if (initMap()) { //mMap.setMyLocationEnabled(true); mLocationClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API) .addConnectionCallbacks(this).addOnConnectionFailedListener(this).build(); mLocationClient.connect(); new Thread(new Runnable() { boolean mStopHandler = false; @Override public void run() { // while (true) { if (!background) { showPeople(); } if (!mStopHandler) { mHandler.postDelayed(this, 3000); } // } } }).start(); userLocation(true);//goto user`s location Intent i = getIntent(); if (i.hasExtra("gamestartresult")) { joinGame(i.getStringExtra("gamestartresult"), i.getIntExtra("game_id", 0)); } } else { Toast.makeText(this, "Map not available!", Toast.LENGTH_SHORT).show(); } } else { setContentView(R.layout.activity_main); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } public boolean servicesOK() { int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (isAvailable == ConnectionResult.SUCCESS) { return true; } else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) { Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, this, GPS_ERRORDIALOG_REQUEST); dialog.show(); } else { Toast.makeText(this, "Can't connect to Google Play services", Toast.LENGTH_SHORT).show(); } return false; } private boolean initMap() { if (mMap == null) { SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mMap = mapFrag.getMap(); if (mMap != null) { mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() { @Override public View getInfoWindow(Marker marker) { // Getting view from the layout file LayoutInflater inflater = LayoutInflater.from(MapActivity.this); View v = inflater.inflate(R.layout.info_window, null); TextView locality = (TextView) v.findViewById(R.id.tv_locality); locality.setText(marker.getTitle()); // TextView title = (TextView) v.findViewById(R.id.tv_lat); // title.setText(marker.getTitle()); TextView address = (TextView) v.findViewById(R.id.tv_lng); address.setText(marker.getSnippet()); ImageView img = (ImageView) v.findViewById(R.id.imageView1); if (lastbitmap != null) { img.setImageBitmap(lastbitmap); } if (pic_map.containsKey(marker.getTitle())) { img.setImageBitmap(pic_map.get(marker.getTitle())); } if (marker.getTitle().equals("You")) { img.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.you_marker)); } if (marker.getSnippet().length() < 30) { // img.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.bad_dog)); new HttpLib.MarkerPic(marker.getTitle(), img, marker).execute(); // HttpLib.DownloadImageTask task=new HttpLib.DownloadImageTask(img,marker); // task.execute("http://52.1.192.145/uploads/img_1434327703156_kgqsjhlevp9fj6tcs7su32gj43.jpg"); // Vector<BasicNameValuePair> vec = new Vector<BasicNameValuePair>(); vec.add(new BasicNameValuePair("name", marker.getTitle())); new HttpLib.MarkerInfoWindow(vec, marker).execute(); } return v; // return null; } @Override public View getInfoContents(Marker marker) { View v = getLayoutInflater().inflate(R.layout.info_window, null); TextView tvLocality = (TextView) v.findViewById(R.id.tv_locality); TextView tvLat = (TextView) v.findViewById(R.id.tv_lat); TextView tvLng = (TextView) v.findViewById(R.id.tv_lng); TextView tvSnippet = (TextView) v.findViewById(R.id.tv_snippet); // ImageView img = (ImageView) v.findViewById(R.id.imageView1); LatLng ll = marker.getPosition(); tvLocality.setText(marker.getTitle()); // tvLat.setText("Dogs: " + "Woofy, Goofy"); // tvLng.setText("Click for more info"); // tvSnippet.setText(marker.getSnippet()); ImageView img = (ImageView) v.findViewById(R.id.imageView1); if (lastbitmap != null) { img.setImageBitmap(lastbitmap); Log.d("Set bitmap", "Set bitmap"); } else { new HttpLib.MarkerPic(marker.getTitle(), img, marker).execute(); } if (marker.getSnippet().length() < 30) { // img.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.bad_dog)); // HttpLib.DownloadImageTask task=new HttpLib.DownloadImageTask(img,marker); // task.execute("http://52.1.192.145/uploads/img_1434327703156_kgqsjhlevp9fj6tcs7su32gj43.jpg"); // Vector<BasicNameValuePair> vec = new Vector<BasicNameValuePair>(); vec.add(new BasicNameValuePair("name", marker.getTitle())); new HttpLib.MarkerInfoWindow(vec, marker).execute(); } return v; } }); mMap.setOnMapLongClickListener(new OnMapLongClickListener() { @Override public void onMapLongClick(final LatLng point) { final Dialog dialog = new Dialog(MapActivity.this); dialog.setContentView(R.layout.alert_layout); dialog.setCancelable(true); dialog.show(); // .setMessage(R.string.really_quit) Button b = (Button) dialog.findViewById(R.id.yesmeet); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String t1 = ((EditText) dialog.findViewById(R.id.meet_name)).getText().toString(); // String t2 = ((EditText)dialog.findViewById(R.id.editText1111)).getText().toString(); if (meet != null) meet.remove(); MarkerOptions options; options = new MarkerOptions().title(t1).position(point) .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)) .anchor(.5f, .5f) //center the icon .draggable(true); Marker mar = mMap.addMarker(options); // MeetingMarkers.add(mar); meet = mar; dialog.dismiss(); } }); Button b1 = (Button) dialog.findViewById(R.id.nomeet); b1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); } }); mMap.setOnCameraChangeListener(new OnCameraChangeListener() { @Override public void onCameraChange(CameraPosition position) { if (SystemClock.uptimeMillis() - show_people_last_updated > 1000) { show_people_last_updated = SystemClock.uptimeMillis(); showPeople(); } } }); mMap.setOnMarkerClickListener(new OnMarkerClickListener() { @Override public boolean onMarkerClick(final Marker marker) { lastbitmap = null; marker.hideInfoWindow(); marker.showInfoWindow(); return false; } }); mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() { @Override public void onInfoWindowClick(Marker marker) { Log.d("Open profile page", marker.getTitle()); Intent intent = new Intent(MapActivity.this, Profile.class); intent.putExtra("name", marker.getTitle()); startActivity(intent); } }); mMap.setOnMarkerDragListener(new OnMarkerDragListener() { @Override public void onMarkerDragStart(Marker marker) { marker.remove(); MarkerOptions options; options = new MarkerOptions().title(marker.getTitle()).position(marker.getPosition()) .icon(BitmapDescriptorFactory.fromResource(R.drawable.custom_marker)) .anchor(.5f, .5f) //center the icon .draggable(true); String name = marker.getTitle(); if (selected_markers.contains(name)) { selected_markers.remove(name); } else { selected_markers.add(name); options.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_checked)); } Marker addmarker = mMap.addMarker(options); PersonMarkers.add(addmarker); } @Override public void onMarkerDragEnd(Marker marker) { } @Override public void onMarkerDrag(Marker arg0) { } }); } } return (mMap != null); } // private void gotoLocation(double lat, double lng,float zoom) { // LatLng ll = new LatLng(lat, lng); // CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom); // mMap.moveCamera(update); // } // // // private void hideSoftKeyboard(View v) { // InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE); // imm.hideSoftInputFromWindow(v.getWindowToken(), 0); // } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.breed: Intent photoIntent = new Intent(MapActivity.this, WikiActivity.class); MapActivity.this.startActivity(photoIntent); break; case R.id.terms: AlertDialog.Builder builder = new AlertDialog.Builder(MapActivity.this); builder.setTitle("Google Maps Terms"); builder.setMessage(GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(this)); builder.setPositiveButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Do something } }); builder.show(); break; // case R.id.gotoCurrentLocation: // userLocation(true); // break; case R.id.take_photo: // Intent photoIntent = new Intent(MapActivity.this, ShareActivity.class); Intent photoIntent2 = new Intent(MapActivity.this, ImageUploadOld.class); // Intent photoIntent = new Intent(MapActivity.this, MessagesActivity.class); //Intent photoIntent = new Intent(MapActivity.this, SocialActivity.class); // Intent photoIntent = new Intent(MapActivity.this, WikiActivity.class); MapActivity.this.startActivity(photoIntent2); break; case R.id.dogs: Intent dogsIntent = new Intent(MapActivity.this, Dogs.class); MapActivity.this.startActivity(dogsIntent); break; case R.id.logout: SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); SharedPreferences.Editor editor = sharedPref.edit(); Log.d("Restore session from SharedPref:", sharedPref.getString("SESSION_ID", "NOT FOUND")); editor.clear();//clear saved preferences editor.commit(); //go back to login screen Intent i = new Intent(getApplicationContext(), LoginActivity.class); startActivity(i); finish(); break; case R.id.settings: Intent settingsIntent = new Intent(MapActivity.this, SettingsActivity.class); startActivityForResult(settingsIntent, RESULT); break; case R.id.social: Intent socialIntent = new Intent(MapActivity.this, SocialActivity.class); startActivityForResult(socialIntent, RESULT); break; default: break; } return super.onOptionsItemSelected(item); } public void showPeople() { userLocation(false);//update user`s marker Vector<BasicNameValuePair> v = new Vector<BasicNameValuePair>(); HttpLib.ShowPeople_PostTask post = new HttpLib.ShowPeople_PostTask(v, "http://52.1.192.145/show_people.php"); post.execute(); ArrayList<Marker> keep = new ArrayList<Marker>(); JSONArray people = show_people_JSON; //copy JSONarray for (Marker m : PersonMarkers) {//check that we aren`t drawing existing elements int found = -1; for (int i = 0; people != null && i < people.length() && (found == -1); i++) { try { JSONObject row = people.getJSONObject(i); if (m.getPosition().latitude == row.getDouble("lat") && m.getPosition().longitude == row.getDouble("lng")) { found = i; break; } } catch (JSONException e) { e.printStackTrace(); } } if (found < 0) {//if info window of the marker is open, don`t remove) if (m.isInfoWindowShown()) { m.setAlpha((float) 0); //hide the marker instead of deleting, it`ll be deleted once window is closed } else m.remove(); } else { people = Tools.RemoveJSONArray(people, found); keep.add(m); //save the marker } } PersonMarkers.clear(); PersonMarkers.addAll(keep); //add the saved markers try { Projection curr_proj = this.mMap.getProjection(); // Current projection of map if (people != null) {//isn`t empty (not yet updated) for (int i = 0; i < people.length(); i++) { JSONObject row = people.getJSONObject(i); //id = row.getInt("id"); //row.getString("email"); setPersonMarker(row, curr_proj); } } } catch (Exception e) { e.printStackTrace(); } } @Override protected void onStop() { if (mLocationClient.isConnected()) { LocationServices.FusedLocationApi.removeLocationUpdates(mLocationClient, this); mLocationClient.disconnect(); } background = true; game_on = false; super.onStop(); MapStateManager mgr = new MapStateManager(this); mgr.saveMapState(mMap); } @Override protected void onPause() { super.onPause(); mSensorManager.unregisterListener(this); } @Override protected void onResume() { background = false; super.onResume(); MapStateManager mgr = new MapStateManager(this); CameraPosition position = mgr.getSavedCameraPosition(); mLocationClient.connect(); if (position != null) { CameraUpdate update = CameraUpdateFactory.newCameraPosition(position); mMap.moveCamera(update); // This is part of the answer to the code challenge mMap.setMapType(mgr.getSavedMapType()); } mSensorManager.registerListener(this, mAccelerometer, 150000);//TODO if (position != null) { CameraUpdate update = CameraUpdateFactory.newCameraPosition(position); mMap.moveCamera(update); // This is part of the answer to the code challenge mMap.setMapType(mgr.getSavedMapType()); } SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); String mapType = SP.getString("prefMap", "1"); int typeNum = Integer.valueOf(mapType); switch (typeNum) { case 1: mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); break; case 2: mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE); break; case 3: mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN); break; case 4: mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); break; default: break; } String privacy = SP.getString("privacy", "0"); Vector<BasicNameValuePair> v = new Vector<BasicNameValuePair>(); v.add(new BasicNameValuePair("privacy", privacy)); HttpLib.PostTask pr = new HttpLib.PostTask(v, "http://52.1.192.145/set_privacy.php"); pr.execute(); } public void userLocation(View v) { userLocation(true); } protected void userLocation(boolean goTo) { Location currentLocation = LocationServices.FusedLocationApi.getLastLocation(mLocationClient);//mLocationClient.getLastLocation(); if (currentLocation == null) { // Toast.makeText(this, "Current location isn't available", Toast.LENGTH_SHORT).show(); } else { if (goTo || game_on) { // if Go to location flag is set LatLng ll = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()); // CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll,DEFAULTZOOM); mMap.getCameraPosition(); CameraPosition oldPos = mMap.getCameraPosition(); CameraPosition pos; if (!game_on) { pos = CameraPosition.builder(oldPos).target(ll).bearing(bearing).zoom(DEFAULTZOOM).build(); } else { pos = CameraPosition.builder(oldPos).target(ll).bearing(bearing).build(); } CameraUpdate update = CameraUpdateFactory.newCameraPosition(pos); mMap.animateCamera(update); // move the camera to user`s location } if (self == null || !(self.getPosition().equals(currentLocation))) { // if changed Marker old = self; self = setMarker("You", "Your current position", currentLocation.getLatitude(), currentLocation.getLongitude()); // set the marker if (old != null) { if (old.isInfoWindowShown()) self.showInfoWindow(); old.remove(); } // remove the old marker update(currentLocation); // post update to server } } } @Override public void onConnectionFailed(ConnectionResult arg0) { Log.i(LOGTAG, "GoogleApiClient connection FAILED"); } @Override public void onConnected(Bundle arg0) { mLocationRequest = LocationRequest.create(); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); mLocationRequest.setInterval(2000); // Update location every second LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, mLocationRequest, this); } private Marker setMarker(String locality, String country, double lat, double lng) { MarkerOptions options = new MarkerOptions().title(locality).position(new LatLng(lat, lng)).title("You") .icon(BitmapDescriptorFactory.fromResource(R.drawable.you_marker)).anchor(.5f, .5f) .draggable(false); if (country.length() > 0) { options.snippet(country); } Marker ret = mMap.addMarker(options); markers.add(ret); return ret; } @Override public void onConnectionSuspended(int arg0) { Log.i(LOGTAG, "GoogleApiClient connection has been suspended"); } @Override public void onLocationChanged(Location location) { if (!background) update(location); userLocation(false); // GeomagneticField field = new GeomagneticField( // (float)location.getLatitude(), // (float)location.getLongitude(), // (float)location.getAltitude(), // System.currentTimeMillis() // ); // // // getDeclination returns degrees // mDeclination = field.getDeclination(); } public void update(Location currentLocation) { if (System.currentTimeMillis() - last_updated < 4000) return; last_updated = System.currentTimeMillis(); Vector<BasicNameValuePair> v = new Vector<BasicNameValuePair>(); v.add(new BasicNameValuePair("lat", String.valueOf(currentLocation.getLatitude()))); v.add(new BasicNameValuePair("lng", String.valueOf(currentLocation.getLongitude()))); v.add(new BasicNameValuePair("email", "email")); // UpdateLocation update = new UpdateLocation(,,);//TODO HttpLib.PostTask update = new HttpLib.PostTask(v, "http://52.1.192.145/update.php"); update.execute(); } private void setPersonMarker(JSONObject user, Projection curr_projection) { try { LatLng userLL = new LatLng(user.getDouble("lat"), user.getDouble("lng")); //get user`s latlng LatLngBounds bounds = curr_projection.getVisibleRegion().latLngBounds; //check if marker is in visible region if (bounds.contains(userLL)) { MarkerOptions options; options = new MarkerOptions().title(user.getString("name")).position(userLL) .icon(BitmapDescriptorFactory.fromResource(R.drawable.custom_marker)) // .icon(BitmapDescriptorFactory.defaultMarker()) .anchor(.5f, .5f) //center the icon .draggable(true); options.snippet("Loading..."); if (selected_markers.contains(user.getString("name"))) { //If marker is selected options.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_checked)); } Marker marker = mMap.addMarker(options); PersonMarkers.add(marker); } } catch (JSONException e) { e.printStackTrace(); } } //=========================Safezone game=============================================================== public void safeZoneGame(View v) { if (game_on) { gameEnd(); return; } //get location Location you = LocationServices.FusedLocationApi.getLastLocation(mLocationClient); if (you == null) { return; } LatLng ll = new LatLng(you.getLatitude(), you.getLongitude()); //create round list ArrayList<Round> roundlist = new ArrayList<Round>(); for (int i = 0; i < 10; i++) { roundlist.add(new Round(i + 1, (50 - i * 2) * 2 + i * 5, ll, 30 - i * 2, (20 - i) * 1000)); } Gson gson = new Gson(); String roundarr = gson.toJson(roundlist); //create game Vector<BasicNameValuePair> vec = new Vector<BasicNameValuePair>(); vec.add(new BasicNameValuePair("round_json", roundarr)); HttpLib.SafeZoneInit initreq = new HttpLib.SafeZoneInit(vec, gson.toJson(selected_markers), roundlist, this); initreq.execute(); // JSONArray roundarr = new JSONArray(roundlist); // Log.wtf("JSONARR", roundarr); } private void gameEnd() { TextView timer = (TextView) findViewById(R.id.gametimer); timer.setVisibility(View.INVISIBLE); TextView plist = (TextView) findViewById(R.id.players_list); plist.setVisibility(View.INVISIBLE); game_on = false; if (counttimer != null) { counttimer.cancel(); zz1.remove(); zz2.remove(); zz3.remove(); } game_counter = 0; } @SuppressLint("NewApi") private void joinGame(String result, int game_id) { String[] stringarr = result.split("@@@"); String json = stringarr[1]; Gson gson = new Gson(); JSONArray json_arr; JSONObject game; try { json_arr = new JSONArray(json); game = json_arr.getJSONObject(0); String stringlist = game.getString("round_list"); json_arr = new JSONArray(stringlist); ArrayList<MapActivity.Round> roundlist = new ArrayList<MapActivity.Round>(); for (int i = 0; i < json_arr.length(); i++) { JSONObject round = json_arr.getJSONObject(i); MapActivity.Round obj = gson.fromJson(round.toString(), Round.class); roundlist.add(obj); } int delta = Integer.parseInt(stringarr[0]); if (delta <= 30) playGame(roundlist, 0, 30 - Integer.parseInt(stringarr[0]), game_id); } catch (JSONException e) { e.printStackTrace(); } } public void playGame(final ArrayList<Round> roundlist, final int round, final int delay, final int game_id) { if (round == 0) { game_on = true; } else if (!game_on) { return; } track = true; if (round == 0) { game_counter = 0; } final TextView timer = (TextView) findViewById(R.id.gametimer); timer.setVisibility(View.VISIBLE); if (round >= roundlist.size()) { timer.setText("You WIN"); //TODO you win return; } final TextView plist = (TextView) findViewById(R.id.players_list); plist.setVisibility(View.VISIBLE); final Round r1 = roundlist.get(round); final Circle zone1 = zz1 = drawCircle(r1.ll1, r1.circle_radius); final Circle zone2 = zz2 = drawCircle(r1.ll2, r1.circle_radius); final Circle zone3 = zz3 = drawCircle(r1.ll3, r1.circle_radius); long time_limit = r1.seconds + delay * 1000, interval = 1000; counttimer = new CountDownTimer(time_limit, interval) { @SuppressLint("NewApi") public void onTick(long milliUntilFinished) { if (!game_on) { zone1.remove(); zone2.remove(); zone3.remove(); this.cancel(); return; } game_counter++; timer.setText("" + milliUntilFinished / 1000); Vector<BasicNameValuePair> vec = new Vector<BasicNameValuePair>(); vec.add(new BasicNameValuePair("game_id", game_id + "")); HttpLib.PlayerList listtask = new PlayerList(vec, plist); listtask.execute(); Vector<BasicNameValuePair> vec2 = new Vector<BasicNameValuePair>(); vec2.add(new BasicNameValuePair("game_id", game_id + "")); vec2.add(new BasicNameValuePair("seconds", (game_counter - delay) + ""));//TODO HttpLib.PostTask updateseconds = new HttpLib.PostTask(vec2, "http://52.1.192.145/safezone_ping.php"); updateseconds.execute(); } public void onFinish() { zone1.remove(); zone2.remove(); zone3.remove(); if (!game_on) { return; } Location you = LocationServices.FusedLocationApi.getLastLocation(mLocationClient); if (you == null) { return; } LatLng ll = new LatLng(you.getLatitude(), you.getLongitude()); latLngDistance(zone1.getCenter(), ll); float mindistance = Math.min(latLngDistance(zone1.getCenter(), ll), latLngDistance(zone2.getCenter(), ll)); mindistance = Math.min(mindistance, latLngDistance(zone3.getCenter(), ll)); if (mindistance <= r1.circle_radius) { timer.setText("Next"); playGame(roundlist, round + 1, 0, game_id); } else { timer.setText("You LOSE"); gameEnd(); return; } } }.start(); } private Circle drawCircle(LatLng ll, double circle_radius) { CircleOptions options = new CircleOptions().center(ll).radius(circle_radius).fillColor(0x330000FF) .strokeColor(Color.RED).strokeWidth(3); return mMap.addCircle(options); } public static float latLngDistance(LatLng ll1, LatLng ll2) { Location loc1 = new Location(LocationManager.GPS_PROVIDER); Location loc2 = new Location(LocationManager.GPS_PROVIDER); loc1.setLatitude(ll1.latitude); loc1.setLongitude(ll1.longitude); loc2.setLatitude(ll2.latitude); loc2.setLongitude(ll2.longitude); return loc1.distanceTo(loc2); } public class Round { public int round_number; LatLng ll1, ll2, ll3; public final double circle_radius; public final long seconds; public Round(int round_number, double spread_radius, LatLng you, double circle_radius, long seconds) { this.round_number = round_number; ll1 = generateLatLng(you, spread_radius); ll2 = generateLatLng(you, spread_radius); ll3 = generateLatLng(you, spread_radius); this.circle_radius = circle_radius; this.seconds = seconds; } private LatLng generateLatLng(LatLng you, double spread_radius) { Random rd = new Random(); double lat = you.latitude + (rd.nextFloat() - 0.5) * spread_radius * 0.00000899; double lng = you.longitude + (rd.nextFloat() - 0.5) * spread_radius * 0.0000139; return new LatLng(lat, lng); } } @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR && rotation_on) { SensorManager.getRotationMatrixFromVector(mRotationMatrix, event.values); float[] orientation = new float[3]; SensorManager.getOrientation(mRotationMatrix, orientation); bearing = (float) (Math.toDegrees(orientation[0]) + mDeclination); // updateCamera(bearing); TODO } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } private void updateCamera(float bearing) { CameraPosition oldPos = mMap.getCameraPosition(); CameraPosition pos = CameraPosition.builder(oldPos).bearing(bearing).build(); mMap.moveCamera(CameraUpdateFactory.newCameraPosition(pos)); } }