Jump to content

juniormelo26

Members
  • Content count

    3
  • Joined

  • Last visited

Community Reputation

0 Comum

About juniormelo26

  1. juniormelo26

    Service Android

    Boa noite, pessoal estou desenvolvendo um App Android que pega ( Latitude, longitude e Imei ) a cada 5 minutos e envia ao banco. até ai tudo certo, o service executa bem certinho quando o app está com a tela habilitada ou no caso está sendo utilizado, queria que o App mesmo com a tela bloqueada realize o serviço. foi criado um service, broadcastReceive. Segue service package com.example.junior.buskrastreamentogps; import android.Manifest; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.support.annotation.RequiresApi; import android.support.v4.app.ActivityCompat; import android.support.v4.app.NotificationCompat; import android.telephony.TelephonyManager; import android.util.Log; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import java.util.HashMap; import java.util.Map; public class service extends Service { int mStartMode; // indicates how to behave if the service is killed IBinder mBinder; // interface for clients that bind boolean mAllowRebind; // indicates whether onRebind should be used private Handler mHandler = new Handler(); // Creating Volley RequestQueue. RequestQueue requestQueue; // Create string variable to hold the EditText Value. String ImeiHolder, LatitudeHolder,LongitudeHolder, tmpLat, tmpLon,tmpImei; // ENDEREÇO DO SERVIDOR E PAGINA RESPONSAVEL POR RECEBER DADOS DO APP E INSERIR NO BANCO String HttpUrl = "http://xxxxxxxx/inserir.php"; /** Called when the activity is first created. */ @TargetApi(Build.VERSION_CODES.O) @Override public void onCreate() { super.onCreate(); Context context = getApplicationContext(); //NOTIFICAÇÃO PARA O USUARIO String CHANNEL_ID = "my_channel_01"; // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is new and not in the support library if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = getString(R.string.app_name); // String description = getString(R.string.channel_description); int importance = NotificationManager.IMPORTANCE_HIGH; NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance); //channel.setDescription(description); // Register the channel with the system; you can't change the importance // or other notification behaviors after this NotificationManager notificationManager = getSystemService(NotificationManager.class); PendingIntent p = PendingIntent.getActivity(this, 1, new Intent(this, service.class), 0); notificationManager.createNotificationChannel(channel); }else { NotificationCompat.Builder builder = new NotificationCompat.Builder(service.this, CHANNEL_ID) .setSmallIcon(R.drawable.logo_busk) .setContentTitle("Notificação") .setContentText("Bem vindo") .setPriority(NotificationCompat.PRIORITY_HIGH); } Log.d("TAG", "Serviço Criado, Notificação enviada"); Toast.makeText(service.this, "Proteção Criada", Toast.LENGTH_SHORT).show(); // Creating Volley newRequestQueue . requestQueue = Volley.newRequestQueue(service.this); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d("TAG", "Comando Service inciado no OnStartComannd."); Toast.makeText(service.this, "Proteção Incializada", Toast.LENGTH_SHORT).show(); Imei(); EnviarLocalizacao.run(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { String CHANNEL_ID = "my_channel_01"; Notification.Builder builder = new Notification.Builder(service.this,CHANNEL_ID) .setContentTitle(getString(R.string.app_name)) .setContentText("Notificação") .setAutoCancel(true); Notification notification = builder.build(); startForeground(1, notification); } else { NotificationCompat.Builder builder = new NotificationCompat.Builder(service.this) .setContentTitle(getString(R.string.app_name)) .setContentText("Notificação") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setAutoCancel(true); Notification notification = builder.build(); startForeground(1, notification); } return mStartMode; } private Runnable EnviarLocalizacao = new Runnable() { @RequiresApi(api = Build.VERSION_CODES.O) @Override public void run() { configurarServico(); //Toast.makeText(MainActivity.this, "This is a delayed toast", Toast.LENGTH_SHORT).show(); mHandler.postDelayed(this, 180000); } }; private void Imei() { final TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { return; } @SuppressLint("HardwareIds") final String imei = telephonyManager.getDeviceId(); tmpImei = imei.toString(); ImeiHolder = tmpImei.trim(); } public void configurarServico() { try { final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { double latPoint = location.getLatitude(); double lngPoint = location.getLongitude(); tmpLat = Double.toString(latPoint); tmpLon = Double.toString(lngPoint); LatitudeHolder = tmpLat.trim(); LongitudeHolder = tmpLon.trim(); insert_banco(); Imei(); Toast.makeText(service.this, "Proteção Sincronizada!", Toast.LENGTH_SHORT).show(); locationManager.removeUpdates(this); } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } }; locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, locationListener); }catch(SecurityException ex){ //Toast.makeText(service.this, "Você precisa ativar a permissão do GPS", Toast.LENGTH_LONG).show(); } } public void insert_banco() { // Creating string request with post method. StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl, new Response.Listener<String>() { @Override public void onResponse(String ServerResponse) { // Showing response message coming from server. //Toast.makeText(service.this, ServerResponse, Toast.LENGTH_LONG).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { // Showing error message if something goes wrong. //Toast.makeText(service.this, volleyError.toString(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() { // Creating Map String Params. Map<String, String> params = new HashMap<String, String>(); // Adding All values to Params. params.put("imei", ImeiHolder); params.put("lat", LatitudeHolder); params.put("lng", LongitudeHolder); return params; } }; // Creating RequestQueue. RequestQueue requestQueue = Volley.newRequestQueue(service.this); // Adding the StringRequest object into requestQueue. requestQueue.add(stringRequest); } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); Log.d("TAG", "Serviço inciado no onStart."); configurarServico(); } //localização @Override public IBinder onBind(Intent arg0) { return mBinder; } }
  2. juniormelo26

    Como exibir input com select e enviar valor ao banco

    Bom dia, alguém pode me ajudar por favor?
  3. <script src="js/sweetalert.min.js"></script> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <?php header('Content-Type: text/html; charset=utf-8'); session_start(); include_once("seguranca.php"); include_once("conexao.php"); seguranca_adm(); if( count($_POST) > 0){ $id_tip_mod = $_POST['id_tip_mod']; $Serial = $_POST['serial']; $defeito = $_POST['defeito']; $site = $_POST['site']; $enviado = $_POST['enviado']; $recebido = $_POST['recebido']; $os_gerada = $_POST['os_gerada']; $data_cadastro = $_POST['data_cadastro']; $hora_cadastro = $_POST['hora_cadastro']; $cadastrado = $_POST['cadastrado']; //VERIFICAR SE O MÓDULO J�? EST�? CADASTRADO COM DEFEITO E NAO FOI BAIXADO $sql = ("SELECT * FROM modulo WHERE serial <> 'SN' AND serial = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE('" . $_POST[serial] . "', '.',''),',',''),'-',''),'/',''),':','') AND cadastrado = 'SIM' AND recebido = 'NAO'"); $res = mysqli_query($conn, $sql); if (mysqli_num_rows($res) >= 1) { $mensagemLog = "Tentativa de Cadastrar Módulo com defeito sem sucesso. Módulo -> $_POST[serial] já cadastrado!"; $ipLog = $_SERVER['REMOTE_ADDR']; $insereLog = ("INSERT INTO logs (usuarioLog, mensagemLog, ipUsuario, dataLog, horaLog) VALUES ('".$_SESSION[usuarioLogin]."','$mensagemLog', '$ipLog', '$data_cadastro', '$hora_cadastro')"); $resultadoLog = mysqli_query($conn, $insereLog); //echo'<br><br><br><center><div id="sumirDiv" class="alert alert-danger"><h4>ERRO!</h4><br><h4>MÓDULO J�? CADASTRADO</h4></div></center>'; ?> <script type="text/javascript"> swal({ buttons: false, title: "Erro", text: "Módulo já cadastrado", icon: "error", closeOnConfirm: false, }); setTimeout(function() { window.location = 'principal.php?link=2'; }, 4000); </script> <?php } else { $result = ("INSERT INTO modulo (id_tip_mod, serial, defeito, site, tecnico, enviado, recebido, os_gerada, data_cadastro, hora_cadastro, cadastrado) VALUES ('$id_tip_mod',UPPER(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE('" . $_POST[serial] . "', '.',''),',',''),'-',''),'/',''),':','')),UPPER('$defeito'),UPPER('$site'),UPPER('" . $_SESSION[usuarioNome] . "'), '$enviado', '$recebido', '$os_gerada', '$data_cadastro', '$hora_cadastro', '$cadastrado')"); $resultado = mysqli_query($conn, $result); $mensagemLog = "Cadastro do Módulo com defeito realizado com sucesso. Módulo cadastrado -> $_POST[serial]"; $ipLog = $_SERVER['REMOTE_ADDR']; $insereLog = ("INSERT INTO logs (usuarioLog, mensagemLog, ipUsuario, dataLog, horaLog) VALUES ('".$_SESSION[usuarioLogin]."','$mensagemLog', '$ipLog', '$data_cadastro', '$hora_cadastro')"); $resultadoLog = mysqli_query($conn, $insereLog);?> <script type="text/javascript"> swal({ title: "Módulo cadastrado com sucesso!", text:"Deseja cadastrar outro modulo?", icon: "success", buttons: ["Não", "Sim"], dangerMode: true, }) .then((willDelete) => { if (willDelete) { window.location = 'principal.php?link=2'; } else { window.location = 'principal.php?link=3'; } }); </script> <?php } }?> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content="Antonio de Melo Sousa Júnior - 84 988147799"> <link rel="icon" href="../../favicon.ico"> <title>Sistema de Cadastro</title> <script src="js/sweetalert.min.js"></script> <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <link href="css/bootstrap.css" rel="stylesheet"> <link href="css/ie10-viewport-bug-workaround.css" rel="stylesheet"> <script src="js/ie-emulation-modes-warning.js"></script> </head> <body> <div class=" col-md-10 col-md-offset-1 main"> <form class="form-group"action="principal.php?link=2" method="post"> <input class="form-control left-border-none" type="hidden" name="enviado" value="NAO"> <input class="form-control left-border-none" type="hidden" name="recebido" value="NAO"> <input class="form-control left-border-none" type="hidden" name="os_gerada" value="NAO"> <input class="form-control left-border-none" type="hidden" name="data_cadastro" value="<?php echo date('d/m/Y'); ?>"> <input class="form-control left-border-none" type="hidden" name="hora_cadastro" value="<?php echo date('H:i:s'); ?>"> <input class="form-control left-border-none" type="hidden" name="cadastrado" value="SIM"> <div class="row"> <div class="col-md-12"> <h4 class="page-header text text-info">CADASTRAR MÓDULO COM DEFEITO</h4> </div> </div> <div class="row"> <div class="col-md-5"> <label for="id_tip_mod" class="text text-primary">TIPO DO MÓDULO</label> <select class="form-control" name="id_tip_mod" id="id_tip_mod" required autofocus> <option>SELECIONE O TIPO DO MÓDULO</option> <?php $busca_modulo = "SELECT * FROM tipo_modulo ORDER BY tipo_mod"; $resultado_busca = mysqli_query($conn, $busca_modulo); while ($linha_modulo = mysqli_fetch_assoc($resultado_busca)) { ?> <option value="<?php echo $linha_modulo['id_tip_mod']; ?>"><?php echo $linha_modulo['tipo_mod']; ?> --- <?php echo $linha_modulo['descricao_modulo']; ?> </option><?php } ?> </select> </div> <script type="text/javascript"> function optionCheck(){ var option = document.getElementById("options").value; if(option == "SIM"){ document.getElementById("hiddenDiv").style.visibility ="visible"; } if(option == "SN"){ document.getElementById("hiddenDiv").style.visibility ="hidden"; } } </script> <div class="col-md-3"> <div class="form-group"> <label for="" class="text text-primary">MÓDULO POSSUI SERIAL?</label> <select name="options" class="form-control select" id="options" onchange="optionCheck()"> <option value=" ">SELECIONE</option> <option value="SN">NÃO</option> <option value="SIM">SIM</option> </select> </div> </div> <div class="col-md-4"> <div class="form-group" id="hiddenDiv" style="visibility:hidden;"> <label for="serial" class="text text-primary">NÚMERO DE SÉRIE DO MÓDULO</label> <!-- NO SELECT TEM A PERGUNTA: MODULO POSSUI SERIAL? se SIM ele chama o serial se NÃO ele nao exibe o input mais deixa o valor fixo SN apos isso quando submeter ao banco pegar o valor do input. --> <input type="text" class="form-control" name="serial" id="serial" placeholder="digite o serial" > <input class="form-control left-border-none" type="text" name="serial" id="sn"> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="form-group"> <label for="defeito" class="text text-primary">PROBLEMA IDENTIFICADO</label> <textarea class="form-control" rows="5" id="defeito" name="defeito" placeholder="Ex: MDI ESTÁ APRESENTANDO FALHA NO LCD 1, FALHA INTERMITENTE." required></textarea> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="site" class="text text-primary">SITE QUE O MÓDULO FOI RETIRADO</label> <input type="text" id="site" name="site" class="form-control" placeholder="Ex: ST00784322" required> </div> </div> </div> <div style="text-align: right"> <button type="submit" class="btn btn-primary">Cadastrar</button> <button type="reset" class="btn btn-danger">Limpar</button> </div> </form> </div> </div> </div> </div> <!-- INSERIR ESPAÇAMENTO DA TABELA COM RODAPÉ--> <div class="col-md-12"> <hr> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="js/jquery.min.js" type="text/javascript"></script> <script src="js/bootstrap.min.js"></script> <script src="js/docs.min.js"></script> <script src="js/ie10-viewport-bug-workaround.js"></script> </body> </html>
×

Important Information

Ao usar o fórum, você concorda com nossos Terms of Use.