· 4 years ago · May 20, 2021, 01:08 PM
1package com.example.safedistance;
2
3import android.Manifest;
4import android.annotation.SuppressLint;
5import android.app.Activity;
6import android.app.AlarmManager;
7import android.app.Notification;
8import android.app.NotificationChannel;
9import android.app.NotificationManager;
10import android.app.PendingIntent;
11import android.app.TaskStackBuilder;
12import android.bluetooth.BluetoothAdapter;
13import android.bluetooth.le.AdvertiseCallback;
14import android.bluetooth.le.AdvertiseSettings;
15import android.content.Context;
16import android.content.Intent;
17import android.content.pm.ActivityInfo;
18import android.content.pm.PackageManager;
19import android.database.Cursor;
20import android.database.sqlite.SQLiteDatabase;
21import android.graphics.Color;
22import android.graphics.drawable.ColorDrawable;
23import android.media.MediaPlayer;
24import android.os.Build;
25import android.os.Bundle;
26import android.os.RemoteException;
27import android.os.Vibrator;
28import android.text.SpannableString;
29import android.text.style.ForegroundColorSpan;
30import android.util.Log;
31import android.view.MenuItem;
32import android.view.View;
33import android.view.Window;
34import android.widget.ImageButton;
35import android.widget.ImageView;
36import android.widget.TextView;
37import android.widget.Toast;
38
39import androidx.appcompat.app.AppCompatActivity;
40import androidx.appcompat.widget.Toolbar;
41import androidx.core.app.ActivityCompat;
42import androidx.core.app.NotificationCompat;
43import androidx.core.app.NotificationManagerCompat;
44import androidx.drawerlayout.widget.DrawerLayout;
45import androidx.navigation.NavController;
46import androidx.navigation.Navigation;
47import androidx.navigation.ui.AppBarConfiguration;
48import androidx.navigation.ui.NavigationUI;
49
50import com.google.android.material.navigation.NavigationView;
51
52import org.altbeacon.beacon.Beacon;
53import org.altbeacon.beacon.BeaconConsumer;
54import org.altbeacon.beacon.BeaconManager;
55import org.altbeacon.beacon.BeaconParser;
56import org.altbeacon.beacon.BeaconTransmitter;
57import org.altbeacon.beacon.MonitorNotifier;
58import org.altbeacon.beacon.RangeNotifier;
59import org.altbeacon.beacon.Region;
60import org.altbeacon.beacon.service.RunningAverageRssiFilter;
61
62import java.io.IOException;
63import java.text.SimpleDateFormat;
64import java.util.Arrays;
65import java.util.Collection;
66import java.util.Date;
67
68import static android.app.PendingIntent.getActivity;
69import static com.example.safedistance.R.id.btn_info;
70import static com.example.safedistance.R.id.btn_stats;
71
72public class MainActivity extends AppCompatActivity implements BeaconConsumer, View.OnClickListener {
73 private Window window;
74
75 int estadoInterfaz = 0;
76
77 ImageButton button;
78
79 private PendingIntent pendingIntent;
80 private final static String CHANNEL_ID = "NOTIFICACION";
81 private final static int NOTIFICACION_ID = 0;
82 private int ciclos=5;
83 private AppBarConfiguration mAppBarConfiguration;
84
85 public static final String TAG = "BeaconTest";
86
87 private boolean hasVibrator, seHaReproducido=false;
88 int incumple = 0;
89 private boolean vibratePermission = true; //en algunos moviles retomaba la orden dada en el onpause y he añadido esta variable para que solo se active en el onresume
90 public static Vibrator vibrator;
91 private double distancia = 1.9;
92
93 double distanciaActual;
94
95 public static String color="default";
96
97 //variables para controlar contactos
98 public static int infracciones = 0;
99
100 //añadimos la variable distance se mantiene constante en todos sus decimales durante mas de n ciclos, se considera un cierre inesperado en la aplicacion vecina, y provocamos una desconexion
101
102 ImageView imageView;
103 MediaPlayer mp;
104 //private BackgroundPowerSaver backgroundPowerSaver;
105 private BeaconManager beaconManager;
106 String bluetoothAoD;
107 static NavigationView navigationView;
108 MenuItem menuItemContactos;
109 static MenuItem menuItemBluetooth;
110
111 public static SQLiteHelper sqLiteHelper;
112 Context context = this;
113 String fecha;
114
115 static TextView txtPuntos;
116
117
118 public void checkVibrator(){
119 // Obtiene instancia a Vibrator
120 vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
121 if (vibrator.hasVibrator() && vibratePermission) { //si la app está en pantalla, vibratePermisson = true
122 hasVibrator = true;
123 Log.v("VIBRATOR", "Vibrador detectado");
124 vibrar();
125 } else {//no tiene
126 hasVibrator = false;
127 Log.v("VIBRATOR", "Este dispositivo NO puede vibrar o se encuentra la app 'minimizada'.");
128 }
129 }
130
131 @SuppressLint("SourceLockedOrientationActivity")
132 @Override
133 protected void onCreate(Bundle savedInstanceState) {
134 super.onCreate(savedInstanceState);
135 setContentView(R.layout.activity_main);
136 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //con esta linea evito que la aplicacion rote si el usuario rota la pantalla
137 this.window = getWindow();
138
139 txtPuntos = findViewById(R.id.textPuntos);
140
141 notificar("inicio"); //notifico el inicio de la app
142
143 Intent sistemaPuntos = new Intent(this,ServicioPuntos.class);
144 this.startService(sistemaPuntos);
145
146 sqLiteHelper = new SQLiteHelper(this, "ItemsDB.sqlite", null, 1);
147 sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS INFRACCIONES (Id INTEGER PRIMARY KEY AUTOINCREMENT, fecha VARCHAR, cantidad LONG)");
148 sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS TPUNTOS (Id INTEGER PRIMARY KEY AUTOINCREMENT, fecha VARCHAR, puntos INTEGER)");
149 imageView = findViewById(R.id.circulo);
150 mp = MediaPlayer.create(this, R.raw.alerta);
151 bluetoothAoD = getString(R.string.menu_bluetooth);
152 navigationView = (NavigationView) findViewById(R.id.nav_view);
153
154 SimpleDateFormat fecha_de_hoy= new SimpleDateFormat("dd-MM-yyyy");
155 fecha = fecha_de_hoy.format(new Date());
156
157
158 Toolbar toolbar = findViewById(R.id.toolbar);
159 setSupportActionBar(toolbar);
160
161 DrawerLayout drawer = findViewById(R.id.drawer_layout);
162 // Passing each menu ID as a set of Ids because each menu should be considered as top level destinations.
163 mAppBarConfiguration = new AppBarConfiguration.Builder(R.id.nav_main, R.id.nav_mas_estadisticas).setDrawerLayout(drawer).build();
164 NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
165 NavigationUI.setupWithNavController(navigationView, navController);
166
167 Cursor cursor = sqLiteHelper.getReadableDatabase().rawQuery("SELECT cantidad FROM INFRACCIONES WHERE fecha = " + "'"+ fecha + "'", null);
168 if(cursor.moveToFirst() && cursor.getCount() >= 0) {
169 infracciones = (int) cursor.getLong(0);
170 }
171
172 SQLiteDatabase db = sqLiteHelper.getWritableDatabase();
173
174 Cursor cursorpt3 = sqLiteHelper.getReadableDatabase().rawQuery("SELECT puntos FROM TPUNTOS WHERE id = '1'", null);
175 if(cursorpt3.moveToFirst() && cursorpt3.getCount() >= 0) {
176 int ptos = cursorpt3.getInt(0);
177 txtPuntos.setText("Puntos: "+ptos);
178 }
179
180 String fech="";
181 Cursor cursorpt = sqLiteHelper.getReadableDatabase().rawQuery("SELECT fecha FROM TPUNTOS WHERE id = '1'", null);
182 if(cursorpt.moveToFirst() && cursorpt.getCount() >= 0) {
183 fech = cursorpt.getString(0);
184 }
185
186 if(fech.equals("")){
187 db.execSQL("INSERT INTO TPUNTOS VALUES (NULL, '"+fecha+"' ,"+Puntos.puntos_diarios+")");
188 txtPuntos.setText("Puntos: 100");
189
190 }else{
191 if(!fech.equals(fecha)) {
192 int ptos = 0;
193 Cursor cursorpt2 = sqLiteHelper.getReadableDatabase().rawQuery("select puntos from tpuntos where id = '1'", null);
194 db = sqLiteHelper.getWritableDatabase();
195 if (cursorpt2.moveToFirst() && cursorpt2.getCount() >= 0) {
196 ptos = cursorpt2.getInt(0);
197 }
198 ptos = ptos + Puntos.puntos_diarios;
199 db.execSQL("UPDATE TPUNTOS SET fecha ='" + fecha + "', puntos = '" + ptos + "' WHERE id = '1'");
200 txtPuntos.setText("Puntos: "+ptos);
201 }
202 }
203
204 //Se obtiene de los tres items, el título del item Contactos en una String
205 menuItemContactos = navigationView.getMenu().findItem(R.id.nav_infracciones);
206 menuItemContactos.setTitle("Infracciones: "+infracciones);
207 //Se obtiene el título para poder estilizarlo (en este caso cambiar de color el número)
208 SpannableString sContactos = new SpannableString(menuItemContactos.getTitle());
209 menuItemContactos.setTitle(sContactos+String.valueOf(infracciones));
210 sContactos.setSpan(new ForegroundColorSpan(Color.RED), 13, sContactos.length(), 0);
211 //Se asigna el título con el número en color rojo
212 menuItemContactos.setTitle(sContactos);
213
214 }
215 public static int ptos=0;
216 public static void updatePuntos(int penalizacion){
217 String fecha;
218 SimpleDateFormat fecha_de_hoy= new SimpleDateFormat("dd-MM-yyyy");
219 fecha = fecha_de_hoy.format(new Date());
220
221 Cursor cursorpt2 = sqLiteHelper.getReadableDatabase().rawQuery("select puntos from tpuntos where id = '1'", null);
222 SQLiteDatabase db = sqLiteHelper.getWritableDatabase();
223 if(cursorpt2.moveToFirst() && cursorpt2.getCount() >= 0) {
224 ptos = cursorpt2.getInt(0);
225 }
226 ptos = ptos - penalizacion;
227 db.execSQL("UPDATE TPUNTOS SET fecha ='" + fecha + "', puntos = '"+ptos+"' WHERE id = '1'");
228 txtPuntos.setText("Puntos: "+ptos);
229 }
230
231 @Override
232 public void onClick(View view){
233 //Se obtiene el id de la Image View pulsada
234 switch(view.getId()){
235 case btn_info:
236 //Se inicia una nueva Activity con la información de la app
237 Intent intent = new Intent (view.getContext(), InfoActivity.class);
238 startActivityForResult(intent, 0);
239 break;
240 case R.id.btn_stats:
241 //Se muestra el Navigation Drawer
242 NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
243 if (!NavigationUI.navigateUp(navController, mAppBarConfiguration)) {
244 super.onSupportNavigateUp();
245 }
246 //Otra forma de escribir la if anterior:
247 break;
248 }
249 }
250
251
252 private void notificar(String color) {
253 if (SettingsFragment.notificaciones_enabled || color == "inicio") {
254 setPendingIntent();
255 createNotificationChannel();
256 createNotification(color);
257 }
258 }
259
260 private void setPendingIntent() {
261 Intent intent = new Intent(this, MainActivity.class);
262 TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
263 stackBuilder.addParentStack(MainActivity.class);
264 stackBuilder.addNextIntent(intent);
265 pendingIntent = stackBuilder.getPendingIntent(1, PendingIntent.FLAG_UPDATE_CURRENT);
266
267 }
268
269 private void createNotificationChannel() {
270 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
271 CharSequence name = "Notificacion";
272 NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH);
273 NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
274 notificationManager.createNotificationChannel(notificationChannel);
275 }
276 }
277
278 private void createNotification(String color) {
279 NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
280 builder.setSmallIcon(R.drawable.ic_stat_onesignal_default);
281 builder.setContentTitle("SafeDistance");
282 builder.setPriority(NotificationCompat.PRIORITY_HIGH);
283 builder.setLights(Color.BLUE,1000,100);
284 builder.setDefaults(Notification.DEFAULT_SOUND);
285
286 switch (color){
287 case "red":
288 builder.setColor(Color.RED);
289 builder.setContentText("¡Estás a menos de 2 metros de alguien!");
290 break;
291 case "yellow":
292 builder.setColor(Color.parseColor("#F6C918"));
293 builder.setContentText("Se han detectado dispositivos cercanos.");
294 break;
295 case "inicio":
296 builder.setContentText("¡La aplicación ha sido iniciada!");
297 break;
298 default:
299 builder.setColor(Color.parseColor("#0066a1"));
300 builder.setContentText("No se detectan dispositivos cercanos.");
301 break;
302
303 }
304 builder.setContentIntent(pendingIntent);
305
306 NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(getApplicationContext());
307 notificationManagerCompat.notify(NOTIFICACION_ID, builder.build());
308 }
309
310
311 public static void checkPermissions(Activity activity, Context context){
312 int PERMISSION_ALL = 1;
313 String[] PERMISSIONS = {
314 Manifest.permission.ACCESS_FINE_LOCATION,
315 Manifest.permission.BLUETOOTH,
316 Manifest.permission.BLUETOOTH_ADMIN,
317 };
318
319 if (!hasPermissions(context, PERMISSIONS)){
320 ActivityCompat.requestPermissions( activity, PERMISSIONS, PERMISSION_ALL);
321 }
322 }
323
324 public static boolean hasPermissions(Context context, String... permissions) {
325 if (context != null && permissions != null) {
326 for (String permission : permissions) {
327 if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
328 return false;
329 }
330 }
331 }
332 return true;
333 }
334
335 @Override
336 protected void onStart() {
337 super.onStart();
338 BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
339 if (bluetoothAdapter == null) { //comprobamos si el dispositivo tiene Bluetooth para que la app no falle al iniciarla en maquinas virtuales o en dispositivos muy antiguos
340 color="black";
341 MainFragment.cambiarCirculo(color);
342 cambiarColores(color);
343 }else {
344 if (!bluetoothAdapter.isEnabled()) {
345 bluetoothAdapter.enable();
346 //reiniciar la app para evitar un reinicio manual
347 doRestart(this);
348 }
349
350 // Pedir permisos (necesario en versiones nuevas de Android)
351 checkPermissions(MainActivity.this, this);
352
353 bluetoothActivado();
354
355 beaconManager = BeaconManager.getInstanceForApplication(this);
356 beaconManager.bind(this);
357 //backgroundPowerSaver = new BackgroundPowerSaver(this);
358 //Iniciar transmisión de beacons
359 startBeaconTransmission();
360 }
361 }
362
363 public static void bluetoothDesactivado(){
364 //Se obtiene de los tres items, el título del item Bluetooth en una String
365 menuItemBluetooth = navigationView.getMenu().findItem(R.id.nav_bluetooth);
366 //Como el Bluetooh está desactivado ahora, se asigna al título un nuevo nombre, "Bluetooth: Desactivado"
367 menuItemBluetooth.setTitle("Bluetooth: Desactivado");
368 //Se obtiene de nuevo el título (cambiado) para poder estilizarlo (en este caso cambiar de color unas letras)
369 SpannableString sBluetooth = new SpannableString(menuItemBluetooth.getTitle());
370 sBluetooth.setSpan(new ForegroundColorSpan(Color.RED), 11, sBluetooth.length(), 0);
371 //Se asigna una vez más el nuevo título que tendrá ciertas letras de color rojo
372 menuItemBluetooth.setTitle(sBluetooth);
373 //cambiarColores("black");
374 }
375
376 public static void bluetoothActivado(){
377 //Se obtiene de los tres items, el título del item Bluetooth en una String
378 menuItemBluetooth = navigationView.getMenu().findItem(R.id.nav_bluetooth);
379 //Se comprueba si el título del item Bluetooth es distinto a "Bluetooth: Activado" para que
380 //no esté cambiando el título cada vez
381 if(!menuItemBluetooth.equals("Bluetooth: Activado")){
382 //Como el Bluetooh está activado ahora, se asigna al título un nuevo nombre, "Bluetooth: Activado"
383 menuItemBluetooth.setTitle("Bluetooth: Activado");
384 //Se obtiene de nuevo el título (cambiado) para poder estilizarlo (en este caso cambiar de color unas letras)
385 SpannableString sBluetooth = new SpannableString(menuItemBluetooth.getTitle());
386 sBluetooth.setSpan(new ForegroundColorSpan(Color.GREEN), 11, sBluetooth.length(), 0);
387 //Se asigna una vez más el nuevo título que tendrá ciertas letras de color verde
388 menuItemBluetooth.setTitle(sBluetooth);
389 }
390 }
391
392 private void startBeaconTransmission() {
393 Beacon beacon = new Beacon.Builder()
394 .setId1("2f234454-cf6d-4a0f-adf2-f4911ba9ffa6")
395 .setId2("1")
396 .setId3("2")
397 .setManufacturer(0x0118) // Radius Networks. Change this for other beacon layouts
398 .setTxPower(-59)
399 .setDataFields(Arrays.asList(new Long[] {0l})) // Remove this for beacon layouts without d: fields
400 .build();
401 // Change the layout below for other beacon types
402 BeaconManager.setRssiFilterImplClass(RunningAverageRssiFilter.class);
403 RunningAverageRssiFilter.setSampleExpirationMilliseconds(1000l);
404
405 //beaconManager.setBackgroundScanPeriod(1100l);
406 BeaconParser beaconParser = new BeaconParser().setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25");
407 BeaconTransmitter beaconTransmitter = new BeaconTransmitter(getApplicationContext(), beaconParser);
408 beaconTransmitter.startAdvertising(beacon, new AdvertiseCallback() {
409 @Override
410 public void onStartFailure(int errorCode) {
411 Log.e(TAG, "Advertisement start failed with code: " + errorCode);
412 }
413 @Override
414 public void onStartSuccess(AdvertiseSettings settingsInEffect) {
415 //se inicia la conexion con un movil cercano, se entra en modo precaución donde la aplicación se pone en amarillo
416 Log.i(TAG, "Advertisement start succeeded.");
417 }
418 });
419 }
420
421 public void vibrar(){
422 if(SettingsFragment.vibration_enabled) {
423 long[] pattern = {1000, 400, //sleep
424 1000, //vibrate
425 400, 1000, 400, 1000, 400};
426 // con -1 se indica desactivar repeticion del patron
427 vibrator.vibrate(pattern, 0);
428 }
429 }
430
431 @Override
432 public void onBeaconServiceConnect() {
433
434 beaconManager.removeAllMonitorNotifiers();
435 beaconManager.addMonitorNotifier(new MonitorNotifier() {
436 @Override
437 public void didEnterRegion(Region region) {
438 //Log.i(TAG, "Encontrado beacon: " + region.getUniqueId());
439 }
440
441 @Override
442 public void didExitRegion(Region region) {
443 if(vibrator!=null) {
444 vibrator.cancel();
445 }
446 color="default";
447 MainFragment.cambiarCirculo(color);
448 ciclos=5;
449
450 cambiarColores("");
451 notificar("");
452 seHaReproducido = false;
453 estadoInterfaz = 0;
454 }
455
456 @Override
457 public void didDetermineStateForRegion(int state, Region region) {
458 //Log.i(TAG, "I have just switched from seeing/not seeing beacons: " + state);
459 }
460 });
461
462
463 try {
464 Region region = new Region("testRegion", null, null, null);
465 beaconManager.startMonitoringBeaconsInRegion(region);
466 } catch (RemoteException e) {
467 e.printStackTrace();
468 }
469
470
471 beaconManager.removeAllRangeNotifiers();
472 beaconManager.addRangeNotifier(new RangeNotifier() {
473 @Override
474 public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
475 if (beacons.isEmpty()) {
476 return;
477 }
478 for (Beacon beacon : beacons) {
479 distanciaActual = beacon.getDistance();
480 if(distanciaActual<distancia){
481 incumple = 0;
482 if(ciclos<5) {
483 ciclos++;
484 }else{
485 Puntos.aplicarInfraccion();
486 ciclos=0;
487 }
488 if(estadoInterfaz != 1){
489 accionesIncumple();
490 }
491 }else{
492 ciclos=5;
493 incumple = 1;
494 if(estadoInterfaz != 2) {
495 accionesIncumple();
496 }
497 }
498
499 }
500 }
501 });
502 try {
503 Region region = new Region("regionDePrueba", null, null, null);
504 beaconManager.startRangingBeaconsInRegion(region);
505 } catch (RemoteException e) {
506 e.printStackTrace();
507 }
508
509 }
510
511 private void accionesIncumple() {
512 switch (incumple){
513 case 0:
514 estadoInterfaz = 1;
515 checkVibrator();
516 color="red";
517 MainFragment.cambiarCirculo(color);
518 notificar(color);
519 cambiarColores(color);
520 alerta();
521 break;
522 case 1:
523 estadoInterfaz = 2;
524 if(vibrator!=null) { //compruebo si el dispositivo está vibrando antes de cancelarlo
525 vibrator.cancel();
526 }
527 color="yellow";
528 Puntos.vuelta = 0;
529 MainFragment.cambiarCirculo(color);
530 notificar(color);
531 cambiarColores(color);
532 seHaReproducido = false;
533 break;
534 }
535 }
536
537
538 private void updateStringInfracciones() {
539 //Se obtiene de los tres items, el título del item Contactos en una String
540 menuItemContactos = navigationView.getMenu().findItem(R.id.nav_infracciones);
541 menuItemContactos.setTitle("Infracciones: "+infracciones);
542 //Se obtiene el título para poder estilizarlo (en este caso cambiar de color el número)
543 SpannableString sContactos = new SpannableString(menuItemContactos.getTitle());
544 menuItemContactos.setTitle(sContactos+String.valueOf(infracciones));
545 sContactos.setSpan(new ForegroundColorSpan(Color.RED), 13, sContactos.length(), 0);
546 //Se asigna el título con el número en color rojo
547 menuItemContactos.setTitle(sContactos);
548 }
549
550 private void cambiarColores(String color) {
551 switch (color){
552 case "yellow":
553 getWindow().setNavigationBarColor(Color.parseColor("#F6C918"));
554 getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F6C918")));
555 window.setStatusBarColor(Color.parseColor("#F6C918"));
556 button = findViewById(btn_info);
557 button.setBackgroundResource(R.drawable.infoyellow);
558 button = findViewById(btn_stats);
559 button.setBackgroundResource(R.drawable.menuyellow);
560 txtPuntos.setTextColor(Color.parseColor("#F6C918"));
561 break;
562 case "red":
563 getWindow().setNavigationBarColor(Color.RED);
564 getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.RED));
565 window.setStatusBarColor(Color.RED);
566 button = findViewById(btn_info);
567 button.setBackgroundResource(R.drawable.infored);
568 button = findViewById(btn_stats);
569 button.setBackgroundResource(R.drawable.menured);
570 txtPuntos.setTextColor(Color.RED);
571 break;
572 case "black":
573 getWindow().setNavigationBarColor(Color.parseColor("#1C1C1C"));
574 getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#1C1C1C")));
575 window.setStatusBarColor(Color.parseColor("#1C1C1C"));
576 button = findViewById(btn_info);
577 button.setBackgroundResource(R.drawable.infoblack);
578 button = findViewById(btn_stats);
579 button.setBackgroundResource(R.drawable.menublack);
580 txtPuntos.setTextColor(Color.parseColor("#1C1C1C"));
581 txtPuntos.setText("Dispositivo incompatible");
582 break;
583 default:
584 getWindow().setNavigationBarColor(Color.parseColor("#0066a1"));
585 getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#0066a1")));
586 window.setStatusBarColor(Color.parseColor("#0066a1"));
587 button = findViewById(btn_info);
588 button.setBackgroundResource(R.drawable.info_icon);
589 button = findViewById(btn_stats);
590 button.setBackgroundResource(R.drawable.menu_icon);
591 txtPuntos.setTextColor(Color.parseColor("#0066a1"));
592 break;
593 }
594 }
595
596 public void alerta(){
597 if(SettingsFragment.volume_enabled) {
598 if (mp != null && mp.isPlaying() && seHaReproducido == true) {
599 mp.stop();
600 try {
601 mp.prepare();
602 } catch (IOException ioe) {
603 ioe.printStackTrace();
604 } catch (IllegalStateException ise) {
605 ise.printStackTrace();
606 }
607 } else {
608 if (vibratePermission && !seHaReproducido) {
609 mp.start();
610 ++infracciones;
611 updateStringInfracciones();
612 long cont=0;
613 Cursor cursor = sqLiteHelper.getReadableDatabase().rawQuery("SELECT cantidad FROM INFRACCIONES WHERE fecha = " + "'"+ fecha + "'", null);
614 if(cursor.moveToFirst() && cursor.getCount() >= 0) {
615 cont = cursor.getLong(0);
616 }
617 if (cont==0){
618 try{
619 insercion(fecha);
620 }catch(Exception e) {
621 Toast.makeText(context, "Incorrecta inserción.", Toast.LENGTH_LONG).show();
622 }
623 }else{
624 try{
625 update(fecha);
626 }catch(Exception e){
627 Toast.makeText(context, "Incorrecta actualización.", Toast.LENGTH_LONG).show();
628 }
629 }
630 }
631 seHaReproducido = true;
632 }
633 }
634 }
635
636 public void insercion(String fecha){
637 Long cantidad = Long.valueOf(infracciones);
638 try{
639 sqLiteHelper.insertData(
640 fecha,
641 cantidad
642 );
643 }catch(Exception e){
644 Toast.makeText(this, "Incorrecta inserción.", Toast.LENGTH_LONG).show();
645 }
646 }
647
648 public void update(String fecha){
649 SQLiteDatabase db = sqLiteHelper.getWritableDatabase();
650 String sql = "UPDATE INFRACCIONES SET cantidad ='" + infracciones + "' WHERE fecha =" + "'"+ fecha + "'";
651 db.execSQL(sql);
652 }
653
654 static long infraccionSieteDias(){
655 double resta = totalId() - 6;
656 Cursor cursor = sqLiteHelper.getReadableDatabase().rawQuery("SELECT sum(cantidad) FROM infracciones WHERE id>="+resta+" AND id<="+totalId(), null);// "+restaId(7)
657 long numinfracciones = 0;
658 if(cursor.moveToFirst() && cursor.getCount() >= 0) {
659 numinfracciones = cursor.getLong(0);
660 }
661 return numinfracciones;
662 }
663
664 static long infraccionQuinceDias(){
665 long numinfracciones = 0;
666 if(totalId() <=15){
667 Cursor cursor = sqLiteHelper.getReadableDatabase().rawQuery("SELECT sum(cantidad) FROM infracciones", null);
668 if(cursor.moveToFirst() && cursor.getCount() >= 0) {
669 numinfracciones = cursor.getLong(0);
670 }
671 }else{
672 double resta = totalId() - 14;
673 Cursor cursor = sqLiteHelper.getReadableDatabase().rawQuery("SELECT sum(cantidad) FROM infracciones WHERE id>="+resta+" AND id<="+totalId(), null);
674 if(cursor.moveToFirst() && cursor.getCount() >= 0) {
675 numinfracciones = cursor.getLong(0);
676 }
677 }
678 return numinfracciones;
679 }
680
681 static long infraccionTreintaDias(){
682 long numinfracciones = 0;
683 if(totalId() <=30){
684 Cursor cursor = sqLiteHelper.getReadableDatabase().rawQuery("SELECT sum(cantidad) FROM infracciones", null);
685 if(cursor.moveToFirst() && cursor.getCount() >= 0) {
686 numinfracciones = cursor.getLong(0);
687 }
688 }else{
689 double resta = totalId() - 29;
690 Cursor cursor = sqLiteHelper.getReadableDatabase().rawQuery("SELECT sum(cantidad) FROM infracciones WHERE id>="+resta+" AND id<="+totalId(), null);
691 if(cursor.moveToFirst() && cursor.getCount() >= 0) {
692 numinfracciones = cursor.getLong(0);
693 }
694 }
695 return numinfracciones;
696 }
697
698 public static double totalId(){
699 Cursor cursor = sqLiteHelper.getReadableDatabase().rawQuery("SELECT count(*) FROM infracciones", null);
700 double totalId = 0;
701 if(cursor.moveToFirst() && cursor.getCount() >= 0) {
702 totalId = cursor.getDouble(0);
703 }
704 //totalId = totalId - numDias;
705 return totalId;
706 }
707
708 @Override
709 public void onBackPressed() {
710 super.onBackPressed();
711 if(mp.isPlaying()){
712 mp.stop();
713 mp.release();
714 }
715 if(vibrator!=null) {
716 vibrator.cancel();
717 }
718 SettingsFragment.notificaciones_enabled = true;
719 BeaconManager.getInstanceForApplication(this).unbind(this);
720 }
721
722 protected void onResume() {
723 super.onResume();
724 vibratePermission = true; //cuando el usuario vuelve a la app se reactiva el "permiso" para vibrar
725 SettingsFragment.notificaciones_enabled = false;
726 }
727
728 protected void onPause() {
729 super.onPause();
730 if (vibrator!=null) {
731 vibrator.cancel();
732 }
733 vibratePermission = false; //niego el permiso para vibrar
734 SettingsFragment.notificaciones_enabled = true;
735 }
736
737 @Override
738 protected void onDestroy() {
739 super.onDestroy();
740 BeaconManager.getInstanceForApplication(this).unbind(this);
741 Intent sistemaPuntos = new Intent(this,ServicioPuntos.class);
742 this.stopService(sistemaPuntos);
743
744 }
745
746 public static void doRestart(Context c) {
747 try {
748 //check if the context is given
749 if (c != null) {
750 //fetch the packagemanager so we can get the default launch activity
751 // (you can replace this intent with any other activity if you want
752 PackageManager pm = c.getPackageManager();
753 //check if we got the PackageManager
754 if (pm != null) {
755 //create the intent with the default start activity for your application
756 Intent mStartActivity = pm.getLaunchIntentForPackage(c.getPackageName());
757 if (mStartActivity != null) {
758 mStartActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
759 //create a pending intent so the application is restarted after System.exit(0) was called.
760 // We use an AlarmManager to call this intent in 100ms
761 int mPendingIntentId = 223344;
762 PendingIntent mPendingIntent = getActivity(c, mPendingIntentId, mStartActivity,PendingIntent.FLAG_CANCEL_CURRENT);
763 AlarmManager mgr = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
764 mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 10, mPendingIntent);
765 //kill the application
766 System.exit(0);
767 } else {
768 Log.e(TAG, "Was not able to restart application, mStartActivity null");
769 }
770 } else {
771 Log.e(TAG, "Was not able to restart application, PM null");
772 }
773 } else {
774 Log.e(TAG, "Was not able to restart application, Context null");
775 }
776 } catch (Exception ex) {
777 Log.e(TAG, "Was not able to restart application");
778 }
779 }
780
781
782}