Compare commits

...

2 Commits

Author SHA1 Message Date
86da99ee13 Merge remote-tracking branch 'origin/main'
# Conflicts:
#	.idea/deploymentTargetSelector.xml
#	app/src/main/java/com/example/pap_findu/LocationService.java
#	app/src/main/java/com/example/pap_findu/login_activity.java
#	app/src/main/java/com/example/pap_findu/ui/map/MapFragment.java
2026-03-17 17:01:31 +00:00
d6e9320b80 a localizaçao esta funcionando + ou - certo 2026-03-13 16:57:14 +00:00
13 changed files with 915 additions and 604 deletions

View File

@@ -7,10 +7,10 @@
</SelectionState>
<SelectionState runConfigName="login_activity">
<option name="selectionMode" value="DIALOG" />
<DropdownSelection timestamp="2026-03-12T15:46:37.841197Z">
<DropdownSelection timestamp="2026-03-17T14:22:15.472961Z">
<Target type="DEFAULT_BOOT">
<handle>
<DeviceId pluginId="LocalEmulator" identifier="path=/Users/230408/.android/avd/Medium_Phone_2.avd" />
<DeviceId pluginId="LocalEmulator" identifier="path=/Users/230408/.android/avd/Pixel_7.avd" />
</handle>
</Target>
</DropdownSelection>
@@ -18,12 +18,12 @@
<targets>
<Target type="DEFAULT_BOOT">
<handle>
<DeviceId pluginId="LocalEmulator" identifier="path=/Users/230408/.android/avd/Pixel_9_Pro.avd" />
<DeviceId pluginId="LocalEmulator" identifier="path=/Users/230408/.android/avd/Pixel_7.avd" />
</handle>
</Target>
<Target type="DEFAULT_BOOT">
<handle>
<DeviceId pluginId="LocalEmulator" identifier="path=/Users/230408/.android/avd/Pixel_9_Pro_filho.avd" />
<DeviceId pluginId="LocalEmulator" identifier="path=/Users/230408/.android/avd/Pixel_7_filho.avd" />
</handle>
</Target>
</targets>

View File

@@ -2,16 +2,24 @@ package com.example.pap_findu;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.util.Log;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.pap_findu.adapters.ChatAdapter;
import com.example.pap_findu.models.ChatMessage;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
@@ -28,50 +36,101 @@ public class ChatActivity extends AppCompatActivity {
private ChatAdapter adapter;
private List<ChatMessage> messageList;
private DatabaseReference chatRef;
private String currentUserId;
private String accessCode;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_activity);
// 1. Inicializar Firebase e User
currentUserId = FirebaseAuth.getInstance().getUid();
// Recuperamos o código da "sala" (partilhado entre pai e filho)
accessCode = getSharedPreferences("FindU_Prefs", MODE_PRIVATE)
.getString("child_access_code", null);
if (accessCode == null) {
Toast.makeText(this, "Erro: Sala de chat não encontrada", Toast.LENGTH_SHORT).show();
finish();
return;
}
// Caminho no Firebase: chats / 123456 / messages
chatRef = FirebaseDatabase.getInstance().getReference("chats")
.child(accessCode)
.child("messages");
// 2. Ligar Componentes do Teu Layout
recyclerChat = findViewById(R.id.recycler_chat);
editChatMessage = findViewById(R.id.edit_chat_message);
btnSend = findViewById(R.id.btnSend);
btnBack = findViewById(R.id.btnBack);
// Initialize Message List with some dummy data
// 3. Configurar RecyclerView e Adapter
messageList = new ArrayList<>();
messageList.add(new ChatMessage("Olá Miguel! Tudo bem?", true, "10:30"));
messageList.add(new ChatMessage("Cheguei bem à escola.", false, "10:32"));
messageList.add(new ChatMessage("Ainda bem! Qualquer coisa avisa.", true, "10:33"));
// Setup Adapter
adapter = new ChatAdapter(messageList);
recyclerChat.setLayoutManager(new LinearLayoutManager(this));
recyclerChat.setAdapter(adapter);
// Scroll to bottom
recyclerChat.scrollToPosition(messageList.size() - 1);
// Send Button Logic
// 4. Lógica do Botão Enviar
btnSend.setOnClickListener(v -> {
String text = editChatMessage.getText().toString().trim();
if (!TextUtils.isEmpty(text)) {
sendMessage(text);
sendMessageToFirebase(text);
}
});
// Back Button Logic
// 5. Lógica do Botão Voltar
btnBack.setOnClickListener(v -> finish());
// 6. Começar a ouvir mensagens em tempo real
listenForMessages();
}
private void sendMessage(String text) {
private void sendMessageToFirebase(String text) {
String currentTime = new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date());
ChatMessage newMessage = new ChatMessage(text, true, currentTime);
messageList.add(newMessage);
adapter.notifyItemInserted(messageList.size() - 1);
recyclerChat.scrollToPosition(messageList.size() - 1);
// Criamos a mensagem com o ID de quem envia
ChatMessage newMessage = new ChatMessage(text, currentUserId, currentTime);
editChatMessage.setText("");
// "Empurramos" para o Firebase (Gera um ID único automático)
chatRef.push().setValue(newMessage)
.addOnSuccessListener(aVoid -> {
editChatMessage.setText(""); // Limpa o campo se correu bem
})
.addOnFailureListener(e -> {
Toast.makeText(this, "Erro ao enviar", Toast.LENGTH_SHORT).show();
});
}
}
private void listenForMessages() {
chatRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
messageList.clear();
for (DataSnapshot data : snapshot.getChildren()) {
ChatMessage msg = data.getValue(ChatMessage.class);
if (msg != null) {
// Se o senderId for o MEU, o adapter desenha à direita (azul)
msg.setSentByMe(msg.getSenderId().equals(currentUserId));
messageList.add(msg);
}
}
adapter.notifyDataSetChanged();
// Faz scroll automático para a última mensagem
if (messageList.size() > 0) {
recyclerChat.scrollToPosition(messageList.size() - 1);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.e("ChatActivity", "Erro no Firebase: " + error.getMessage());
}
});
}
}

View File

@@ -2,46 +2,55 @@ package com.example.pap_findu;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.pap_findu.models.User;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import com.example.pap_findu.models.User;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class CriarConta extends AppCompatActivity {
private EditText inputFullName;
private EditText emailEditText;
private EditText passwordEditText;
private EditText inputConfirmPassword;
private EditText inputFullName, emailEditText, passwordEditText, inputConfirmPassword;
private CheckBox checkTerms;
private Button btnCreateAccount;
private TextView loginLink;
private com.google.firebase.auth.FirebaseAuth mAuth;
private FirebaseAuth mAuth;
private DatabaseReference mDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_criar_conta);
// Ajuste de Padding para EdgeToEdge
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
// Initialize views
// 1. Inicializar Firebase
mAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference("users");
// 2. Inicializar Views
inputFullName = findViewById(R.id.inputFullName);
emailEditText = findViewById(R.id.emailEditText);
passwordEditText = findViewById(R.id.passwordEditText);
@@ -50,78 +59,69 @@ public class CriarConta extends AppCompatActivity {
btnCreateAccount = findViewById(R.id.btnCreateAccount);
loginLink = findViewById(R.id.loginLink);
mAuth = com.google.firebase.auth.FirebaseAuth.getInstance();
// 3. Botão Criar Conta
btnCreateAccount.setOnClickListener(v -> validarECriar());
// Set click listener for the create account button
btnCreateAccount.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String fullName = inputFullName.getText().toString();
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
String confirmPassword = inputConfirmPassword.getText().toString();
if (fullName.isEmpty() || email.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) {
Toast.makeText(CriarConta.this, "Por favor, preencha todos os campos.", Toast.LENGTH_SHORT).show();
} else if (!password.equals(confirmPassword)) {
Toast.makeText(CriarConta.this, "As palavras-passe não coincidem.", Toast.LENGTH_SHORT).show();
} else if (!checkTerms.isChecked()) {
Toast.makeText(CriarConta.this, "Você deve concordar com os Termos de Serviço.", Toast.LENGTH_SHORT)
.show();
} else {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(CriarConta.this,
new com.google.android.gms.tasks.OnCompleteListener<com.google.firebase.auth.AuthResult>() {
@Override
public void onComplete(
@androidx.annotation.NonNull com.google.android.gms.tasks.Task<com.google.firebase.auth.AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Toast.makeText(CriarConta.this, "Conta criada com sucesso!",
Toast.LENGTH_SHORT).show();
com.google.firebase.auth.FirebaseUser firebaseUser = mAuth
.getCurrentUser();
// Save user data to Realtime Database
if (firebaseUser != null) {
String userId = firebaseUser.getUid();
DatabaseReference mDatabase = FirebaseDatabase.getInstance()
.getReference("users");
User user = new User(fullName, email);
mDatabase.child(userId).setValue(user)
.addOnCompleteListener(task1 -> {
if (!task1.isSuccessful()) {
Toast.makeText(CriarConta.this,
"Falha ao salvar dados do perfil.",
Toast.LENGTH_SHORT).show();
}
});
}
Intent intent = new Intent(CriarConta.this, MainActivity.class);
startActivity(intent);
finish();
} else {
// If sign in fails, display a message to the user.
Toast.makeText(CriarConta.this,
"Falha ao criar conta: " + task.getException().getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
// Set click listener for the login link text
loginLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Navigate back to the login activity
Intent intent = new Intent(CriarConta.this, login_activity.class);
startActivity(intent);
finish();
}
// 4. Link para Login
loginLink.setOnClickListener(v -> {
startActivity(new Intent(CriarConta.this, login_activity.class));
finish();
});
}
}
private void validarECriar() {
String fullName = inputFullName.getText().toString().trim();
String email = emailEditText.getText().toString().trim();
String password = passwordEditText.getText().toString().trim();
String confirmPassword = inputConfirmPassword.getText().toString().trim();
// Validações Básicas
if (fullName.isEmpty() || email.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) {
Toast.makeText(this, "Preencha todos os campos!", Toast.LENGTH_SHORT).show();
return;
}
if (!password.equals(confirmPassword)) {
Toast.makeText(this, "As passwords não coincidem!", Toast.LENGTH_SHORT).show();
return;
}
if (!checkTerms.isChecked()) {
Toast.makeText(this, "Aceite os termos de serviço!", Toast.LENGTH_SHORT).show();
return;
}
// Criar no FirebaseAuth
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, task -> {
if (task.isSuccessful()) {
salvarDadosNoPerfil(fullName, email);
} else {
Toast.makeText(CriarConta.this, "Erro: " + task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
});
}
private void salvarDadosNoPerfil(String fullName, String email) {
FirebaseUser firebaseUser = mAuth.getCurrentUser();
if (firebaseUser != null) {
String userId = firebaseUser.getUid();
// Usamos o teu modelo User (Mapping: fullName -> name)
User user = new User(fullName, email);
mDatabase.child(userId).setValue(user)
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Toast.makeText(CriarConta.this, "Conta configurada com sucesso!", Toast.LENGTH_SHORT).show();
// Só avança se os dados foram salvos
Intent intent = new Intent(CriarConta.this, MainActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(CriarConta.this, "Erro ao salvar perfil no banco de dados.", Toast.LENGTH_SHORT).show();
}
});
}
}
}

View File

@@ -1,11 +1,14 @@
package com.example.pap_findu;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
@@ -15,9 +18,6 @@ import androidx.appcompat.app.AppCompatActivity;
import com.bumptech.glide.Glide;
import com.example.pap_findu.models.User;
import com.example.pap_findu.ui.profile.ProfileFragment;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.auth.FirebaseAuth;
@@ -27,25 +27,27 @@ import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.ByteArrayOutputStream;
public class EditProfileActivity extends AppCompatActivity {
private ImageView btnBack;
private ImageView editProfileImage;
private View btnChangePhoto;
private TextView btnChangePhoto;
private TextInputEditText editName;
private TextInputEditText editEmail;
private TextInputEditText editPhone;
// Botoes
private MaterialButton btnSaveProfile;
private MaterialButton btnChangePassword;
private FirebaseAuth mAuth;
private DatabaseReference mDatabase;
private StorageReference mStorageRef;
private FirebaseUser currentUser;
private Uri selectedImageUri;
// NOVO: Variável para guardar o texto gigante da imagem (Base64) em vez do Uri
private String base64ImageString = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
@@ -55,7 +57,7 @@ public class EditProfileActivity extends AppCompatActivity {
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
mDatabase = FirebaseDatabase.getInstance().getReference("users");
mStorageRef = FirebaseStorage.getInstance().getReference("profile_images");
// O StorageReference foi removido pois já não precisamos dele!
if (currentUser == null) {
finish();
@@ -73,8 +75,8 @@ public class EditProfileActivity extends AppCompatActivity {
btnChangePhoto = findViewById(R.id.btnChangePhoto);
editName = findViewById(R.id.editName);
editEmail = findViewById(R.id.editEmail);
editPhone = findViewById(R.id.editPhone);
btnSaveProfile = findViewById(R.id.btnSaveProfile);
btnChangePassword = findViewById(R.id.btnChangePassword);
}
private void loadUserData() {
@@ -85,13 +87,22 @@ public class EditProfileActivity extends AppCompatActivity {
if (user != null) {
editName.setText(user.getName());
editEmail.setText(user.getEmail());
editPhone.setText(user.getPhone());
if (user.getProfileImageUrl() != null && !user.getProfileImageUrl().isEmpty()) {
Glide.with(EditProfileActivity.this)
.load(user.getProfileImageUrl())
.placeholder(R.drawable.logo)
.into(editProfileImage);
try {
// Tenta descodificar a imagem de formato Base64 (Texto para Imagem)
byte[] decodedString = Base64.decode(user.getProfileImageUrl(), Base64.DEFAULT);
Glide.with(EditProfileActivity.this)
.load(decodedString)
.placeholder(R.drawable.logo)
.into(editProfileImage);
} catch (Exception e) {
// Se der erro (ex: se na DB estiver um link antigo em vez de Base64), tenta carregar normalmente
Glide.with(EditProfileActivity.this)
.load(user.getProfileImageUrl())
.placeholder(R.drawable.logo)
.into(editProfileImage);
}
}
} else {
// Fallback to auth data if DB is empty
@@ -110,13 +121,26 @@ public class EditProfileActivity extends AppCompatActivity {
private void setupListeners() {
btnBack.setOnClickListener(v -> finish());
// Lógica de mudar a senha
btnChangePassword.setOnClickListener(v -> {
String emailAddress = editEmail.getText().toString().trim();
if (!emailAddress.isEmpty()) {
enviarEmailRecuperacao(emailAddress);
} else {
Toast.makeText(this, "Erro: Email não encontrado.", Toast.LENGTH_SHORT).show();
}
});
// Image Picker Launcher
ActivityResultLauncher<Intent> imagePickerLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == RESULT_OK && result.getData() != null) {
selectedImageUri = result.getData().getData();
Uri selectedImageUri = result.getData().getData();
editProfileImage.setImageURI(selectedImageUri);
// NOVO: Faz a conversão mágica da imagem para texto!
converterImagemParaTexto(selectedImageUri);
}
});
@@ -128,10 +152,41 @@ public class EditProfileActivity extends AppCompatActivity {
btnSaveProfile.setOnClickListener(v -> saveProfile());
}
// NOVO: Função que pega na foto, encolhe-a e transforma num texto gigante
private void converterImagemParaTexto(Uri imageUri) {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
// Encolher para 300x300 pixeis para não exceder o limite da Realtime Database
Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, 300, 300, true);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, baos); // Qualidade 70%
byte[] imageBytes = baos.toByteArray();
// Guarda a imagem final como uma string
base64ImageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Erro ao processar imagem", Toast.LENGTH_SHORT).show();
}
}
// Função para pedir ao Firebase para enviar email de reset
private void enviarEmailRecuperacao(String email) {
btnChangePassword.setEnabled(false);
mAuth.sendPasswordResetEmail(email)
.addOnCompleteListener(task -> {
btnChangePassword.setEnabled(true);
if (task.isSuccessful()) {
Toast.makeText(EditProfileActivity.this, "Email enviado! Verifique a sua caixa de entrada.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(EditProfileActivity.this, "Erro ao enviar email.", Toast.LENGTH_SHORT).show();
}
});
}
private void saveProfile() {
String name = editName.getText().toString().trim();
String email = editEmail.getText().toString().trim();
String phone = editPhone.getText().toString().trim();
if (name.isEmpty() || email.isEmpty()) {
Toast.makeText(this, "Nome e Email são obrigatórios", Toast.LENGTH_SHORT).show();
@@ -139,32 +194,13 @@ public class EditProfileActivity extends AppCompatActivity {
}
btnSaveProfile.setEnabled(false);
btnSaveProfile.setText("Salvando...");
btnSaveProfile.setText("A Salvar...");
if (selectedImageUri != null) {
uploadImageAndSaveUser(name, email, phone);
} else {
saveUserToDb(name, email, phone, null);
}
// Guardamos o perfil passando a String Base64 (se houver), em vez de fazer upload para o Storage
saveUserToDb(name, email, base64ImageString);
}
private void uploadImageAndSaveUser(String name, String email, String phone) {
final StorageReference fileRef = mStorageRef.child(currentUser.getUid() + ".jpg");
fileRef.putFile(selectedImageUri)
.addOnSuccessListener(taskSnapshot -> fileRef.getDownloadUrl().addOnSuccessListener(uri -> {
String imageUrl = uri.toString();
saveUserToDb(name, email, phone, imageUrl);
}))
.addOnFailureListener(e -> {
Toast.makeText(EditProfileActivity.this, "Erro ao enviar imagem: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
btnSaveProfile.setEnabled(true);
btnSaveProfile.setText("Salvar Alterações");
});
}
private void saveUserToDb(String name, String email, String phone, String imageUrl) {
private void saveUserToDb(String name, String email, String imageUrlBase64) {
mDatabase.child(currentUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
@@ -174,9 +210,10 @@ public class EditProfileActivity extends AppCompatActivity {
user.setName(name);
user.setEmail(email);
user.setPhone(phone);
if (imageUrl != null) {
user.setProfileImageUrl(imageUrl);
// Se houver uma imagem convertida em Base64, guardamos na base de dados
if (imageUrlBase64 != null) {
user.setProfileImageUrl(imageUrlBase64);
}
mDatabase.child(currentUser.getUid()).setValue(user)
@@ -198,4 +235,4 @@ public class EditProfileActivity extends AppCompatActivity {
}
});
}
}
}

View File

@@ -1,24 +1,27 @@
package com.example.pap_findu;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ServiceInfo;
import androidx.core.content.ContextCompat;
import android.location.Location;
import android.os.BatteryManager;
import android.os.Build;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.os.Build;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log; // Importação adicionada
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
@@ -26,8 +29,6 @@ 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.location.Priority;
// Importações do Firebase
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
@@ -40,135 +41,112 @@ public class LocationService extends Service {
private LocationCallback locationCallback;
private DatabaseReference databaseReference;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
// Inicializa o cliente de GPS
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
// =================================================================
// AUTOMAÇÃO: Vai buscar o código de 6 dígitos salvo no Login
// =================================================================
String childCode = getSharedPreferences("FindU_Prefs", MODE_PRIVATE)
.getString("child_access_code", null);
if (childCode != null) {
// Cria a pasta usando o código de 6 dígitos (ex: users/484981/live_location)
databaseReference = FirebaseDatabase.getInstance().getReference("users/" + childCode + "/live_location");
// Caminho direto na raiz para o monitoramento em tempo real
databaseReference = FirebaseDatabase.getInstance().getReference(childCode).child("live_location");
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 1. Cria o Canal e a Notificação IMEDIATAMENTE
createNotificationChannel();
Notification notification = new NotificationCompat.Builder(this, "LocationChannel")
.setContentTitle("FindU Ativo")
.setContentText("A monitorizar a localização em tempo real...")
.setContentText("A partilhar localização e bateria em tempo real...")
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(NotificationCompat.PRIORITY_LOW)
.build();
// 2. ENVOLVER TUDO NUM TRY-CATCH PARA EVITAR CRASHES NO ANDROID 14
try {
// O Android Q (API 29) e superior permite/exige especificar o tipo de serviço no código
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
startForeground(1, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION);
} else {
startForeground(1, notification);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
startForeground(1, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION);
} else {
startForeground(1, notification);
}
// 3. Verifica permissão ANTES de ligar o motor de GPS
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// Se tem permissão, arranca com a recolha de coordenadas!
requestLocationUpdates();
} else {
// Se por acaso a permissão falhou, desliga-se silenciosamente
stopForeground(true);
stopSelf();
}
} catch (Exception e) {
Log.e("LocationService", "Erro ao iniciar Foreground Service: " + e.getMessage());
e.printStackTrace();
stopSelf();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
requestLocationUpdates();
}
return START_STICKY;
}
@SuppressWarnings("MissingPermission")
private void requestLocationUpdates() {
// Configura a frequência do GPS (a cada 10 segundos, só se mover 5 metros)
LocationRequest locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 10000)
.setMinUpdateDistanceMeters(5.0f)
LocationRequest locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 5000)
.setMinUpdateDistanceMeters(0)
.build();
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(@NonNull LocationResult locationResult) {
super.onLocationResult(locationResult);
for (Location location : locationResult.getLocations()) {
// Prepara os dados
Map<String, Object> locationData = new HashMap<>();
locationData.put("latitude", location.getLatitude());
locationData.put("longitude", location.getLongitude());
locationData.put("last_updated", System.currentTimeMillis());
// Verifica se a referência não é nula antes de enviar para o Firebase
if (databaseReference != null) {
databaseReference.setValue(locationData);
// Filtro para ignorar a localização padrão do emulador (Califórnia)
if (Math.abs(location.getLatitude() - 37.4219) > 0.001) {
updateFirebase(location);
}
}
}
};
// MELHORIA AQUI: Try-catch mais abrangente para lidar com o erro de "Broker"
try {
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
} catch (Exception e) {
Log.e("LocationService", "Erro crítico nos Google Play Services (Broker): " + e.getMessage());
} catch (SecurityException e) {
Log.e("LocationService", "Erro de permissão GPS");
}
}
// Plano B: Tenta obter pelo menos a última localização conhecida
fusedLocationClient.getLastLocation().addOnSuccessListener(location -> {
if (location != null && databaseReference != null) {
Map<String, Object> locationData = new HashMap<>();
locationData.put("latitude", location.getLatitude());
locationData.put("longitude", location.getLongitude());
locationData.put("last_updated", System.currentTimeMillis());
databaseReference.setValue(locationData);
}
private void updateFirebase(Location location) {
if (databaseReference != null) {
// --- LÓGICA DA BATERIA ---
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = registerReceiver(null, ifilter);
int level = -1;
if (batteryStatus != null) {
int rawLevel = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
level = (int) ((rawLevel / (float) scale) * 100);
}
// -------------------------
Map<String, Object> data = new HashMap<>();
data.put("latitude", location.getLatitude());
data.put("longitude", location.getLongitude());
data.put("bateria", level + "%"); // Envia ex: "85%"
data.put("last_updated", System.currentTimeMillis());
databaseReference.setValue(data).addOnFailureListener(e -> {
Log.e("LocationService", "Erro ao enviar para Firebase: " + e.getMessage());
});
}
}
@Override
public void onDestroy() {
super.onDestroy();
// Quando o serviço for desligado, para de usar o GPS para poupar bateria
if (fusedLocationClient != null && locationCallback != null) {
fusedLocationClient.removeLocationUpdates(locationCallback);
}
super.onDestroy();
}
// Cria o Canal de Notificação (obrigatório a partir do Android 8.0)
@Nullable @Override public IBinder onBind(Intent intent) { return null; }
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
"LocationChannel",
"Monitoramento de Localização",
"Monitoramento",
NotificationManager.IMPORTANCE_LOW
);
NotificationManager manager = getSystemService(NotificationManager.class);
if (manager != null) {
manager.createNotificationChannel(channel);
}
if (manager != null) manager.createNotificationChannel(channel);
}
}
}

View File

@@ -5,6 +5,7 @@ import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
@@ -18,6 +19,8 @@ import androidx.navigation.ui.NavigationUI;
import com.example.pap_findu.databinding.ActivityMainBinding;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.ArrayList;
import java.util.List;
@@ -25,24 +28,16 @@ import java.util.List;
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
private FirebaseAuth mAuth;
// ========================================================
// 1. GESTOR DE PERMISSÕES (O "Contrato" com o Android)
// ========================================================
private final ActivityResultLauncher<String[]> requestPermissionLauncher =
registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), permissions -> {
Boolean fineLocationGranted = permissions.getOrDefault(Manifest.permission.ACCESS_FINE_LOCATION, false);
Boolean coarseLocationGranted = permissions.getOrDefault(Manifest.permission.ACCESS_COARSE_LOCATION, false);
if (fineLocationGranted != null && fineLocationGranted) {
// Permissão precisa concedida, podemos iniciar o serviço!
startLocationService();
} else if (coarseLocationGranted != null && coarseLocationGranted) {
// Permissão aproximada concedida, podemos iniciar o serviço!
startLocationService();
decidirInicioDeServico();
} else {
// O utilizador recusou as permissões. A app não pode iniciar o serviço.
Toast.makeText(this, "Permissão de localização negada. O rastreamento não funcionará.", Toast.LENGTH_LONG).show();
Toast.makeText(this, "Sem permissão, o rastreamento não funcionará.", Toast.LENGTH_LONG).show();
}
});
@@ -53,8 +48,17 @@ public class MainActivity extends AppCompatActivity {
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
mAuth = FirebaseAuth.getInstance();
// Configuração da Navegação (Bottom Bar)
setupNavigation();
// Verifica permissões antes de tudo
checkAndRequestPermissions();
}
private void setupNavigation() {
BottomNavigationView navView = binding.navView;
// Configurações da barra de navegação
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_map, R.id.navigation_zones, R.id.navigation_alerts,
R.id.navigation_history, R.id.navigation_profile)
@@ -66,25 +70,16 @@ public class MainActivity extends AppCompatActivity {
if (navHostFragment != null) {
NavController navController = navHostFragment.getNavController();
NavigationUI.setupWithNavController(binding.navView, navController);
//teste
}
// ========================================================
// 2. PEDE PERMISSÕES ANTES DE LIGAR O MOTOR
// ========================================================
checkAndRequestPermissions();
}
private void checkAndRequestPermissions() {
List<String> permissionsNeeded = new ArrayList<>();
// Verifica a permissão de localização
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
permissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
permissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION);
}
// Se for Android 13 ou superior, verifica a permissão de notificações (Obrigatório para Foreground Services)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
permissionsNeeded.add(Manifest.permission.POST_NOTIFICATIONS);
@@ -92,17 +87,32 @@ public class MainActivity extends AppCompatActivity {
}
if (!permissionsNeeded.isEmpty()) {
// Se faltam permissões, pede-as ao utilizador! (Isto vai mostrar a janelinha)
requestPermissionLauncher.launch(permissionsNeeded.toArray(new String[0]));
} else {
// Se já tem todas as permissões, arranca logo com o serviço de localização!
startLocationService();
decidirInicioDeServico();
}
}
// ========================================================
// LÓGICA DE DECISÃO: PAI VS FILHO
// ========================================================
private void decidirInicioDeServico() {
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
if (user.isAnonymous()) {
// É O FILHO: Precisamos de enviar a localização e bateria
startLocationService();
Log.d("MainActivity", "Modo Filho: Serviço de GPS iniciado.");
} else {
// É O PAI: Apenas carregamos a interface (o MapFragment tratará do resto)
Log.d("MainActivity", "Modo Pai: GPS desligado para poupar bateria.");
}
}
}
private void startLocationService() {
Intent serviceIntent = new Intent(this, LocationService.class);
// O ContextCompat resolve automaticamente os problemas de compatibilidade de versões do Android!
ContextCompat.startForegroundService(this, serviceIntent);
}
}

View File

@@ -1,7 +1,7 @@
package com.example.pap_findu;
import android.content.Intent;
import android.content.SharedPreferences; // <-- Importação adicionada automaticamente
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
@@ -26,10 +26,11 @@ import com.google.firebase.Timestamp;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class login_activity extends AppCompatActivity {
@@ -38,7 +39,6 @@ public class login_activity extends AppCompatActivity {
private Button btnLogin;
private TextView criarContaTextView;
// --- NOVAS VARIÁVEIS PARA O FILHO ---
private MaterialButton btnChildLogin;
private FirebaseFirestore db;
private FirebaseAuth mAuth;
@@ -55,68 +55,46 @@ public class login_activity extends AppCompatActivity {
return insets;
});
// Inicializar Firebase Auth e Firestore
mAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
// Vincular componentes
emailEditText = findViewById(R.id.emailEditText);
passwordEditText = findViewById(R.id.passwordEditText);
btnLogin = findViewById(R.id.btnLogin);
criarContaTextView = findViewById(R.id.criarContaTextView);
// Novo botão do filho (Certifique-se que adicionou no XML com id btnChildLogin)
btnChildLogin = findViewById(R.id.btnChildLogin);
// --- LÓGICA 1: LOGIN DO PAI (Seu código original) ---
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
btnLogin.setOnClickListener(v -> {
String email = emailEditText.getText().toString();
String password = passwordEditText.getText().toString();
if (email.isEmpty() || password.isEmpty()) {
Toast.makeText(login_activity.this, "Por favor, preencha todos os campos.", Toast.LENGTH_SHORT).show();
return;
}
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(login_activity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(login_activity.this, "Login com sucesso.", Toast.LENGTH_SHORT).show();
goToMainActivity();
} else {
Toast.makeText(login_activity.this, "Falha na autenticação.", Toast.LENGTH_SHORT).show();
}
}
});
if (email.isEmpty() || password.isEmpty()) {
Toast.makeText(login_activity.this, "Por favor, preencha todos os campos.", Toast.LENGTH_SHORT).show();
return;
}
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(login_activity.this, task -> {
if (task.isSuccessful()) {
Toast.makeText(login_activity.this, "Login com sucesso.", Toast.LENGTH_SHORT).show();
goToMainActivity();
} else {
Toast.makeText(login_activity.this, "Falha na autenticação.", Toast.LENGTH_SHORT).show();
}
});
});
// --- LÓGICA 2: LOGIN DO FILHO (Novo código) ---
btnChildLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showChildLoginDialog();
}
});
btnChildLogin.setOnClickListener(v -> showChildLoginDialog());
// --- LÓGICA 3: CRIAR CONTA ---
criarContaTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(login_activity.this, CriarConta.class);
startActivity(intent);
}
criarContaTextView.setOnClickListener(v -> {
Intent intent = new Intent(login_activity.this, CriarConta.class);
startActivity(intent);
});
}
@Override
public void onStart() {
super.onStart();
// Verifica se já está logado
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser != null){
goToMainActivity();
@@ -125,28 +103,21 @@ public class login_activity extends AppCompatActivity {
private void goToMainActivity() {
Intent intent = new Intent(login_activity.this, MainActivity.class);
// Limpa a pilha para não voltar ao login com o botão voltar
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
// ==========================================================
// MÉTODOS DE LOGIN DO FILHO
// ==========================================================
private void showChildLoginDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Acesso do Filho");
builder.setMessage("Digite o código de 6 dígitos gerado pelo pai:");
// Cria uma caixa de texto dentro do alerta
final EditText inputCode = new EditText(this);
inputCode.setInputType(InputType.TYPE_CLASS_NUMBER);
inputCode.setHint("Ex: 123456");
builder.setView(inputCode);
// Botão Entrar do Alerta
builder.setPositiveButton("Entrar", (dialog, which) -> {
String code = inputCode.getText().toString().trim();
if (!TextUtils.isEmpty(code)) {
@@ -161,14 +132,12 @@ public class login_activity extends AppCompatActivity {
}
private void verifyChildCode(String code) {
// Verifica no Firestore se o código existe
db.collection("login_codes").document(code).get()
.addOnSuccessListener(document -> {
if (document.exists()) {
boolean used = Boolean.TRUE.equals(document.getBoolean("used"));
Timestamp expiresAt = document.getTimestamp("expiresAt");
// Validações
if (used) {
Toast.makeText(this, "Este código já foi usado.", Toast.LENGTH_LONG).show();
return;
@@ -180,7 +149,20 @@ public class login_activity extends AppCompatActivity {
// SUCESSO: O código é bom!
String parentId = document.getString("parentId");
loginChildAnonymously(code, parentId);
String childName = document.getString("childName");
// =======================================================
// ASSOCIAÇÃO AUTOMÁTICA: Cria o registo na coleção 'children'
// =======================================================
Map<String, Object> childData = new HashMap<>();
childData.put("parentId", parentId);
childData.put("accessCode", code);
childData.put("name", childName != null ? childName : "Filho");
childData.put("createdAt", new Timestamp(new Date()));
db.collection("children").document(code).set(childData)
.addOnSuccessListener(aVoid -> loginChildAnonymously(code, parentId))
.addOnFailureListener(e -> Toast.makeText(this, "Erro ao associar filho.", Toast.LENGTH_SHORT).show());
} else {
Toast.makeText(this, "Código inválido.", Toast.LENGTH_SHORT).show();
@@ -190,16 +172,13 @@ public class login_activity extends AppCompatActivity {
}
private void loginChildAnonymously(String code, String parentId) {
// Faz login anônimo (sem email)
mAuth.signInAnonymously()
.addOnCompleteListener(this, task -> {
if (task.isSuccessful()) {
// 1. Invalida o código para ninguém usar de novo
// Invalida o código no Firestore
db.collection("login_codes").document(code).update("used", true);
// =======================================================
// 2. NOVA LINHA: GUARDA O CÓDIGO NA MEMÓRIA DO TELEMÓVEL!
// =======================================================
// Guarda o código para o LocationService usar
getSharedPreferences("FindU_Prefs", MODE_PRIVATE)
.edit()
.putString("child_access_code", code)

View File

@@ -2,24 +2,53 @@ package com.example.pap_findu.models;
public class ChatMessage {
private String message;
private boolean isSentByMe;
private String senderId;
private String timestamp;
private boolean isSentByMe;
public ChatMessage(String message, boolean isSentByMe, String timestamp) {
// 1. Construtor Vazio (OBRIGATÓRIO para o Firebase conseguir ler os dados)
public ChatMessage() {
}
// 2. Construtor para enviar mensagens (usado na ChatActivity)
public ChatMessage(String message, String senderId, String timestamp) {
this.message = message;
this.isSentByMe = isSentByMe;
this.senderId = senderId;
this.timestamp = timestamp;
}
// --- Getters e Setters ---
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getSenderId() {
return senderId;
}
public void setSenderId(String senderId) {
this.senderId = senderId;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public boolean isSentByMe() {
return isSentByMe;
}
public String getTimestamp() {
return timestamp;
// Este setter é usado na ChatActivity dentro do loop listenForMessages
public void setSentByMe(boolean sentByMe) {
isSentByMe = sentByMe;
}
}
}

View File

@@ -1,28 +1,36 @@
package com.example.pap_findu.ui.map;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.pap_findu.ChatActivity;
import com.example.pap_findu.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.card.MaterialCardView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
@@ -30,8 +38,8 @@ import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
public class MapFragment extends Fragment implements OnMapReadyCallback {
@@ -41,6 +49,19 @@ public class MapFragment extends Fragment implements OnMapReadyCallback {
private FirebaseFirestore db;
private FirebaseAuth auth;
private FloatingActionButton btnAbrirChat;
private MaterialButton btnSOS;
// --- VARIÁVEIS PARA O CARTÃO DE INFORMAÇÃO PREMIUM ---
private View cardChildInfo;
private TextView txtChildName;
private TextView txtChildBattery;
// --- VARIÁVEIS PARA A ZONA DE STATUS (VERDE/LARANJA) ---
private MaterialCardView cardZoneStatus, cardZoneIconBG;
private ImageView iconZone;
private TextView txtZoneTitle, txtZoneSubtitle;
private GoogleMap mMap;
private Marker childMarker;
private DatabaseReference locationRef;
@@ -48,9 +69,12 @@ public class MapFragment extends Fragment implements OnMapReadyCallback {
private String currentChildId = null;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// NOVA VARIÁVEL: Guarda o nome real do filho
private String currentChildName = "A carregar...";
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_map, container, false);
db = FirebaseFirestore.getInstance();
@@ -59,16 +83,27 @@ public class MapFragment extends Fragment implements OnMapReadyCallback {
layoutEmptyState = root.findViewById(R.id.layoutEmptyState);
mapContainer = root.findViewById(R.id.mapContainer);
btnAddChild = root.findViewById(R.id.btnAddChild);
btnAbrirChat = root.findViewById(R.id.btnAbrirChat);
btnSOS = root.findViewById(R.id.btnSOS);
// --- INICIALIZAR AS VIEWS DO CARTÃO ---
cardChildInfo = root.findViewById(R.id.cardChildInfo);
txtChildName = root.findViewById(R.id.txtChildName);
txtChildBattery = root.findViewById(R.id.txtChildBattery);
// --- INICIALIZAR AS VIEWS DA ZONA ---
cardZoneStatus = root.findViewById(R.id.cardZoneStatus);
cardZoneIconBG = root.findViewById(R.id.cardZoneIconBG);
iconZone = root.findViewById(R.id.iconZone);
txtZoneTitle = root.findViewById(R.id.txtZoneTitle);
txtZoneSubtitle = root.findViewById(R.id.txtZoneSubtitle);
if (btnAbrirChat != null) btnAbrirChat.setVisibility(View.GONE);
if (btnSOS != null) btnSOS.setVisibility(View.GONE);
if (cardChildInfo != null) cardChildInfo.setVisibility(View.GONE); // Começa escondido
if (btnAddChild != null) {
btnAddChild.setOnClickListener(v -> {
FirebaseUser user = auth.getCurrentUser();
if (user != null) {
openAddChildScreen();
} else {
Toast.makeText(getContext(), "Erro: Utilizador não autenticado", Toast.LENGTH_SHORT).show();
}
});
btnAddChild.setOnClickListener(v -> openAddChildScreen());
}
checkUserTypeAndShowScreen();
@@ -81,12 +116,11 @@ public class MapFragment extends Fragment implements OnMapReadyCallback {
if (user == null) return;
if (user.isAnonymous()) {
// Se o utilizador é anónimo (Filho), ele vê o próprio mapa
showMapState();
return;
setupChildButtons();
} else {
checkIfHasChildren();
}
checkIfHasChildren();
}
private void checkIfHasChildren() {
@@ -100,14 +134,25 @@ public class MapFragment extends Fragment implements OnMapReadyCallback {
.addOnCompleteListener(task -> {
if (task.isSuccessful() && task.getResult() != null && !task.getResult().isEmpty()) {
// Pegamos no código de acesso do primeiro filho encontrado
var document = task.getResult().getDocuments().get(0);
// USAMOS O accessCode COMO CHAVE DE LIGAÇÃO
// Extraímos o documento todo
DocumentSnapshot document = task.getResult().getDocuments().get(0);
currentChildId = document.getString("accessCode");
// LER O NOME REAL DA BASE DE DADOS FIRESTORE
if (document.contains("name")) {
currentChildName = document.getString("name");
} else if (document.contains("nome")) {
currentChildName = document.getString("nome");
} else {
currentChildName = "Filho";
}
if (currentChildId != null) {
showMapState();
setupChildButtons();
if (mMap != null) {
startListeningToChildLocation();
}
} else {
showEmptyState();
}
@@ -117,70 +162,139 @@ public class MapFragment extends Fragment implements OnMapReadyCallback {
});
}
private void setupChildButtons() {
if (btnAbrirChat != null) {
btnAbrirChat.setVisibility(View.VISIBLE);
btnAbrirChat.setOnClickListener(v -> {
String roomCode = auth.getCurrentUser().isAnonymous() ?
requireContext().getSharedPreferences("FindU_Prefs", Context.MODE_PRIVATE).getString("child_access_code", null) :
currentChildId;
if (roomCode != null) {
requireContext().getSharedPreferences("FindU_Prefs", Context.MODE_PRIVATE).edit().putString("child_access_code", roomCode).apply();
startActivity(new Intent(getActivity(), ChatActivity.class));
}
});
}
if (btnSOS != null) btnSOS.setVisibility(View.VISIBLE);
}
private void showMapState() {
if (layoutEmptyState != null) layoutEmptyState.setVisibility(View.GONE);
if (mapContainer != null) mapContainer.setVisibility(View.VISIBLE);
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapContainer);
if (mapFragment == null) {
mapFragment = SupportMapFragment.newInstance();
getChildFragmentManager().beginTransaction()
.replace(R.id.mapContainer, mapFragment)
.commit();
if (mapFragment != null) {
mapFragment.getMapAsync(this);
}
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(@NonNull GoogleMap googleMap) {
mMap = googleMap;
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(0, 0), 2f));
FirebaseUser user = auth.getCurrentUser();
if (currentChildId != null) {
startListeningToChildLocation();
if (user != null && user.isAnonymous()) {
try { mMap.setMyLocationEnabled(true); } catch (SecurityException e) {}
} else {
if (currentChildId != null) {
startListeningToChildLocation();
} else {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(0, 0), 2f));
}
}
}
private void startListeningToChildLocation() {
// Escuta na pasta baseada no Código de Acesso
locationRef = FirebaseDatabase.getInstance().getReference("users/" + currentChildId + "/live_location");
if (currentChildId == null || mMap == null) return;
FirebaseUser user = auth.getCurrentUser();
// SE FOR O PAI, MOSTRAMOS O CARTÃO DO FILHO
if (user != null && !user.isAnonymous()) {
if (cardChildInfo != null) cardChildInfo.setVisibility(View.VISIBLE);
// CORREÇÃO: Agora usa estritamente o nome lido da base de dados (Ex: "Jorge")
if (txtChildName != null) {
txtChildName.setText(currentChildName);
}
}
locationRef = FirebaseDatabase.getInstance().getReference(currentChildId).child("live_location");
if (locationListener != null) locationRef.removeEventListener(locationListener);
locationListener = new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
if (snapshot.exists() && mMap != null) {
Double lat = snapshot.child("latitude").getValue(Double.class);
Double lng = snapshot.child("longitude").getValue(Double.class);
if (lat != null && lng != null && mMap != null) {
LatLng childPosition = new LatLng(lat, lng);
// LÊ A BATERIA DO FIREBASE
String bateria = snapshot.child("bateria").getValue(String.class);
if (childMarker == null) {
childMarker = mMap.addMarker(new MarkerOptions().position(childPosition).title("Filho"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(childPosition, 15f));
} else {
childMarker.setPosition(childPosition);
// ATUALIZA O TEXTO DA BATERIA
if (bateria != null && txtChildBattery != null) {
txtChildBattery.setText(bateria);
}
if (lat != null && lng != null) {
LatLng childPos = new LatLng(lat, lng);
if (Math.abs(lat - 37.4219) > 0.001) {
if (childMarker == null) {
childMarker = mMap.addMarker(new MarkerOptions()
.position(childPos)
.title(currentChildName) // O pino no mapa também vai dizer o nome do filho
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
} else {
childMarker.setPosition(childPos);
childMarker.setTitle(currentChildName);
}
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(childPos, 17f));
// TESTE DE DESIGN
atualizarStatusZona(true, "A atualizar localização...");
}
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.e("MapFragment", "Erro: " + error.getMessage());
}
@Override public void onCancelled(@NonNull DatabaseError error) {}
};
locationRef.addValueEventListener(locationListener);
}
// --- FUNÇÃO PARA MUDAR AS CORES DA ZONA (VERDE/LARANJA) ---
private void atualizarStatusZona(boolean naZonaSegura, String subtitulo) {
if (cardZoneStatus == null) return;
if (naZonaSegura) {
// MODO VERDE: Dentro de Zona Segura
cardZoneStatus.setCardBackgroundColor(Color.parseColor("#9DCA43"));
cardZoneIconBG.setCardBackgroundColor(Color.parseColor("#EAF4D4"));
iconZone.setColorFilter(Color.parseColor("#5F8B1A"));
txtZoneTitle.setText("Dentro de Zona Segura");
txtZoneTitle.setTextColor(Color.parseColor("#2D4608"));
txtZoneSubtitle.setText(subtitulo);
txtZoneSubtitle.setTextColor(Color.parseColor("#486B11"));
} else {
// MODO LARANJA: Em Movimento / Fora de Zonas
cardZoneStatus.setCardBackgroundColor(Color.parseColor("#FFA726"));
cardZoneIconBG.setCardBackgroundColor(Color.parseColor("#FFE0B2"));
iconZone.setColorFilter(Color.parseColor("#E65100"));
txtZoneTitle.setText("A movimentar-se");
txtZoneTitle.setTextColor(Color.parseColor("#822B00"));
txtZoneSubtitle.setText("Fora das zonas seguras");
txtZoneSubtitle.setTextColor(Color.parseColor("#A63A00"));
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (locationRef != null && locationListener != null) {
locationRef.removeEventListener(locationListener);
}
if (locationRef != null && locationListener != null) locationRef.removeEventListener(locationListener);
}
private void showEmptyState() {
@@ -195,14 +309,10 @@ public class MapFragment extends Fragment implements OnMapReadyCallback {
}
private void showCodeDialog(String code) {
if (getContext() == null) return;
ClipboardManager clipboard = (ClipboardManager) requireContext().getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(ClipData.newPlainText("Código", code));
new AlertDialog.Builder(getContext())
new AlertDialog.Builder(requireContext())
.setTitle("Filho Adicionado!")
.setMessage("O código de acesso é: " + code)
.setPositiveButton("Ir para o Mapa", (dialog, which) -> checkIfHasChildren())
.setMessage("Código: " + code)
.setPositiveButton("OK", (d, w) -> checkIfHasChildren())
.show();
}
}

View File

@@ -2,6 +2,7 @@ package com.example.pap_findu.ui.profile;
import android.content.Intent;
import android.os.Bundle;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@@ -13,7 +14,6 @@ import androidx.fragment.app.Fragment;
import com.bumptech.glide.Glide;
import com.example.pap_findu.EditProfileActivity;
import com.example.pap_findu.R;
import com.example.pap_findu.SecurityActivity;
import com.example.pap_findu.databinding.FragmentProfileBinding;
import com.example.pap_findu.models.User;
import com.google.firebase.auth.FirebaseAuth;
@@ -28,12 +28,12 @@ public class ProfileFragment extends Fragment {
private FragmentProfileBinding binding;
private FirebaseAuth mAuth;
private DatabaseReference mDatabase;
private ValueEventListener mUserListener;
private DatabaseReference mUserRef;
private ValueEventListener mUserListener;
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
ViewGroup container, Bundle savedInstanceState) {
binding = FragmentProfileBinding.inflate(inflater, container, false);
View root = binding.getRoot();
@@ -41,49 +41,68 @@ public class ProfileFragment extends Fragment {
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null) {
// Should prompt login or handle error
return root;
}
mDatabase = FirebaseDatabase.getInstance().getReference("users");
mUserRef = mDatabase.child(currentUser.getUid());
setupListeners();
// Listen for user data changes
mUserListener = new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (getContext() == null)
return;
// Verifica se é o Filho (Anónimo)
if (currentUser.isAnonymous()) {
binding.profileName.setText("Conta de Criança");
binding.profileEmail.setText("Modo de Monitorização Ativo");
binding.profileImage.setImageResource(R.drawable.logo);
User user = snapshot.getValue(User.class);
if (user != null) {
binding.profileName.setText(user.getName());
binding.profileEmail.setText(user.getEmail());
// Oculta opções que não fazem sentido para o Filho
binding.layoutEditProfile.setVisibility(View.GONE);
if (user.getProfileImageUrl() != null && !user.getProfileImageUrl().isEmpty()) {
Glide.with(ProfileFragment.this)
.load(user.getProfileImageUrl())
.placeholder(R.drawable.logo) // Make sure logo exists or use R.mipmap.ic_launcher
.into(binding.profileImage);
} else {
binding.profileImage.setImageResource(R.drawable.logo);
} else {
// É O PAI: Carrega os dados reais do Firebase
mUserRef = FirebaseDatabase.getInstance().getReference("users").child(currentUser.getUid());
mUserListener = new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (getContext() == null || binding == null) return;
if (snapshot.exists()) {
User user = snapshot.getValue(User.class);
if (user != null) {
binding.profileName.setText(user.getName());
binding.profileEmail.setText(user.getEmail());
// MAGIA: LER A FOTO EM FORMATO DE TEXTO (BASE64)
if (user.getProfileImageUrl() != null && !user.getProfileImageUrl().isEmpty()) {
try {
byte[] decodedString = Base64.decode(user.getProfileImageUrl(), Base64.DEFAULT);
Glide.with(ProfileFragment.this)
.load(decodedString)
.placeholder(R.drawable.logo)
.into(binding.profileImage);
} catch (Exception e) {
// Fallback caso a imagem seja um link antigo e não Base64
try {
Glide.with(ProfileFragment.this)
.load(user.getProfileImageUrl())
.placeholder(R.drawable.logo)
.into(binding.profileImage);
} catch (Exception ex) {
binding.profileImage.setImageResource(R.drawable.logo);
}
}
} else {
binding.profileImage.setImageResource(R.drawable.logo);
}
}
}
} else {
// Fallback to Auth data if DB is empty
binding.profileName.setText(
currentUser.getDisplayName() != null ? currentUser.getDisplayName() : "Utilizador");
binding.profileEmail.setText(currentUser.getEmail());
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
if (getContext() != null)
Toast.makeText(getContext(), "Erro ao carregar perfil", Toast.LENGTH_SHORT).show();
}
};
@Override
public void onCancelled(@NonNull DatabaseError error) {
if (getContext() != null)
Toast.makeText(getContext(), "Erro ao carregar perfil", Toast.LENGTH_SHORT).show();
}
};
}
return root;
}
@@ -93,10 +112,6 @@ public class ProfileFragment extends Fragment {
startActivity(new Intent(getActivity(), EditProfileActivity.class));
});
binding.layoutSecurity.setOnClickListener(v -> {
startActivity(new Intent(getActivity(), SecurityActivity.class));
});
binding.btnLogout.setOnClickListener(v -> {
mAuth.signOut();
Intent intent = new Intent(getActivity(), com.example.pap_findu.login_activity.class);
@@ -126,4 +141,4 @@ public class ProfileFragment extends Fragment {
super.onDestroyView();
binding = null;
}
}
}

View File

@@ -9,7 +9,6 @@
android:background="#F6F7FB"
tools:context=".EditProfileActivity">
<!-- Header -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
@@ -48,7 +47,6 @@
android:padding="24dp"
android:gravity="center_horizontal">
<!-- Profile Image -->
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
@@ -62,32 +60,35 @@
app:shapeAppearanceOverlay="@style/ShapeAppearance.MaterialComponents.MediumComponent"
android:src="@drawable/logo" />
<ImageView
android:layout_width="32dp"
android:layout_height="32dp"
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:background="@drawable/bg_circle_button"
android:padding="6dp"
android:layout_marginEnd="-8dp"
android:layout_marginBottom="-8dp"
android:src="@android:drawable/ic_menu_camera"
app:tint="#FFFFFF" />
app:backgroundTint="#3B82F6"
app:fabSize="mini"
app:tint="#FFFFFF"
android:clickable="false" />
</FrameLayout>
<TextView
android:id="@+id/btnChangePhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginTop="16dp"
android:text="Alterar Foto"
android:textColor="#3B82F6"
android:textStyle="bold"
android:clickable="true"
android:padding="8dp"
android:background="?attr/selectableItemBackground" />
<!-- Form -->
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:layout_marginTop="24dp"
android:hint="Nome Completo"
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">
@@ -102,38 +103,37 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:hint="Email"
android:hint="Email (Não editável)"
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/editEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress" />
android:inputType="textEmailAddress"
android:enabled="false"
android:textColor="#9CA3AF"/>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:hint="Telefone (Opcional)"
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/editPhone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="phone" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.button.MaterialButton
android:id="@+id/btnChangePassword"
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_marginTop="24dp"
android:text="MUDAR PALAVRA-PASSE"
android:textColor="#3B82F6"
app:strokeColor="#3B82F6"
app:cornerRadius="12dp" />
<com.google.android.material.button.MaterialButton
android:id="@+id/btnSaveProfile"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginTop="40dp"
android:layout_marginTop="32dp"
android:text="Salvar Alterações"
app:cornerRadius="12dp" />
</LinearLayout>
</ScrollView>
</LinearLayout>
</LinearLayout>

View File

@@ -5,128 +5,264 @@
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F3F6FB">
tools:context=".ui.map.MapFragment">
<androidx.constraintlayout.widget.ConstraintLayout
<LinearLayout
android:id="@+id/layoutEmptyState"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible">
<View
android:id="@+id/viewHeader"
android:layout_width="match_parent"
android:layout_height="160dp"
android:background="@drawable/bg_header_rounded"
app:layout_constraintTop_toTopOf="parent" />
android:gravity="center"
android:orientation="vertical"
android:visibility="gone">
<TextView
android:id="@+id/tvAppTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="FindU"
android:textColor="@android:color/white"
android:textSize="22sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
android:text="Ainda não tem filhos associados."
android:textSize="18sp"
android:layout_marginBottom="16dp"/>
<androidx.cardview.widget.CardView
android:id="@+id/cardEmptyState"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginHorizontal="24dp"
android:layout_marginTop="30dp"
android:layout_marginBottom="24dp"
app:cardCornerRadius="20dp"
app:cardElevation="4dp"
app:layout_constraintBottom_toTopOf="@+id/btnSOS"
app:layout_constraintTop_toBottomOf="@+id/tvAppTitle">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="24dp">
<View
android:id="@+id/bgIcon"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/bg_circle_light_blue"
app:layout_constraintBottom_toTopOf="@+id/tvNoChildTitle"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="packed" />
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@android:drawable/ic_menu_add"
app:layout_constraintBottom_toBottomOf="@+id/bgIcon"
app:layout_constraintEnd_toEndOf="@+id/bgIcon"
app:layout_constraintStart_toStartOf="@+id/bgIcon"
app:layout_constraintTop_toTopOf="@+id/bgIcon"
app:tint="#3D6DFF" />
<TextView
android:id="@+id/tvNoChildTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="Nenhum filho adicionado"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="@+id/tvNoChildDesc"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/bgIcon" />
<TextView
android:id="@+id/tvNoChildDesc"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:gravity="center"
android:text="Adicione o seu primeiro filho para começar."
app:layout_constraintBottom_toTopOf="@+id/btnAddChild"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvNoChildTitle" />
<com.google.android.material.button.MaterialButton
android:id="@+id/btnAddChild"
android:layout_width="match_parent"
android:layout_height="60dp"
android:text="Adicionar Filho"
android:textStyle="bold"
app:backgroundTint="#3D6DFF"
app:cornerRadius="12dp"
app:layout_constraintBottom_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
<com.google.android.material.button.MaterialButton
android:id="@+id/btnSOS"
android:layout_width="match_parent"
android:layout_height="65dp"
android:layout_marginHorizontal="24dp"
android:layout_marginBottom="24dp"
android:text="SOS"
app:backgroundTint="#D32F2F"
app:cornerRadius="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<Button
android:id="@+id/btnAddChild"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Adicionar Filho" />
</LinearLayout>
<androidx.fragment.app.FragmentContainerView
android:id="@+id/mapContainer"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<com.google.android.material.card.MaterialCardView
android:id="@+id/cardChildInfo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />
android:layout_height="wrap_content"
android:layout_marginHorizontal="20dp"
android:layout_marginTop="32dp"
app:cardCornerRadius="24dp"
app:cardElevation="8dp"
app:cardBackgroundColor="#FFFFFF"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:visibility="gone">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical">
<com.google.android.material.card.MaterialCardView
android:layout_width="56dp"
android:layout_height="56dp"
app:cardCornerRadius="28dp"
app:cardBackgroundColor="#F0F4FF"
app:cardElevation="0dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="12dp"
android:src="@android:drawable/ic_menu_myplaces"
app:tint="#A0AABF"/>
</com.google.android.material.card.MaterialCardView>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:layout_marginStart="16dp">
<TextView
android:id="@+id/txtChildName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nome do Filho"
android:textColor="#1F2937"
android:textSize="20sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:layout_marginTop="2dp">
<com.google.android.material.card.MaterialCardView
android:layout_width="10dp"
android:layout_height="10dp"
app:cardCornerRadius="5dp"
app:cardBackgroundColor="#4CAF50"
app:cardElevation="0dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Online"
android:textColor="#4CAF50"
android:textStyle="bold"
android:textSize="14sp"
android:layout_marginStart="6dp"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="end">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical">
<ImageView
android:layout_width="16dp"
android:layout_height="16dp"
android:src="@android:drawable/ic_lock_idle_charging"
app:tint="#4CAF50"/>
<TextView
android:id="@+id/txtChildBattery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="--%"
android:textColor="#1F2937"
android:textSize="15sp"
android:textStyle="bold"
android:layout_marginStart="4dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:layout_marginTop="6dp">
<ImageView
android:layout_width="16dp"
android:layout_height="16dp"
android:src="@android:drawable/ic_menu_mylocation"
app:tint="#3B82F6"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GPS"
android:textColor="#1F2937"
android:textSize="15sp"
android:textStyle="bold"
android:layout_marginStart="4dp"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
<com.google.android.material.card.MaterialCardView
android:id="@+id/cardZoneStatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:cardCornerRadius="12dp"
app:cardBackgroundColor="#9DCA43"
app:cardElevation="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="12dp"
android:gravity="center_vertical">
<com.google.android.material.card.MaterialCardView
android:id="@+id/cardZoneIconBG"
android:layout_width="36dp"
android:layout_height="36dp"
app:cardCornerRadius="18dp"
app:cardBackgroundColor="#EAF4D4"
app:cardElevation="0dp">
<ImageView
android:id="@+id/iconZone"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
android:src="@android:drawable/ic_menu_mylocation"
app:tint="#5F8B1A"/>
</com.google.android.material.card.MaterialCardView>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:layout_marginStart="12dp">
<TextView
android:id="@+id/txtZoneTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dentro de Zona Segura"
android:textColor="#2D4608"
android:textSize="15sp"
android:textStyle="bold"/>
<TextView
android:id="@+id/txtZoneSubtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="A carregar..."
android:textColor="#486B11"
android:textSize="13sp"/>
</LinearLayout>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/btnAbrirChat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:backgroundTint="#4CAF50"
app:tint="@android:color/white"
android:src="@android:drawable/ic_dialog_email"
app:layout_constraintBottom_toTopOf="@+id/btnSOS"
app:layout_constraintEnd_toEndOf="parent" />
<com.google.android.material.button.MaterialButton
android:id="@+id/btnSOS"
android:layout_width="0dp"
android:layout_height="60dp"
android:layout_marginStart="24dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="24dp"
android:text="BOTÃO SOS DE EMERGÊNCIA"
android:textColor="@android:color/white"
android:textSize="16sp"
android:textStyle="bold"
app:backgroundTint="#D32F2F"
app:cornerRadius="12dp"
app:icon="@android:drawable/ic_menu_call"
app:iconGravity="textEnd"
app:iconPadding="16dp"
app:iconTint="@android:color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

View File

@@ -60,7 +60,6 @@
</LinearLayout>
</FrameLayout>
<!-- Account Settings Section -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
@@ -88,7 +87,6 @@
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Item 1 -->
<LinearLayout
android:id="@+id/layoutEditProfile"
android:layout_width="match_parent"
@@ -121,47 +119,9 @@
android:rotation="0" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#F3F4F6" />
<!-- Item 2 -->
<LinearLayout
android:id="@+id/layoutSecurity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:clickable="true"
android:gravity="center_vertical"
android:padding="16dp">
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:src="@android:drawable/ic_lock_idle_lock"
app:tint="#4B5563" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_weight="1"
android:text="Segurança e Senha"
android:textColor="#1F2937"
android:textSize="16sp" />
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:src="@android:drawable/ic_media_play"
app:tint="#9CA3AF"
android:rotation="0" />
</LinearLayout>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<!-- App Settings Section -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
@@ -189,7 +149,6 @@
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Item 1 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
@@ -224,7 +183,6 @@
android:layout_height="1dp"
android:background="#F3F4F6" />
<!-- Item 2 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
@@ -274,10 +232,10 @@
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:gravity="center"
android:text="FindU Inc. © 2024"
android:text="FindU Inc. © 2026"
android:textColor="#D1D5DB"
android:textSize="12sp" />
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</androidx.core.widget.NestedScrollView>