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 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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.core.app.ActivityCompat;
  23. import androidx.core.content.ContextCompat;
  24. import androidx.fragment.app.FragmentActivity;
  25. import com.google.android.gms.location.FusedLocationProviderClient;
  26. import com.google.android.gms.location.LocationServices;
  27. import com.google.android.gms.maps.CameraUpdateFactory;
  28. import com.google.android.gms.maps.GoogleMap;
  29. import com.google.android.gms.maps.OnMapReadyCallback;
  30. import com.google.android.gms.maps.SupportMapFragment;
  31. import com.google.android.gms.maps.model.LatLng;
  32. import com.google.android.gms.maps.model.MarkerOptions;
  33. import com.google.android.gms.tasks.OnCompleteListener;
  34. import com.google.android.gms.tasks.Task;
  35. import com.google.firebase.database.DataSnapshot;
  36. import com.google.firebase.database.DatabaseError;
  37. import com.google.firebase.database.DatabaseReference;
  38. import com.google.firebase.database.FirebaseDatabase;
  39. import com.google.firebase.database.ValueEventListener;
  40. import java.time.LocalDateTime;
  41. import java.util.Calendar;
  42. import java.util.Date;
  43. import java.util.Objects;
  44. public class EarthquakeMapsActivity extends FragmentActivity implements OnMapReadyCallback {
  45. private static final String TAG = "MainActivity";
  46. private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
  47. private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
  48. private Boolean mLocationPermissionsGranted = false;
  49. private GoogleMap mMap;
  50. private FusedLocationProviderClient mFusedLocationProviderClient;
  51. Long currentTime;
  52. Location currentLocation;
  53. private DatabaseReference mDatenbank;
  54. private double breitengrad;
  55. private double laengengrad;
  56. private boolean useOwnGPS;
  57. private int indexID = 1;
  58. //##########################################################################################################################################################################
  59. //################################################################## vvv ShakeParameter vvv ##############################################################################
  60. private SensorManager mSensorManager;
  61. private static final float mUpperThreshold = 10.5f; // für Emulator auf 1.5 setzen
  62. private static final float mLowerThreshold = 5.5f; // für Emulator auf 0.5 setzen
  63. private static final long mShakeDetectionLockTimeMicroSeconds = 10000;
  64. private float mAccel;
  65. private float mAccelCurrent;
  66. private float mAccelLast;
  67. private boolean mShakeDetectionIsActive = false;
  68. private boolean mShakeDetected = false;
  69. //private boolean allowShakeEvent = true;
  70. //################################################################## ^^^^ ShakeParameter ^^^^ ############################################################################
  71. //##########################################################################################################################################################################
  72. @Override
  73. protected void onCreate(Bundle savedInstanceState) {
  74. super.onCreate(savedInstanceState);
  75. setContentView(R.layout.activity_earthquake_maps);
  76. getDataBaseValuesNoListener();
  77. sensorManagementInit();
  78. getLocationPermission();
  79. }
  80. //#####################################################################################################################################################################
  81. //################################################################## vvv ShakeCode vvv ##############################################################################
  82. private void sensorManagementInit()
  83. {
  84. TextView txtEarthquake = (TextView) findViewById(R.id.txtEarthquake);
  85. mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
  86. Objects.requireNonNull(mSensorManager).registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
  87. mAccel = 1f;
  88. mAccelCurrent = SensorManager.GRAVITY_EARTH;
  89. mAccelLast = SensorManager.GRAVITY_EARTH;
  90. mShakeDetectionIsActive = true;
  91. mShakeDetected = false;
  92. }
  93. private CountDownTimer mLockTimer = new CountDownTimer(mShakeDetectionLockTimeMicroSeconds, 1000)
  94. {
  95. public void onTick(long millisUntilFinished) {
  96. ((TextView) findViewById(R.id.txtEarthquake)).setText("Earthquake started! Detection locked for " + millisUntilFinished / 1000 + " s");
  97. }
  98. public void onFinish() {
  99. mShakeDetectionIsActive = true;
  100. mShakeDetected = false;
  101. Toast.makeText(getApplicationContext(), "Shake Detection unlocked", Toast.LENGTH_SHORT).show();
  102. ( (TextView) findViewById(R.id.txtEarthquake)).setText("Shake your Smartphone for an Earthquake");
  103. }
  104. };
  105. private final SensorEventListener mSensorListener = new SensorEventListener() {
  106. @Override
  107. public void onSensorChanged(SensorEvent event) {
  108. float x = event.values[0];
  109. float y = event.values[1];
  110. float z = event.values[2];
  111. mAccelLast = mAccelCurrent;
  112. mAccelCurrent = (float) Math.sqrt((double) (x * x + y * y + z * z));
  113. float delta = mAccelCurrent - mAccelLast;
  114. mAccel = mAccel * 0.9f + delta;
  115. // Log.d(TAG,"mAccel: "+ mAccel);
  116. if (mShakeDetectionIsActive) {
  117. if(Math.abs(mAccel) > mUpperThreshold) {
  118. new CountDownTimer(50, 10) {
  119. public void onTick(long millisUntilFinished) {
  120. if (Math.abs(mAccel) > mUpperThreshold) {
  121. mShakeDetectionIsActive = false;
  122. } else if (Math.abs(mAccel) < mLowerThreshold) {
  123. mShakeDetectionIsActive = true;
  124. this.cancel();
  125. }
  126. }
  127. public void onFinish() {
  128. if (Math.abs(mAccel) > mUpperThreshold) {
  129. mShakeDetectionIsActive = false;
  130. mShakeDetected = true;
  131. Toast.makeText(getApplicationContext(), "Shake event detected", Toast.LENGTH_SHORT).show();
  132. writeEarthquakeToDatabase();
  133. mLockTimer.start();
  134. } else {
  135. mShakeDetectionIsActive = true;
  136. mShakeDetected = false;
  137. }
  138. }
  139. }.start();
  140. }
  141. }
  142. }
  143. @Override
  144. public void onAccuracyChanged(Sensor sensor, int accuracy) {
  145. }
  146. };
  147. private void writeEarthquakeToDatabase()
  148. {
  149. setDataBaseValues();
  150. }
  151. @Override
  152. protected void onResume() {
  153. mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
  154. SensorManager.SENSOR_DELAY_NORMAL);
  155. super.onResume();
  156. }
  157. @Override
  158. protected void onPause() {
  159. mSensorManager.unregisterListener(mSensorListener);
  160. super.onPause();
  161. }
  162. //################################################################## ^^^^ ShakeCode ^^^^ ############################################################################
  163. //#####################################################################################################################################################################
  164. //#####################################################################################################################################################################
  165. //################################################################## vvv GPS Code vvv ###############################################################################
  166. private void getLocationPermission() {
  167. String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
  168. if (ContextCompat.checkSelfPermission(this.getApplicationContext(), FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
  169. mLocationPermissionsGranted = true;
  170. initMap();
  171. } else {
  172. ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
  173. }
  174. }
  175. @Override
  176. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  177. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  178. mLocationPermissionsGranted = false;
  179. switch (requestCode) {
  180. case LOCATION_PERMISSION_REQUEST_CODE: {
  181. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  182. mLocationPermissionsGranted = true;
  183. initMap(); //initalize or map
  184. }
  185. }
  186. }
  187. }
  188. private void initMap() {
  189. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
  190. mapFragment.getMapAsync(this);
  191. }
  192. @Override
  193. public void onMapReady(GoogleMap googleMap) {
  194. Toast.makeText(this, "Map is ready", Toast.LENGTH_SHORT).show();
  195. mMap = googleMap;
  196. if (mLocationPermissionsGranted) {
  197. getDeviceLocation();
  198. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
  199. != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
  200. Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  201. return;
  202. }
  203. mMap.setMyLocationEnabled(true);
  204. }
  205. // Add a marker in Sydney and move the camera
  206. //LatLng sydney = new LatLng(-34, 151);
  207. //mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
  208. //mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
  209. }
  210. private void getDeviceLocation(){
  211. mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
  212. try {
  213. if (mLocationPermissionsGranted){
  214. final Task location = mFusedLocationProviderClient.getLastLocation();
  215. location.addOnCompleteListener(new OnCompleteListener() {
  216. @Override
  217. public void onComplete(@NonNull Task task) {
  218. if (task.isSuccessful()){
  219. currentLocation = (Location) task.getResult();
  220. //currentTime = Calendar.getInstance().getTimeInMillis(); //verschoben in setDataBaseValues
  221. //Toast.makeText(EarthquakeMapsActivity.this, currentTime.toString(), Toast.LENGTH_SHORT).show(); //verschoben in setDataBaseValues
  222. if(useOwnGPS)
  223. {
  224. breitengrad = currentLocation.getLatitude();
  225. laengengrad = currentLocation.getLongitude();
  226. }
  227. currentLocation.setLatitude(breitengrad);
  228. currentLocation.setLongitude(laengengrad);
  229. moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),15f);
  230. //setDataBaseValues(); //Wurde verschoben zu Methode writeEarthquakeToDatabase
  231. }
  232. else{
  233. Toast.makeText(EarthquakeMapsActivity.this, "Current Location unavailable", Toast.LENGTH_SHORT).show();
  234. }
  235. }
  236. });
  237. }
  238. }catch (SecurityException e){
  239. Log.e(TAG,"Device Location not found" + e.getMessage());
  240. }
  241. }
  242. private void moveCamera(LatLng latlng, float zoom){
  243. Log.d(TAG,"Latitude: "+latlng.latitude+"Longitude: "+latlng.longitude);
  244. mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, zoom));
  245. }
  246. //################################################################## ^^^^ GPS Code ^^^^ #############################################################################
  247. //#####################################################################################################################################################################
  248. //#####################################################################################################################################################################
  249. //################################################################## vvv Datenbank Code vvv #########################################################################
  250. public void getDataBaseValuesNoListener()
  251. {
  252. mDatenbank = FirebaseDatabase.getInstance().getReference();
  253. mDatenbank.child("overviewAronTestetInDiesemAbschnitt").get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
  254. @Override
  255. public void onComplete(@NonNull Task<DataSnapshot> task) {
  256. if (!task.isSuccessful()) {
  257. System.out.println("Datenbankfehler in getDataBaseValuesNoListener");
  258. System.out.println("Error getting data: " + task.getException());
  259. }
  260. else {
  261. processDataBaseValues(task.getResult());
  262. }
  263. }
  264. });
  265. }
  266. public void processDataBaseValues (DataSnapshot data)
  267. {
  268. processDeviceIndex(data);
  269. processLocation(data);
  270. //processMessageDisplay(data);
  271. }
  272. public void processDeviceIndex(DataSnapshot data)
  273. {
  274. for (int i = 1; i<=4; i++)
  275. {
  276. String androidid = data.child("IDG" + i).child("androidid").getValue().toString();
  277. if(androidid.isEmpty())
  278. {
  279. indexID = i;
  280. break;
  281. }else
  282. {
  283. continue;
  284. }
  285. }
  286. }
  287. public void processLocation(DataSnapshot data)
  288. {
  289. String breitengradString = data.child("IDG" + indexID).child("breitengrad").getValue().toString();
  290. String laengengradString = data.child("IDG" + indexID).child("laengengrad").getValue().toString();
  291. if(breitengradString.isEmpty() || laengengradString.isEmpty())
  292. {
  293. useOwnGPS = true;
  294. }else{
  295. useOwnGPS = false;
  296. breitengrad = Double.parseDouble(breitengradString);
  297. laengengrad = Double.parseDouble(laengengradString);
  298. }
  299. }
  300. /*
  301. public void processMessageDisplay(DataSnapshot data)
  302. {
  303. String vibrationString;
  304. String androidid;
  305. for (int i = 1; i<=4; i++)
  306. {
  307. androidid = data.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + i).child("androidid").getValue().toString();
  308. vibrationString = data.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + i).child("vibration").getValue().toString();
  309. if((!androidid.isEmpty()) && vibrationString.equals("true"))
  310. {
  311. allowShakeEvent = false;
  312. }
  313. }
  314. }
  315. */
  316. public String getandroidid ()
  317. {
  318. return Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
  319. }
  320. public String getDeviceIpAdress ()
  321. {
  322. WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
  323. int ip = wm.getConnectionInfo().getIpAddress();
  324. String ipAddress = String.format("%d.%d.%d.%d",(ip & 0xff),(ip >> 8 & 0xff),(ip >> 16 & 0xff), (ip >> 24 & 0xff));
  325. return ipAddress;
  326. }
  327. public void setDataBaseValues()
  328. {
  329. mDatenbank = FirebaseDatabase.getInstance().getReference();
  330. mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + indexID).child("ip").setValue(getDeviceIpAdress());
  331. mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + indexID).child("vibration").setValue(true);
  332. mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + indexID).child("timestamp").setValue(Calendar.getInstance().getTimeInMillis());
  333. currentTime = Calendar.getInstance().getTimeInMillis();
  334. Toast.makeText(EarthquakeMapsActivity.this, currentTime.toString(), Toast.LENGTH_SHORT).show();
  335. mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + indexID).child("breitengrad").setValue(breitengrad);
  336. mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + indexID).child("laengengrad").setValue(laengengrad);
  337. mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + indexID).child("amplitude").setValue(1001);
  338. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  339. mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + indexID).child("localdatetime").setValue(LocalDateTime.now().toString());
  340. }
  341. mDatenbank.child("overviewAronTestetInDiesemAbschnitt").child("IDG" + indexID).child("androidid").setValue(getandroidid());
  342. }
  343. //################################################################## ^^^^ Datenbank Code ^^^^ #############################################################################
  344. //###########################################################################################################################################################################
  345. }
  346. //Evtl. Redundanter Code
  347. /*
  348. public void getDataBaseValues()
  349. {
  350. mDatenbank = FirebaseDatabase.getInstance().getReference();
  351. mDatenbank.addValueEventListener(new ValueEventListener() {
  352. @Override
  353. public void onDataChange(@NonNull DataSnapshot snapshot) {
  354. processDataBaseValues(snapshot); //Daten Snapshot, Übergabe an processDataBaseValues
  355. }
  356. @Override
  357. public void onCancelled(@NonNull DatabaseError error) {
  358. getDataBaseFailure(error);
  359. }
  360. });
  361. }
  362. public void getDataBaseFailure (DatabaseError error)
  363. {
  364. System.out.println("Datenbankfehler in gerDataBaseFailure");
  365. Log.w("Datenbankfehler", error.toException());
  366. }
  367. */