Projektarbeit
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

EarthquakeMapsActivity.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. package de.edotzlaff.schockwelle;
  2. import android.Manifest;
  3. import android.app.ActionBar;
  4. import android.content.Context;
  5. import android.content.pm.PackageManager;
  6. import android.hardware.Sensor;
  7. import android.hardware.SensorEvent;
  8. import android.hardware.SensorEventListener;
  9. import android.hardware.SensorManager;
  10. import android.location.Location;
  11. import android.net.wifi.WifiManager;
  12. import android.os.Build;
  13. import android.os.Bundle;
  14. import android.os.CountDownTimer;
  15. import android.os.SystemClock;
  16. import android.provider.ContactsContract;
  17. import android.provider.Settings;
  18. import android.util.Log;
  19. import android.widget.TextView;
  20. import android.widget.Toast;
  21. import androidx.annotation.NonNull;
  22. import androidx.annotation.RequiresApi;
  23. import androidx.core.app.ActivityCompat;
  24. import androidx.core.content.ContextCompat;
  25. import androidx.fragment.app.FragmentActivity;
  26. import com.google.android.gms.location.FusedLocationProviderClient;
  27. import com.google.android.gms.location.LocationServices;
  28. import com.google.android.gms.maps.CameraUpdateFactory;
  29. import com.google.android.gms.maps.GoogleMap;
  30. import com.google.android.gms.maps.OnMapReadyCallback;
  31. import com.google.android.gms.maps.SupportMapFragment;
  32. import com.google.android.gms.maps.model.LatLng;
  33. import com.google.android.gms.maps.model.MarkerOptions;
  34. import com.google.android.gms.tasks.OnCompleteListener;
  35. import com.google.android.gms.tasks.Task;
  36. import com.google.firebase.database.DataSnapshot;
  37. import com.google.firebase.database.DatabaseError;
  38. import com.google.firebase.database.DatabaseReference;
  39. import com.google.firebase.database.FirebaseDatabase;
  40. import com.google.firebase.database.ValueEventListener;
  41. import java.time.LocalDateTime;
  42. import java.time.ZoneOffset;
  43. import java.util.Calendar;
  44. import java.util.Date;
  45. import java.util.Objects;
  46. public class EarthquakeMapsActivity extends FragmentActivity implements OnMapReadyCallback {
  47. private static final String TAG = "MainActivity";
  48. private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
  49. private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
  50. private Boolean mLocationPermissionsGranted = false;
  51. private GoogleMap mMap;
  52. private FusedLocationProviderClient mFusedLocationProviderClient;
  53. Datenbank db = new Datenbank();
  54. Long currentTime;
  55. Location currentLocation;
  56. private DatabaseReference mDatenbank;
  57. private double breitengrad;
  58. private double laengengrad;
  59. private boolean useOwnGPS;
  60. private int indexID = 1;
  61. //##########################################################################################################################################################################
  62. //################################################################## vvv ShakeParameter vvv ##############################################################################
  63. private SensorManager mSensorManager;
  64. private static final float mUpperThreshold = 10.5f; // für Emulator auf 1.5 setzen TODO Aron
  65. private static final float mLowerThreshold = 5.5f; // für Emulator auf 0.5 setzen TODO Aron
  66. //private static final float mUpperThreshold = 10.5f; // für Emulator auf 1.5 setzen TODO Aron
  67. //private static final float mLowerThreshold = 5.5f; // für Emulator auf 0.5 setzen TODO Aron
  68. private static final long mShakeDetectionLockTimeMicroSeconds = 10000;
  69. private float mAccel;
  70. private float mAccelCurrent;
  71. private float mAccelLast;
  72. private boolean mShakeDetectionIsActive = false;
  73. private boolean mShakeDetected = false;
  74. private boolean allowShakeEvent = true;
  75. //################################################################## ^^^^ ShakeParameter ^^^^ ############################################################################
  76. //##########################################################################################################################################################################
  77. @Override
  78. protected void onCreate(Bundle savedInstanceState) {
  79. super.onCreate(savedInstanceState);
  80. setContentView(R.layout.activity_earthquake_maps);
  81. //Database Init
  82. db.setMyWaveSpeed(500);
  83. db.setMyAndroidID(Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID));
  84. WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
  85. int ip = wm.getConnectionInfo().getIpAddress();
  86. db.setMyIPadress(String.format("%d.%d.%d.%d",(ip & 0xff),(ip >> 8 & 0xff),(ip >> 16 & 0xff), (ip >> 24 & 0xff)));
  87. db.getDatafromDBnoListener();
  88. db.getDataBaseValuesWithListener();
  89. sensorManagementInit();
  90. getLocationPermission();
  91. }
  92. //#####################################################################################################################################################################
  93. //################################################################## vvv ShakeCode vvv ##############################################################################
  94. private void sensorManagementInit()
  95. {
  96. TextView txtEarthquake = (TextView) findViewById(R.id.txtEarthquake);
  97. mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
  98. Objects.requireNonNull(mSensorManager).registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
  99. mAccel = 1f;
  100. mAccelCurrent = SensorManager.GRAVITY_EARTH;
  101. mAccelLast = SensorManager.GRAVITY_EARTH;
  102. mShakeDetectionIsActive = true;
  103. mShakeDetected = false;
  104. }
  105. private CountDownTimer mLockTimer = new CountDownTimer(mShakeDetectionLockTimeMicroSeconds, 1000)
  106. {
  107. public void onTick(long millisUntilFinished) {
  108. ((TextView) findViewById(R.id.txtEarthquake)).setText("Earthquake started! Detection locked for " + millisUntilFinished / 1000 + " s");
  109. }
  110. public void onFinish() {
  111. mShakeDetectionIsActive = true;
  112. mShakeDetected = false;
  113. Toast.makeText(getApplicationContext(), "Shake Detection unlocked", Toast.LENGTH_SHORT).show();
  114. ( (TextView) findViewById(R.id.txtEarthquake)).setText("Shake your Smartphone for an Earthquake");
  115. }
  116. };
  117. private final SensorEventListener mSensorListener = new SensorEventListener() {
  118. @Override
  119. public void onSensorChanged(SensorEvent event) {
  120. float x = event.values[0];
  121. float y = event.values[1];
  122. float z = event.values[2];
  123. mAccelLast = mAccelCurrent;
  124. mAccelCurrent = (float) Math.sqrt((double) (x * x + y * y + z * z));
  125. float delta = mAccelCurrent - mAccelLast;
  126. mAccel = mAccel * 0.9f + delta;
  127. // Log.d(TAG,"mAccel: "+ mAccel);
  128. if (mShakeDetectionIsActive) {
  129. if(Math.abs(mAccel) > mUpperThreshold) {
  130. new CountDownTimer(50, 10) {
  131. public void onTick(long millisUntilFinished) {
  132. if (Math.abs(mAccel) > mUpperThreshold) {
  133. mShakeDetectionIsActive = false;
  134. } else if (Math.abs(mAccel) < mLowerThreshold) {
  135. mShakeDetectionIsActive = true;
  136. this.cancel();
  137. }
  138. }
  139. @RequiresApi(api = Build.VERSION_CODES.O)
  140. public void onFinish() {
  141. if (Math.abs(mAccel) > mUpperThreshold) {
  142. mShakeDetectionIsActive = false;
  143. mShakeDetected = true;
  144. Toast.makeText(getApplicationContext(), "Shake event detected", Toast.LENGTH_SHORT).show();
  145. writeEarthquakeToDatabase(); //TODO Aron
  146. mLockTimer.start();
  147. } else {
  148. mShakeDetectionIsActive = true;
  149. mShakeDetected = false;
  150. }
  151. }
  152. }.start();
  153. }
  154. }
  155. }
  156. @Override
  157. public void onAccuracyChanged(Sensor sensor, int accuracy) {
  158. }
  159. };
  160. @Override
  161. protected void onResume() {
  162. mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
  163. super.onResume();
  164. }
  165. @Override
  166. protected void onPause() {
  167. mSensorManager.unregisterListener(mSensorListener);
  168. super.onPause();
  169. }
  170. //################################################################## ^^^^ ShakeCode ^^^^ ############################################################################
  171. //#####################################################################################################################################################################
  172. //#####################################################################################################################################################################
  173. //################################################################## vvv GPS Code vvv ###############################################################################
  174. private void getLocationPermission() {
  175. String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
  176. if (ContextCompat.checkSelfPermission(this.getApplicationContext(), FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
  177. mLocationPermissionsGranted = true;
  178. initMap();
  179. } else {
  180. ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
  181. }
  182. }
  183. @Override
  184. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  185. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  186. mLocationPermissionsGranted = false;
  187. switch (requestCode) {
  188. case LOCATION_PERMISSION_REQUEST_CODE: {
  189. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  190. mLocationPermissionsGranted = true;
  191. initMap(); //initalize or map
  192. }
  193. }
  194. }
  195. }
  196. private void initMap() {
  197. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
  198. mapFragment.getMapAsync(this);
  199. }
  200. @Override
  201. public void onMapReady(GoogleMap googleMap) {
  202. Toast.makeText(this, "Map is ready", Toast.LENGTH_SHORT).show();
  203. mMap = googleMap;
  204. if (mLocationPermissionsGranted) {
  205. getDeviceLocation();
  206. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
  207. != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
  208. Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  209. return;
  210. }
  211. mMap.setMyLocationEnabled(true);
  212. }
  213. //TODO @ Eddy: Ich denke diesen Code brauchst du auch, oder? :D
  214. //Add a marker in Sydney and move the camera
  215. //LatLng sydney = new LatLng(-34, 151);
  216. //mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
  217. //mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
  218. }
  219. private void getDeviceLocation(){
  220. mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
  221. try {
  222. if (mLocationPermissionsGranted){
  223. final Task location = mFusedLocationProviderClient.getLastLocation();
  224. location.addOnCompleteListener(new OnCompleteListener() {
  225. @Override
  226. public void onComplete(@NonNull Task task) {
  227. if (task.isSuccessful()){
  228. currentLocation = (Location) task.getResult();
  229. System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + db.getNativeGPScaseInDB());
  230. if(db.getNativeGPScaseInDB())
  231. {
  232. System.out.println("---Eigene GPS Daten werden verwendet");
  233. breitengrad = currentLocation.getLatitude();
  234. laengengrad = currentLocation.getLongitude();
  235. db.setShakeBreitengrad(breitengrad);
  236. db.setShakeLaengengrad(laengengrad);
  237. }
  238. /*
  239. if(useOwnGPS) //TODO Aron
  240. {
  241. breitengrad = currentLocation.getLatitude();
  242. laengengrad = currentLocation.getLongitude();
  243. }
  244. */
  245. currentLocation.setLatitude(breitengrad);
  246. currentLocation.setLongitude(laengengrad);
  247. moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),15f);
  248. }
  249. else{
  250. Toast.makeText(EarthquakeMapsActivity.this, "Current Location unavailable", Toast.LENGTH_SHORT).show();
  251. }
  252. }
  253. });
  254. }
  255. }catch (SecurityException e){
  256. Log.e(TAG,"Device Location not found" + e.getMessage());
  257. }
  258. }
  259. private void moveCamera(LatLng latlng, float zoom){
  260. Log.d(TAG,"Latitude: "+latlng.latitude+"Longitude: "+latlng.longitude);
  261. mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, zoom));
  262. }
  263. //################################################################## ^^^^ GPS Code ^^^^ #############################################################################
  264. //#####################################################################################################################################################################
  265. //#####################################################################################################################################################################
  266. //################################################################## vvv Datenbank Code vvv #########################################################################
  267. @RequiresApi(api = Build.VERSION_CODES.O)
  268. private void writeEarthquakeToDatabase()
  269. {
  270. boolean nativeGPS;
  271. if(db.getNativeGPScaseInDB())
  272. {
  273. nativeGPS = true;
  274. }else{
  275. nativeGPS = false;
  276. }
  277. ///Evtl löschen und localDateTimeMod mit LocalDateTime.now(ZoneOffset.UTC).toString() ersetzen...
  278. String localDateTimeMod;
  279. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  280. localDateTimeMod = LocalDateTime.now(ZoneOffset.UTC).toString();
  281. } else
  282. {
  283. localDateTimeMod = LocalDateTime.now(ZoneOffset.UTC).toString();
  284. }
  285. for(int i=1; i<=db.getAmountOfIDGs(); i++)
  286. {
  287. if(!db.getStatusIFAndroidIDexistsInDB(db.getMyAndroidID()))
  288. {
  289. //Wenn eigenen androidID nicht in DB existiert
  290. Devices d1 = new Devices();
  291. d1 = new Devices(db.getMyAndroidID(),
  292. localDateTimeMod,
  293. db.getMyIPadress(),
  294. breitengrad,
  295. laengengrad,
  296. nativeGPS,
  297. true,
  298. Calendar.getInstance().getTimeInMillis(),
  299. 1000,
  300. db.getMyWaveSpeed());
  301. db.setIDGtoDevice(i,d1);
  302. break;
  303. }else{
  304. Toast.makeText(getApplicationContext(), "Gerät ist bereits in DB eingetragen!", Toast.LENGTH_SHORT).show();
  305. break;
  306. }
  307. }
  308. }
  309. }