diff --git a/android/RunUsAndroid/app/src/main/java/MultiMode/MultiModeRoom.java b/android/RunUsAndroid/app/src/main/java/MultiMode/MultiModeRoom.java index 4898a6ac..ffcb3961 100644 --- a/android/RunUsAndroid/app/src/main/java/MultiMode/MultiModeRoom.java +++ b/android/RunUsAndroid/app/src/main/java/MultiMode/MultiModeRoom.java @@ -13,7 +13,7 @@ import java.util.Queue; public class MultiModeRoom implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1344949L; private final int GAME_STARTED = 1; private final int GAME_NOT_STARTED = 0; private final transient List clientOutputStreams = new ArrayList<>(); diff --git a/android/RunUsAndroid/app/src/main/java/MultiMode/MultiModeUser.java b/android/RunUsAndroid/app/src/main/java/MultiMode/MultiModeUser.java index 870b34ae..cebd6668 100644 --- a/android/RunUsAndroid/app/src/main/java/MultiMode/MultiModeUser.java +++ b/android/RunUsAndroid/app/src/main/java/MultiMode/MultiModeUser.java @@ -4,7 +4,7 @@ import java.net.Socket; public class MultiModeUser implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 2194848L; private long id; private MultiModeRoom room; diff --git a/android/RunUsAndroid/app/src/main/java/MultiMode/Packet.java b/android/RunUsAndroid/app/src/main/java/MultiMode/Packet.java index 95752fdd..0a5d460d 100644 --- a/android/RunUsAndroid/app/src/main/java/MultiMode/Packet.java +++ b/android/RunUsAndroid/app/src/main/java/MultiMode/Packet.java @@ -5,9 +5,10 @@ public class Packet implements Serializable { //서버와 통신하기 위해 사용하는 클래스. Protocol + 필요한 정보 넣어서 전송 및 수신 private static final long serialVersionUID = 1L; + UserDistance[] top3UserDistance = null; + List listTop3UserDistance = null; // 데이터 유형을 나타내는 필드 private final int protocol; - UserDistance[] top3UserDistance = null; private RoomCreateInfo roomCreateInfo = null; // 실제 데이터 private MultiModeUser user; @@ -74,6 +75,11 @@ public Packet(int protocol, UserDistance[] top3UserDistance, long groupHistoryId this.groupHistoryId = groupHistoryId; } + public Packet(int protocol, List lTop3UserDistances, int temp) { + this.protocol = protocol; + this.listTop3UserDistance = lTop3UserDistances; + } + public Packet(int protocol, MultiModeUser user, float distance) { this.protocol = protocol; this.user = user; @@ -83,6 +89,9 @@ public Packet(int protocol, MultiModeUser user, float distance) { public long getGroupHistoryId() { return groupHistoryId; } + public List getListTop3UserDistance() { + return listTop3UserDistance; + } public void setGroupHistoryId(long groupHistoryId) { this.groupHistoryId = groupHistoryId; diff --git a/android/RunUsAndroid/app/src/main/java/MultiMode/UserDistance.java b/android/RunUsAndroid/app/src/main/java/MultiMode/UserDistance.java index d5c6b0ac..2e40fdab 100644 --- a/android/RunUsAndroid/app/src/main/java/MultiMode/UserDistance.java +++ b/android/RunUsAndroid/app/src/main/java/MultiMode/UserDistance.java @@ -3,7 +3,7 @@ import java.io.Serializable; public class UserDistance implements Serializable { - + private static final long serialVersionUID = 1931380L; MultiModeUser user; diff --git a/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/MultiModeAdapter.java b/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/MultiModeAdapter.java index 652d5cce..2f8a7d8b 100644 --- a/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/MultiModeAdapter.java +++ b/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/MultiModeAdapter.java @@ -129,6 +129,7 @@ public ViewHolder(@NonNull View itemView) { private class EnterRoomTask extends AsyncTask { private final Context mContext; private final NavController navcon; + private boolean isRoomFull; Packet packet; public EnterRoomTask(Context context, NavController navcon) { @@ -140,6 +141,7 @@ public EnterRoomTask(Context context, NavController navcon) { protected Boolean doInBackground(Void... voids) { Socket socket = null; boolean success = true; + isRoomFull = false; try { socketManager.openSocket(); // 소켓 연결 @@ -161,6 +163,10 @@ protected Boolean doInBackground(Void... voids) { printRoomInfo(packet.getSelectedRoom()); } } + else{ + success = false; + isRoomFull = true; + } } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); success = false; @@ -171,8 +177,6 @@ protected Boolean doInBackground(Void... voids) { @Override protected void onPostExecute(Boolean success) { //doInBackground()의 return값에 따라 작업 수행. 룸 리스트 업데이트, 입장하는 방 정보 업데이트 super.onPostExecute(success); - setRoomList(packet.getRoomList()); - selectedRoom = packet.getSelectedRoom(); if (success) { Log.d("SendPacket", "Packet sent successfully!"); setRoomList(packet.getRoomList()); @@ -183,7 +187,9 @@ protected void onPostExecute(Boolean success) { //doInBackground()의 return값 // NavController를 사용하여 다음 fragment로 이동 navcon.navigate(R.id.navigation_multi_room_wait, bundle); } else { - showFullRoomToast(mContext); // 방이 이미 꽉 찼다는 Toast 보내기 + if(isRoomFull) { + showFullRoomToast(mContext); // 방이 이미 꽉 찼다는 Toast 보내기 + } Log.e("SendPacket", "Failed to send packet!"); } } diff --git a/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/MultiModeFragment.java b/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/MultiModeFragment.java index 63b7d982..9ae94a8a 100644 --- a/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/MultiModeFragment.java +++ b/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/MultiModeFragment.java @@ -89,8 +89,9 @@ private void showModal(Context context) { // 초기값 설정 groupNameEditText.setText("Test"); //distanceEditText.setText("5"); - time_picker.setHour(0); - time_picker.setMinute(0); + LocalTime now = LocalTime.now().plusMinutes(1); + time_picker.setHour(now.getHour()); + time_picker.setMinute(now.getMinute()); membersEditText.setText("5"); numberPickerHour.setValue(0); numberPickerMinute.setValue(1); diff --git a/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/MultiModePlayFragment.java b/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/MultiModePlayFragment.java index 834f9998..b23839cb 100644 --- a/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/MultiModePlayFragment.java +++ b/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/MultiModePlayFragment.java @@ -1,6 +1,10 @@ package com.example.runusandroid.ui.multi_mode; import android.Manifest; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; import android.content.pm.PackageManager; import android.location.Location; import android.os.AsyncTask; @@ -19,6 +23,7 @@ import androidx.annotation.Nullable; import androidx.core.app.ActivityCompat; import androidx.fragment.app.Fragment; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; import androidx.navigation.NavController; import androidx.navigation.Navigation; @@ -28,11 +33,10 @@ import com.example.runusandroid.MainActivity2; import com.example.runusandroid.R; import com.example.runusandroid.RetrofitClient; +import com.example.runusandroid.ui.single_mode.BackGroundLocationService; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationCallback; import com.google.android.gms.location.LocationRequest; -import com.google.android.gms.location.LocationResult; -import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.model.LatLng; import org.json.JSONException; @@ -41,6 +45,7 @@ import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import java.io.Serializable; import java.time.Duration; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; @@ -49,6 +54,7 @@ import java.util.List; import java.util.Locale; +import Logging.FileLogger; import MultiMode.MultiModeRoom; import MultiMode.MultiModeUser; import MultiMode.Packet; @@ -60,6 +66,8 @@ import retrofit2.Response; public class MultiModePlayFragment extends Fragment { + static final String START_LOCATION_SERVICE = "start"; + static final String STOP_LOCATION_SERVICE = "stop"; private final List pathPoints = new ArrayList<>(); private final List speedList = new ArrayList<>(); // 매 km 마다 속력 (km/h) LocalDateTime iterationStartTime; @@ -71,7 +79,6 @@ public class MultiModePlayFragment extends Fragment { ObjectOutputStream oos; MultiModeRoom selectedRoom; float distance = 0; - float calories = 0; FusedLocationProviderClient fusedLocationClient; LocationCallback locationCallback; @@ -97,6 +104,71 @@ public class MultiModePlayFragment extends Fragment { UserDistance[] userDistances; private float minSpeed; private float maxSpeed; + private final BroadcastReceiver locationReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + if (intent.getAction().equals("location_update")) { + double latitude = intent.getDoubleExtra("latitude", 0.0); + double longitude = intent.getDoubleExtra("longitude", 0.0); + LatLng newPoint = new LatLng(latitude, longitude); + + pathPoints.add(newPoint); + Location location = new Location(""); + location.setLatitude(latitude); + location.setLongitude(longitude); + int lastDistanceInt = (int) distance; + + // get distance + if (newPoint != null) { + // first few points might be noisy + if (pathPoints.size() > 5 && mainActivity.activityReceiver.getIsRunning()) { + Location lastLocation = new Location(""); + lastLocation.setLatitude(pathPoints.get(pathPoints.size() - 2).latitude); + lastLocation.setLongitude(pathPoints.get(pathPoints.size() - 2).longitude); + // unit : meter -> kilometer + double last_distance_5s_kilometer = location.distanceTo(lastLocation) / (double) 1000; + + distance += last_distance_5s_kilometer; + Log.d("test:distance:5sec", "Last 5 second Distance :" + location.distanceTo(lastLocation) / (double) 1000); + if (last_distance_5s_kilometer != 0) { + int paceMinute = (int) (1 / (last_distance_5s_kilometer / 5)) / 60; + int paceSecond = (int) (1 / (last_distance_5s_kilometer / 5)) % 60; + if (paceMinute <= 30) { + String paceString = String.format("%02d'%02d\"", paceMinute, paceSecond); + pacePresentContentTextView.setText(paceString); + } else { + String paceString = "--'--\""; + pacePresentContentTextView.setText(paceString); + } + } else { + String paceString = "--'--\""; + pacePresentContentTextView.setText(paceString); + } + + // log distance into file + FileLogger.logToFileAndLogcat(mainActivity, "test:distance:5sec", "" + location.distanceTo(lastLocation) / (double) 1000); + //Below code seems to cause NullPointerException after 10 minutes or so (on Duration.between) + if ((int) distance != lastDistanceInt) { + LocalDateTime currentTime = LocalDateTime.now(); + Duration iterationDuration = Duration.between(iterationStartTime, currentTime); + long secondsDuration = iterationDuration.getSeconds(); + float newPace = (float) (1.0 / (secondsDuration / 3600.0)); + if (newPace > maxSpeed) + maxSpeed = newPace; + if (newPace < minSpeed) + minSpeed = newPace; + speedList.add(newPace); + iterationStartTime = currentTime; + + } + Log.d("test:distance:total", "Distance:" + distance); + } + + } + distancePresentContentTextView.setText(String.format(Locale.getDefault(), "%.2f" + "km", distance)); + } + } + }; private float medianSpeed; private HistoryApi historyApi; private TextView timePresentContentTextView; @@ -108,6 +180,7 @@ public class MultiModePlayFragment extends Fragment { @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); + finishedTask = new SendFinishedTask(); socketListenerThread.addPlayFragment(this); socketListenerThread.resumeListening(); gameStartTime = (LocalDateTime) getArguments().getSerializable("startTime"); @@ -120,7 +193,7 @@ public void onCreate(@Nullable Bundle savedInstanceState) { timeRunnable = new Runnable() { @Override public void run() { - if (selectedRoom != null && isFinished==0) { + if (selectedRoom != null && isFinished == 0) { LocalDateTime currentTime = LocalDateTime.now(); Duration present = Duration.between(gameStartTime, currentTime); long secondsElapsed = present.getSeconds(); @@ -135,14 +208,14 @@ public void run() { } else { String formattedTime = String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes, seconds); - timePresentContentTextView.setText(formattedTime); + if (timePresentContentTextView != null) + timePresentContentTextView.setText(formattedTime); } } if (isFinished == 0) { timeHandler.postDelayed(this, 1000); - } else if(isFinished == 1){ + } else if (isFinished == 1) { Packet requestPacket = new Packet(Protocol.FINISH_GAME, user, selectedRoom); - finishedTask = new SendFinishedTask(); finishedTask.execute(requestPacket); isFinished = 2; } @@ -155,7 +228,6 @@ public void run() { historyApi = RetrofitClient.getClient().create(HistoryApi.class); } - @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { @@ -163,10 +235,10 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c mainActivity = (MainActivity2) getActivity(); - locationRequest = LocationRequest.create(); - // TODO: let's find out which interval has best tradeoff - locationRequest.setInterval(5000); // Update interval in milliseconds - locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); + //locationRequest = LocationRequest.create(); + //// TODO: let's find out which interval has best tradeoff + //locationRequest.setInterval(5000); // Update interval in milliseconds + //locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); maxSpeed = 0; minSpeed = 999; View view = inflater.inflate(R.layout.fragment_multi_room_play, container, false); //각종 view 선언 @@ -207,85 +279,82 @@ public void onClick(View v) { } }); - //TODO: only draw lines if running is started - //TODO: doesn't update location when app is in background -> straight lines are drawn from the last location when app is opened again - //TODO: lines are ugly and noisy -> need to filter out some points or smoothed - locationCallback = new LocationCallback() { - @Override - public void onLocationResult(LocationResult locationResult) { - if (locationResult != null) { - Location location = locationResult.getLastLocation(); - LatLng newPoint = new LatLng(location.getLatitude(), location.getLongitude()); - Log.d("debug:location", "location : " + location.getLongitude() + ", " + location.getLatitude()); - pathPoints.add(newPoint); - - int lastDistanceInt = (int) distance; - // TODO: check calculate distance - if (newPoint != null) { - // first few points might be noisy && while activity is running (or walking) - if (pathPoints.size() > 5 && mainActivity.activityReceiver.getIsRunning()) { - Location lastLocation = new Location(""); - lastLocation.setLatitude(pathPoints.get(pathPoints.size() - 2).latitude); - lastLocation.setLongitude(pathPoints.get(pathPoints.size() - 2).longitude); - - // unit : meter -> kilometer - double last_distance_5s_kilometer = location.distanceTo(lastLocation) / (double) 1000; - distance += last_distance_5s_kilometer; - - // double speed_average = distance / (double) (Duration.between(gameStartTime, LocalDateTime.now()).getSeconds() / 3600.0); - -// if (speed_average > 0.1) { -// Log.d("debug:distance", "last 5s distance (km) : " + last_distance_5s_kilometer + ""); -// Log.d("debug:speed", "average speed since start (km/h) : " + speed_average + ""); -// String paceString = String.format("%4.2f km/h", speed_average); -// pacePresentContentTextView.setText(paceString); +// //TODO: only draw lines if running is started +// //TODO: doesn't update location when app is in background -> straight lines are drawn from the last location when app is opened again +// //TODO: lines are ugly and noisy -> need to filter out some points or smoothed +// locationCallback = new LocationCallback() { +// @Override +// public void onLocationResult(LocationResult locationResult) { +// if (locationResult != null) { +// Location location = locationResult.getLastLocation(); +// LatLng newPoint = new LatLng(location.getLatitude(), location.getLongitude()); +// Log.d("debug:location", "location : " + location.getLongitude() + ", " + location.getLatitude()); +// pathPoints.add(newPoint); +// +// int lastDistanceInt = (int) distance; +// // TODO: check calculate distance +// if (newPoint != null) { +// // first few points might be noisy && while activity is running (or walking) +// if (pathPoints.size() > 5 && mainActivity.activityReceiver.getIsRunning()) { +// Location lastLocation = new Location(""); +// lastLocation.setLatitude(pathPoints.get(pathPoints.size() - 2).latitude); +// lastLocation.setLongitude(pathPoints.get(pathPoints.size() - 2).longitude); +// +// // unit : meter -> kilometer +// double last_distance_5s_kilometer = location.distanceTo(lastLocation) / (double) 1000; +// distance += last_distance_5s_kilometer; +// +// // double speed_average = distance / (double) (Duration.between(gameStartTime, LocalDateTime.now()).getSeconds() / 3600.0); +// +//// if (speed_average > 0.1) { +//// Log.d("debug:distance", "last 5s distance (km) : " + last_distance_5s_kilometer + ""); +//// Log.d("debug:speed", "average speed since start (km/h) : " + speed_average + ""); +//// String paceString = String.format("%4.2f km/h", speed_average); +//// pacePresentContentTextView.setText(paceString); +//// } else { +//// String paceString = "--.-- km/h"; +//// pacePresentContentTextView.setText(paceString); +//// } +// +// if (last_distance_5s_kilometer != 0) { +// int paceMinute = (int) (1 / (last_distance_5s_kilometer / 5)) / 60; +// int paceSecond = (int) (1 / (last_distance_5s_kilometer / 5)) % 60; +// +// if (paceMinute <= 30) { +// String paceString = String.format("%02d'%02d\"", paceMinute, paceSecond); +// pacePresentContentTextView.setText(paceString); +// } else { +// String paceString = "--'--\""; +// pacePresentContentTextView.setText(paceString); +// } // } else { -// String paceString = "--.-- km/h"; +// String paceString = "--'--\""; // pacePresentContentTextView.setText(paceString); // } - - if (last_distance_5s_kilometer != 0 ) { - int paceMinute = (int) (1 / (last_distance_5s_kilometer / 5)) / 60; - int paceSecond = (int) (1 / (last_distance_5s_kilometer / 5)) % 60; - - if (paceMinute <= 30) { - String paceString = String.format("%02d'%02d\"", paceMinute, paceSecond); - pacePresentContentTextView.setText(paceString); - } - else { - String paceString = "--'--\""; - pacePresentContentTextView.setText(paceString); - } - } else { - String paceString = "--'--\""; - pacePresentContentTextView.setText(paceString); - } - - - - - // pace unused for now -// if ((int) distance != lastDistanceInt) { -// LocalDateTime currentTime = LocalDateTime.now(); -// Duration iterationDuration = Duration.between(iterationStartTime, currentTime); -// long secondsDuration = iterationDuration.getSeconds(); -// float newPace = (float) (1.0 / (secondsDuration / 3600.0)); -// if (newPace > maxSpeed) maxSpeed = newPace; -// if (newPace < minSpeed) minSpeed = newPace; -// speedList.add(newPace); -// iterationStartTime = currentTime; // -// } - } - } - // update distance text - distancePresentContentTextView.setText(String.format(Locale.getDefault(), "%.2f" + "km", distance)); - Log.d("debug:distance", "total distance : " + distance); - } - } - }; - - fusedLocationClient = LocationServices.getFusedLocationProviderClient(mainActivity); +// +// // pace unused for now +//// if ((int) distance != lastDistanceInt) { +//// LocalDateTime currentTime = LocalDateTime.now(); +//// Duration iterationDuration = Duration.between(iterationStartTime, currentTime); +//// long secondsDuration = iterationDuration.getSeconds(); +//// float newPace = (float) (1.0 / (secondsDuration / 3600.0)); +//// if (newPace > maxSpeed) maxSpeed = newPace; +//// if (newPace < minSpeed) minSpeed = newPace; +//// speedList.add(newPace); +//// iterationStartTime = currentTime; +//// +//// } +// } +// } +// // update distance text +// distancePresentContentTextView.setText(String.format(Locale.getDefault(), "%.2f" + "km", distance)); +// Log.d("debug:distance", "total distance : " + distance); +// } +// } +// }; + + //fusedLocationClient = LocationServices.getFusedLocationProviderClient(mainActivity); //5초마다 현재 이동 거리 전송 @@ -314,7 +383,6 @@ public void run() { } - public void updateTop3UserDistance(UserDistance[] userDistances) { // 화면에 표시되는 top3 유저 정보 업데이트. socketListenerThread에서 사용 UserDistance[] top3UserDistance = userDistances; for (int i = 0; i < userDistances.length; i++) { @@ -326,21 +394,21 @@ public void updateTop3UserDistance(UserDistance[] userDistances) { // 화면에 if (top3UserDistance.length >= 1) { goldNickNameTextView.setText(top3UserDistance[0].getUser().getNickName()); goldDistance = top3UserDistance[0].getDistance(); - String goldDistanceString = String.format("%.3fkm", goldDistance); + String goldDistanceString = String.format("%.2fkm", goldDistance); goldDistanceTextView.setText(goldDistanceString); if (top3UserDistance.length >= 2) { silverNickNameTextView.setText(top3UserDistance[1].getUser().getNickName()); double silverDistance = top3UserDistance[1].getDistance(); - String silverDistanceString = String.format("%.3fkm", silverDistance); + String silverDistanceString = String.format("%.2fkm", silverDistance); silverDistanceTextView.setText(silverDistanceString); if (top3UserDistance.length >= 3) { bronzeNickNameTextView.setText(top3UserDistance[2].getUser().getNickName()); double bronzeDistance = top3UserDistance[2].getDistance(); - String bronzeDistanceString = String.format("%.3fkm", bronzeDistance); + String bronzeDistanceString = String.format("%.2fkm", bronzeDistance); bronzeDistanceTextView.setText(bronzeDistanceString); } } @@ -349,7 +417,7 @@ public void updateTop3UserDistance(UserDistance[] userDistances) { // 화면에 int progress = 0; if (goldDistance != 0) { progress = (int) ((int) distance / goldDistance) * 100; - } + } else progress = 100; progressBar.setProgress(progress); } @@ -358,13 +426,13 @@ public void updateTop3UserDistance(UserDistance[] userDistances) { // 화면에 public void onResume() { super.onResume(); //아래 코드에서 resume때 result fragment로 가는 이유? - transitionToRusultFragment(); + transitionToResultFragment(); // socketListenerThread = (SocketListenerThread) getArguments().getSerializable("socketListenerThread"); //waitFragment의 socketListenrThread객체 가져와서 이어서 사용 Log.d("response", "start play screen"); //top3UpdateHandler.postDelayed(sendDataRunnable, 5000); - fusedLocationClient.removeLocationUpdates(locationCallback); + //fusedLocationClient.removeLocationUpdates(locationCallback); if (ActivityCompat.checkSelfPermission(mainActivity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { @@ -374,8 +442,12 @@ public void onResume() { != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(mainActivity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1000); } + Intent intent = new Intent(getContext(), BackGroundLocationService.class); + intent.setAction(START_LOCATION_SERVICE); + getActivity().startForegroundService(intent); + LocalBroadcastManager.getInstance(requireContext()).registerReceiver(locationReceiver, new IntentFilter("location_update")); - fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper()); + //fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper()); } @@ -385,8 +457,8 @@ public void onPause() { // if (socketListenerThread != null) { // socketListenerThread.interrupt(); // } - fusedLocationClient.removeLocationUpdates(locationCallback); - finishedTask.cancel(true); + //fusedLocationClient.removeLocationUpdates(locationCallback); + //finishedTask.cancel(true); } @Override @@ -416,7 +488,7 @@ public void onResponse(Call call, Response response) } catch (IOException e) { throw new RuntimeException(e); } - transitionToRusultFragment(); + transitionToResultFragment(); } } @@ -475,6 +547,7 @@ public void onResponse(Call call, Response response) } } + @Override public void onFailure(Call call, Throwable t) { } @@ -511,12 +584,20 @@ public void setSendDataHandler(Handler sendDataHandler) { this.sendDataHandler = sendDataHandler; } - private void transitionToRusultFragment() { + private void transitionToResultFragment() { if (userDistances != null) { + if (speedList != null) { + LocalDateTime currentTime = LocalDateTime.now(); + Duration iterationDuration = Duration.between(iterationStartTime, currentTime); + long secondsDuration = iterationDuration.getSeconds(); + float newPace = (float) ((distance - (int) distance) / (secondsDuration / 3600.0)); + speedList.add(newPace); + } Bundle bundle = new Bundle(); bundle.putSerializable("room", selectedRoom); bundle.putSerializable("top3UserDistance", userDistances); bundle.putSerializable("userDistance", distance); + bundle.putSerializable("userSpeedList", (Serializable) speedList); NavController navController = Navigation.findNavController(requireView()); navController.navigate(R.id.navigation_multi_room_result, bundle); } @@ -571,11 +652,10 @@ public Boolean doInBackground(Packet... packets) { if (packets.length > 0) { Packet requestPacket = packets[0]; ObjectOutputStream oos = socketManager.getOOS(); - if(!isCancelled() && oos!=null) { + if (!isCancelled() && oos != null) { oos.writeObject(requestPacket); oos.flush(); - } - else { + } else { success = false; Log.d("Sendfinishedpacket", "task is cancelled or oos is null"); } @@ -596,6 +676,9 @@ protected void onPostExecute(Boolean success) { super.onPostExecute(success); if (success) { Log.d("SendfinishedPacket", "Packet sent successfully!"); + timeHandler.removeCallbacks(timeRunnable); + sendDataHandler.removeCallbacks(sendDataRunnable); + } else { Log.d("SendfinishedPacket", "Failed to send packet!"); @@ -643,6 +726,7 @@ protected void onPostExecute(Boolean success) { public class ExitGameTask extends AsyncTask { Packet packet; + @Override public Boolean doInBackground(Packet... packets) { boolean success = true; diff --git a/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/MultiModeRecordAdapter.java b/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/MultiModeRecordAdapter.java new file mode 100644 index 00000000..78d5b4bc --- /dev/null +++ b/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/MultiModeRecordAdapter.java @@ -0,0 +1,83 @@ +package com.example.runusandroid.ui.multi_mode; + +import android.util.Log; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.RecyclerView; + +import com.example.runusandroid.R; + +import java.util.ArrayList; + +public class MultiModeRecordAdapter extends RecyclerView.Adapter { + private final ArrayList items = new ArrayList<>(); + + @NonNull + @Override + public RecordViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + LayoutInflater inflater = LayoutInflater.from(parent.getContext()); + View itemView = inflater.inflate(R.layout.record_item, parent, false); + + return new RecordViewHolder(itemView); + } + + @Override + public void onBindViewHolder(@NonNull RecordViewHolder holder, int position) { + holder.setItem(items.get(position)); + } + + @Override + public int getItemCount() { + return items.size(); + } + + void addItem(RecordItem item) { + items.add(item); + } + + static class RecordViewHolder extends RecyclerView.ViewHolder { + TextView runSectionTextView; + TextView averagePaceTextView; + + RecordViewHolder(View itemView) { + super(itemView); + + runSectionTextView = itemView.findViewById(R.id.runSection); + averagePaceTextView = itemView.findViewById(R.id.average_pace); + } + + void setItem(RecordItem item) { + String sectionString; + if (Math.abs(item.getSection() - (int) item.getSection()) < 0.0005) { + sectionString = String.valueOf((int) item.getSection()); + } else { + Log.d("speedlist", item.getSection() + ""); + sectionString = String.format("%.3f", item.getSection()); + } + + double averageSpeed = item.getAverageSpeed(); + String paceString; + if (averageSpeed < 1) { + paceString = "59'59''"; + } else { + double pace = 1.0 / (averageSpeed / 60.0); + int paceMinutes = (int) pace; + int paceSeconds = (int) ((pace - paceMinutes) * 60.0); + paceString = String.format("%02d'%02d''", paceMinutes, paceSeconds); + } + + + runSectionTextView.setText(sectionString); + averagePaceTextView.setText(paceString); + + + } + + + } + +} diff --git a/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/MultiModeResultFragment.java b/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/MultiModeResultFragment.java index 019407b1..8e5f2a4d 100644 --- a/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/MultiModeResultFragment.java +++ b/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/MultiModeResultFragment.java @@ -14,11 +14,14 @@ import androidx.fragment.app.Fragment; import androidx.navigation.NavController; import androidx.navigation.Navigation; +import androidx.recyclerview.widget.RecyclerView; import com.example.runusandroid.MainActivity2; import com.example.runusandroid.R; import java.io.ObjectOutputStream; +import java.util.ArrayList; +import java.util.Locale; import MultiMode.MultiModeRoom; import MultiMode.MultiModeUser; @@ -31,6 +34,7 @@ public class MultiModeResultFragment extends Fragment { ObjectOutputStream oos; MultiModeRoom selectedRoom; float distance = 0; + ArrayList speedList; NavController navController; TextView paceGoalContentTextView; MainActivity2 mainActivity; @@ -43,7 +47,13 @@ public class MultiModeResultFragment extends Fragment { TextView bronzeNickNameTextView; ProgressBar progressBar; Button playLeaveButton; + Button recordButton; + TextView distanceResultContentTextView; //API 사용해서 구한 나의 현재 이동 거리 SocketListenerThread socketListenerThread = MultiModeWaitFragment.socketListenerThread; + RecyclerView recyclerView; + RecordDialog dialog; + boolean isDialogOpenedBefore = false; + private TextView timeResultContentTextView; @Nullable @Override @@ -61,6 +71,50 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c bronzeDistanceTextView = view.findViewById(R.id.bronze_distance); progressBar = view.findViewById(R.id.linear_progress_bar); playLeaveButton = view.findViewById(R.id.result_leaveButton); + distanceResultContentTextView = view.findViewById(R.id.distance_present_content); + timeResultContentTextView = view.findViewById(R.id.time_present_content); + dialog = new RecordDialog(requireContext()); // requireContext()를 사용하여 컨텍스트 가져옴 + + recordButton = view.findViewById(R.id.record_button); + recordButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + dialog.show(); + if (!isDialogOpenedBefore) { + + + speedList = (ArrayList) getArguments().getSerializable("userSpeedList"); + Log.d("speedList", speedList.size() + ""); + double section = 1.0; + //for test +// distance = 4.579f; +// speedList = new ArrayList<>(); +// speedList.add(12.0f); +// speedList.add(10.0f); +// speedList.add(15.0f); +// speedList.add(20.0f); +// speedList.add(12.0f); + + while (true) { + if (distance - section >= 0) { + float speed = speedList.get((int) section - 1); + dialog.adapter.addItem(new RecordItem(section, speed)); + Log.d("speedList", "first if : " + section + " " + speed); + + section++; + } else { + float speed = speedList.get((int) section - 1); + dialog.adapter.addItem(new RecordItem(distance - (section - 1), speed)); + Log.d("speedList", "second if : " + (section - 1) + " " + speed); + section = 1.0; + break; + } + } + dialog.adapter.notifyDataSetChanged(); + isDialogOpenedBefore = true; + } + } + }); } @@ -90,20 +144,20 @@ public void updateTop3UserDistance(UserDistance[] userDistances) { // 화면에 if (top3UserDistance.length >= 1) { goldNickNameTextView.setText(top3UserDistance[0].getUser().getNickName()); goldDistance = top3UserDistance[0].getDistance(); - String goldDistanceString = String.format("%.3fkm", goldDistance); + String goldDistanceString = String.format("%.2fkm", goldDistance); goldDistanceTextView.setText(goldDistanceString); if (top3UserDistance.length >= 2) { silverNickNameTextView.setText(top3UserDistance[1].getUser().getNickName()); double silverDistance = top3UserDistance[1].getDistance(); - String silverDistanceString = String.format("%.3fkm", silverDistance); + String silverDistanceString = String.format("%.2fkm", silverDistance); silverDistanceTextView.setText(silverDistanceString); if (top3UserDistance.length >= 3) { bronzeNickNameTextView.setText(top3UserDistance[2].getUser().getNickName()); double bronzeDistance = top3UserDistance[2].getDistance(); - String bronzeDistanceString = String.format("%.3fkm", bronzeDistance); + String bronzeDistanceString = String.format("%.2fkm", bronzeDistance); bronzeDistanceTextView.setText(bronzeDistanceString); } } @@ -123,6 +177,16 @@ public void onResume() { UserDistance[] top3UserDistance = (UserDistance[]) getArguments().getSerializable("top3UserDistance"); updateTop3UserDistance(top3UserDistance); distance = (float) getArguments().getSerializable("userDistance"); + distanceResultContentTextView.setText(String.format(Locale.getDefault(), "%.2f" + "km", distance)); + long seconds = selectedRoom.getDuration().getSeconds(); + long hours = seconds / 3600; + long minutes = (seconds % 3600) / 60; + seconds = seconds % 60; + // "00:00:00" 형태의 문자열로 변환 + String formattedDuration = String.format("%02d:%02d:%02d", hours, minutes, seconds); + + + timeResultContentTextView.setText(formattedDuration); Log.d("response", "here is room result screen"); diff --git a/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/RecordDialog.java b/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/RecordDialog.java new file mode 100644 index 00000000..92e8efb3 --- /dev/null +++ b/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/RecordDialog.java @@ -0,0 +1,55 @@ +package com.example.runusandroid.ui.multi_mode; + +import android.app.Dialog; +import android.content.Context; +import android.os.Bundle; +import android.view.View; +import android.view.Window; +import android.widget.ImageButton; + +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import com.example.runusandroid.R; + +public class RecordDialog extends Dialog implements View.OnClickListener { + + public Context context; + public ImageButton closeButton; + RecyclerView recyclerView; + + MultiModeRecordAdapter adapter; + + public RecordDialog(Context context) { + super(context); + this.context = context; + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + requestWindowFeature(Window.FEATURE_NO_TITLE); + setContentView(R.layout.running_record_modal_layout); + + closeButton = findViewById(R.id.buttonClose); + closeButton.setOnClickListener(this); + + recyclerView = findViewById(R.id.recordRecyclerView); + adapter = new MultiModeRecordAdapter(); + recyclerView.setAdapter(adapter); + LinearLayoutManager layoutManager = new LinearLayoutManager(context); + recyclerView.setLayoutManager(layoutManager); + + } + + @Override + public void onClick(View v) { + if (v.getId() == R.id.buttonClose) { + dismiss(); + } + } + + public void notifyDataSetChanged() { + adapter.notifyDataSetChanged(); + } +} diff --git a/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/RecordItem.java b/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/RecordItem.java new file mode 100644 index 00000000..6d8c2341 --- /dev/null +++ b/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/RecordItem.java @@ -0,0 +1,19 @@ +package com.example.runusandroid.ui.multi_mode; + +public class RecordItem { + private final double section; + private final double averageSpeed; + + RecordItem(double section, double pace) { + this.section = section; + this.averageSpeed = pace; + } + + double getSection() { + return section; + } + + double getAverageSpeed() { + return averageSpeed; + } +} diff --git a/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/SocketListenerThread.java b/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/SocketListenerThread.java index 0e93aee2..1c32de22 100644 --- a/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/SocketListenerThread.java +++ b/android/RunUsAndroid/app/src/main/java/com/example/runusandroid/ui/multi_mode/SocketListenerThread.java @@ -16,6 +16,7 @@ import java.io.Serializable; import java.net.SocketException; import java.time.LocalDateTime; +import java.util.List; import MultiMode.MultiModeRoom; import MultiMode.MultiModeUser; @@ -37,9 +38,6 @@ public SocketListenerThread(MultiModeWaitFragment waitFragment, Handler handler, this.ois = ois; this.waitFragment = waitFragment; this.selectedRoom = selectedRoom; - Log.d("response", "waitFragment is " + this.waitFragment); - Log.d("response", "playFragment is " + this.playFragment); - } public void pauseListening() { @@ -71,7 +69,6 @@ public void run() { synchronized (ois) { receivedObject = ois.readObject(); } - Log.d("response", "getReceivedObject " + receivedObject); if (receivedObject instanceof Packet) { Packet packet = (Packet) receivedObject; @@ -118,21 +115,13 @@ public void run() { handler.post(new Runnable() { @Override public void run() { - UserDistance[] userDistances = packet.getTop3UserDistance(); - if (userDistances == null) { - Log.d("response", "userDistances.length is null"); - } else { - Log.d("response", "userDistances.length is " + userDistances.length); - - for (int i = 0; i < userDistances.length; i++) { - - Log.d("response", "user " + i + " : " + userDistances[0].getUser().getNickName() + " , distance : " + userDistances[0].getDistance()); - } - Log.d("response", "playFragment is " + playFragment); - Log.d("response", "waitFragment is " + waitFragment); - playFragment.updateTop3UserDistance(userDistances); + List temp = packet.getListTop3UserDistance(); + UserDistance[] userDistances = temp.toArray(new UserDistance[temp.size()]); + Log.d("response", "userDistances.length is " + userDistances.length); + for (int i = 0; i < userDistances.length; i++) { + Log.d("response", "user " + i + " : " + userDistances[i].getUser().getNickName() + " , distance : " + userDistances[i].getDistance()); } - + playFragment.updateTop3UserDistance(userDistances); } }); } else if (packet.getProtocol() == Protocol.SAVE_GROUP_HISTORY) { @@ -141,7 +130,9 @@ public void run() { public void run() { try { Log.d("response", "got packet and try to save group history"); - playFragment.saveGroupHistoryData(packet.getTop3UserDistance()); + List temp = packet.getListTop3UserDistance(); + UserDistance[] userDistances = temp.toArray(new UserDistance[temp.size()]); + playFragment.saveGroupHistoryData(userDistances); } catch (JSONException e) { throw new RuntimeException(e); } @@ -159,7 +150,9 @@ public void run() { Bundle bundle = new Bundle(); bundle.putSerializable("room", selectedRoom); //bundle.putSerializable("socketListenerThread", SocketListenerThread.this); - playFragment.userDistances = packet.getTop3UserDistance(); + List temp = packet.getListTop3UserDistance(); + UserDistance[] userDistances = temp.toArray(new UserDistance[temp.size()]); + playFragment.userDistances = userDistances; // bundle.putSerializable("top3UserDistance", packet.getTop3UserDistance()); // bundle.putSerializable("userDistance", playFragment.distance); Log.d("response", "go to room result screen"); @@ -170,7 +163,7 @@ public void run() { } // NavController navController = Navigation.findNavController(playFragment.requireView()); // navController.navigate(R.id.navigation_multi_room_result, bundle); - Log.d("response", packet.getTop3UserDistance() + " "); + //Log.d("response", packet.getTop3UserDistance() + " "); Log.d("response", resultFragment + ""); // resultFragment.updateTop3UserDistance(packet.getTop3UserDistance()); diff --git a/android/RunUsAndroid/app/src/main/res/layout/fragment_multi_room_wait.xml b/android/RunUsAndroid/app/src/main/res/layout/fragment_multi_room_wait.xml index c435ab1e..e347f046 100644 --- a/android/RunUsAndroid/app/src/main/res/layout/fragment_multi_room_wait.xml +++ b/android/RunUsAndroid/app/src/main/res/layout/fragment_multi_room_wait.xml @@ -61,7 +61,7 @@ + + + + + + \ No newline at end of file diff --git a/android/RunUsAndroid/app/src/main/res/layout/running_record_modal_layout.xml b/android/RunUsAndroid/app/src/main/res/layout/running_record_modal_layout.xml new file mode 100644 index 00000000..560444bc --- /dev/null +++ b/android/RunUsAndroid/app/src/main/res/layout/running_record_modal_layout.xml @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/android/SocketServer/.gitignore b/android/SocketServer/.gitignore new file mode 100644 index 00000000..a284ee22 --- /dev/null +++ b/android/SocketServer/.gitignore @@ -0,0 +1,28 @@ + +### Java ### +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +# End of https://www.toptal.com/developers/gitignore/api/java \ No newline at end of file diff --git a/android/SocketServer/out/production/SocketServer/MultiMode/MultiModeRoom.class b/android/SocketServer/out/production/SocketServer/MultiMode/MultiModeRoom.class index 8f3aeeb0..faf9608f 100644 Binary files a/android/SocketServer/out/production/SocketServer/MultiMode/MultiModeRoom.class and b/android/SocketServer/out/production/SocketServer/MultiMode/MultiModeRoom.class differ diff --git a/android/SocketServer/out/production/SocketServer/MultiMode/MultiModeUser.class b/android/SocketServer/out/production/SocketServer/MultiMode/MultiModeUser.class index ce7df973..618c80b6 100644 Binary files a/android/SocketServer/out/production/SocketServer/MultiMode/MultiModeUser.class and b/android/SocketServer/out/production/SocketServer/MultiMode/MultiModeUser.class differ diff --git a/android/SocketServer/out/production/SocketServer/MultiMode/Packet.class b/android/SocketServer/out/production/SocketServer/MultiMode/Packet.class index 524155e2..f42f55a9 100644 Binary files a/android/SocketServer/out/production/SocketServer/MultiMode/Packet.class and b/android/SocketServer/out/production/SocketServer/MultiMode/Packet.class differ diff --git a/android/SocketServer/out/production/SocketServer/MultiMode/RoomManager.class b/android/SocketServer/out/production/SocketServer/MultiMode/RoomManager.class index 5205d7e7..6caba795 100644 Binary files a/android/SocketServer/out/production/SocketServer/MultiMode/RoomManager.class and b/android/SocketServer/out/production/SocketServer/MultiMode/RoomManager.class differ diff --git a/android/SocketServer/out/production/SocketServer/MultiMode/UserDistance.class b/android/SocketServer/out/production/SocketServer/MultiMode/UserDistance.class index c17c4472..abb30350 100644 Binary files a/android/SocketServer/out/production/SocketServer/MultiMode/UserDistance.class and b/android/SocketServer/out/production/SocketServer/MultiMode/UserDistance.class differ diff --git a/android/SocketServer/out/production/SocketServer/Server.class b/android/SocketServer/out/production/SocketServer/Server.class index bc828ee2..36614ebb 100644 Binary files a/android/SocketServer/out/production/SocketServer/Server.class and b/android/SocketServer/out/production/SocketServer/Server.class differ diff --git a/android/SocketServer/src/MultiMode/MultiModeRoom.java b/android/SocketServer/src/MultiMode/MultiModeRoom.java index 4898a6ac..ffcb3961 100644 --- a/android/SocketServer/src/MultiMode/MultiModeRoom.java +++ b/android/SocketServer/src/MultiMode/MultiModeRoom.java @@ -13,7 +13,7 @@ import java.util.Queue; public class MultiModeRoom implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1344949L; private final int GAME_STARTED = 1; private final int GAME_NOT_STARTED = 0; private final transient List clientOutputStreams = new ArrayList<>(); diff --git a/android/SocketServer/src/MultiMode/MultiModeUser.java b/android/SocketServer/src/MultiMode/MultiModeUser.java index f9f24bc3..34915537 100644 --- a/android/SocketServer/src/MultiMode/MultiModeUser.java +++ b/android/SocketServer/src/MultiMode/MultiModeUser.java @@ -4,7 +4,7 @@ import java.net.Socket; public class MultiModeUser implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 2194848L; private long id; private MultiModeRoom room; diff --git a/android/SocketServer/src/MultiMode/Packet.java b/android/SocketServer/src/MultiMode/Packet.java index 58aced76..0a5d460d 100644 --- a/android/SocketServer/src/MultiMode/Packet.java +++ b/android/SocketServer/src/MultiMode/Packet.java @@ -6,6 +6,7 @@ public class Packet implements Serializable { //서버와 통신하기 위해 사용하는 클래스. Protocol + 필요한 정보 넣어서 전송 및 수신 private static final long serialVersionUID = 1L; UserDistance[] top3UserDistance = null; + List listTop3UserDistance = null; // 데이터 유형을 나타내는 필드 private final int protocol; private RoomCreateInfo roomCreateInfo = null; @@ -74,6 +75,11 @@ public Packet(int protocol, UserDistance[] top3UserDistance, long groupHistoryId this.groupHistoryId = groupHistoryId; } + public Packet(int protocol, List lTop3UserDistances, int temp) { + this.protocol = protocol; + this.listTop3UserDistance = lTop3UserDistances; + } + public Packet(int protocol, MultiModeUser user, float distance) { this.protocol = protocol; this.user = user; @@ -83,6 +89,9 @@ public Packet(int protocol, MultiModeUser user, float distance) { public long getGroupHistoryId() { return groupHistoryId; } + public List getListTop3UserDistance() { + return listTop3UserDistance; + } public void setGroupHistoryId(long groupHistoryId) { this.groupHistoryId = groupHistoryId; diff --git a/android/SocketServer/src/MultiMode/RoomManager.class b/android/SocketServer/src/MultiMode/RoomManager.class deleted file mode 100644 index 0294b391..00000000 Binary files a/android/SocketServer/src/MultiMode/RoomManager.class and /dev/null differ diff --git a/android/SocketServer/src/MultiMode/UserDistance.java b/android/SocketServer/src/MultiMode/UserDistance.java index d5c6b0ac..2e40fdab 100644 --- a/android/SocketServer/src/MultiMode/UserDistance.java +++ b/android/SocketServer/src/MultiMode/UserDistance.java @@ -3,7 +3,7 @@ import java.io.Serializable; public class UserDistance implements Serializable { - + private static final long serialVersionUID = 1931380L; MultiModeUser user; diff --git a/android/SocketServer/src/Server.java b/android/SocketServer/src/Server.java index ecd29b49..b19199be 100644 --- a/android/SocketServer/src/Server.java +++ b/android/SocketServer/src/Server.java @@ -5,12 +5,14 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Arrays; public class Server { private List allClientOutputStreams = new ArrayList<>(); private RoomManager roomManager = new RoomManager(); private ObjectOutputStream oos; private static final int PORT = 5001; private static final String SERVER_IP = "0.0.0.0"; + private static int num = 0; public Server() { try { @@ -99,9 +101,8 @@ private void handleClient(Socket socket, ObjectOutputStream oos) { System.out.println("user " + ((Packet) data).getUser().getNickName() + "'s update distance is " + distance); updateRoom.updateDistance(new UserDistance(user, distance)); - if(updateRoom.canUpdate()){ - System.out.println("update top3 distance : " + updateRoom); + System.out.println("update top3 distance"); updateTop3Users(Protocol.UPDATE_TOP3_STATES, updateRoom); } } else if (((Packet) data).getProtocol() == Protocol.START_GAME) { @@ -156,19 +157,19 @@ else if(data instanceof String){ private void updateTop3Users(int protocol, MultiModeRoom room){ UserDistance[] top3UserDistance = null; - System.out.println("here"); while(true){ top3UserDistance = room.getTop3UserDistance(); if(top3UserDistance != null){ break; } } - System.out.println("there"); - + /* for(int i = 0; i < top3UserDistance.length; i++){ System.out.println("user " + i + " : " + top3UserDistance[0].getUser().getNickName() + " , distance : " + top3UserDistance[0].getDistance()); } - Packet updateTop3Packet = new Packet(protocol, top3UserDistance); + */ + List lTop3UserDistances = new ArrayList(Arrays.asList(top3UserDistance)); + Packet updateTop3Packet = new Packet(protocol, lTop3UserDistances, 0); broadcastToRoomUsers(room, updateTop3Packet); } private void sendResultToRoomOwner(int protocol, MultiModeRoom room) throws IOException { @@ -179,7 +180,9 @@ private void sendResultToRoomOwner(int protocol, MultiModeRoom room) throws IOEx break; } } - Packet updateTop3Packet = new Packet(protocol, top3UserDistance); + List lTop3UserDistances = new ArrayList(Arrays.asList(top3UserDistance)); + System.out.println(lTop3UserDistances); + Packet updateTop3Packet = new Packet(protocol, lTop3UserDistances, 0); ObjectOutputStream oos = room.getRoomOwnerOos(); if (oos != null ){ @@ -205,7 +208,8 @@ private void sendResultTop3Users(int protocol, MultiModeRoom room, long groupHis for(int i = 0; i < top3UserDistance.length; i++){ System.out.println("user " + i + " : " + top3UserDistance[0].getUser().getNickName() + " , distance : " + top3UserDistance[0].getDistance()); } - Packet updateTop3Packet = new Packet(protocol, top3UserDistance, groupHistoryId); + List lTop3UserDistances = new ArrayList(Arrays.asList(top3UserDistance)); + Packet updateTop3Packet = new Packet(protocol, lTop3UserDistances, (int) groupHistoryId); broadcastToRoomUsers(room, updateTop3Packet); } @@ -226,9 +230,11 @@ private void broadcastToRoomUsers(MultiModeRoom room, Packet packet) { List oosList = room.getOutputStream(); System.out.println("numbers of oos list : "+oosList.size()); if(packet.getProtocol() == Protocol.UPDATE_TOP3_STATES){ - System.out.println("send top3 packet " + packet.getProtocol() + " 1st user is " + packet.getTop3UserDistance()[0].getUser().getNickName()); + for(int i = 0; i