corrige o erro da camera e da ia não funcionar e mudar o layout futuramente

This commit is contained in:
2026-05-11 17:19:20 +01:00
parent e480abd98e
commit 1a8ddf4b79
20 changed files with 850 additions and 829 deletions

View File

@@ -1,147 +1,81 @@
package com.example.pap;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
public class DesafiosActivity extends AppCompatActivity {
private TextView tvPontos, tvStatusDesafio1, tvStatusDesafio2;
private Button btnVideoDesafio1, btnVideoDesafio2, btnVoltarDesafios;
private int pontosAtuais = 0;
private SharedPreferences sharedPreferences;
// Variável para saber qual desafio está a ser gravado no momento
private int desafioAtualEmGravacao = -1;
// Ferramenta para abrir a câmara de vídeo e receber o resultado
private final ActivityResultLauncher<Intent> videoLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == RESULT_OK) {
// O utilizador gravou o vídeo com sucesso!
Toast.makeText(this, "Vídeo capturado! A enviar para a IA...", Toast.LENGTH_SHORT).show();
simularAnaliseDaIA(desafioAtualEmGravacao);
} else {
Toast.makeText(this, "Gravação cancelada.", Toast.LENGTH_SHORT).show();
}
}
);
private ProgressBar progressAgua;
private TextView tvStatusAgua;
private int coposBebidos = 3; // Simulação de progresso atual
private final int META_COPOS = 8;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_desafios);
// 1. Inicializar os componentes
tvPontos = findViewById(R.id.tvPontos);
tvStatusDesafio1 = findViewById(R.id.tvStatusDesafio1);
tvStatusDesafio2 = findViewById(R.id.tvStatusDesafio2);
btnVideoDesafio1 = findViewById(R.id.btnVideoDesafio1);
btnVideoDesafio2 = findViewById(R.id.btnVideoDesafio2);
btnVoltarDesafios = findViewById(R.id.btnVoltarDesafios);
progressAgua = findViewById(R.id.progressAgua);
tvStatusAgua = findViewById(R.id.tvStatusAgua);
Button btnGravarAgua = findViewById(R.id.btnGravarAgua);
Button btnEx1 = findViewById(R.id.btnGravarEx1);
Button btnEx2 = findViewById(R.id.btnGravarEx2);
// 2. Carregar os dados guardados no telemóvel
sharedPreferences = getSharedPreferences("AppEmagrecimento", MODE_PRIVATE);
carregarDadosGuardados();
// Launcher para capturar VÍDEO
ActivityResultLauncher<Intent> videoLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == RESULT_OK) {
// AQUI É ONDE A IA ENTRARIA PARA ANALISAR O VÍDEO
validarDesafioIA();
}
});
// 3. Configurar os cliques para gravar vídeo
btnVideoDesafio1.setOnClickListener(v -> abrirCameraVideo(1));
btnVideoDesafio2.setOnClickListener(v -> abrirCameraVideo(2));
// 4. Botão de voltar
btnVoltarDesafios.setOnClickListener(v -> finish());
}
// Função para abrir a câmara do telemóvel em modo VÍDEO
private void abrirCameraVideo(int numeroDoDesafio) {
desafioAtualEmGravacao = numeroDoDesafio;
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
try {
// Configurar botões para abrir a câmara em modo VÍDEO
btnGravarAgua.setOnClickListener(v -> {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10); // Limita a 10 segundos para ser rápido
videoLauncher.launch(intent);
} catch (ActivityNotFoundException e) {
// Caso o emulador não tenha uma câmara configurada, abre a galeria para selecionar um vídeo
Toast.makeText(this, "Câmara não encontrada. Selecione um vídeo da galeria.", Toast.LENGTH_LONG).show();
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("video/*");
videoLauncher.launch(galleryIntent);
}
});
btnEx1.setOnClickListener(v -> {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
videoLauncher.launch(intent);
});
btnEx2.setOnClickListener(v -> {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
videoLauncher.launch(intent);
});
findViewById(R.id.btnVoltarDesafios).setOnClickListener(v -> finish());
}
// Função que simula o tempo de pensamento da Inteligência Artificial
private void simularAnaliseDaIA(int numeroDoDesafio) {
TextView tvStatusAtual = (numeroDoDesafio == 1) ? tvStatusDesafio1 : tvStatusDesafio2;
Button btnAtual = (numeroDoDesafio == 1) ? btnVideoDesafio1 : btnVideoDesafio2;
private void validarDesafioIA() {
// Simulação: A IA demora 2 segundos a processar e diz que está OK
Toast.makeText(this, "IA a analisar movimento...", Toast.LENGTH_SHORT).show();
// Muda a interface para mostrar que a IA está a trabalhar
tvStatusAtual.setText("A IA está a analisar os teus movimentos...");
tvStatusAtual.setTextColor(Color.parseColor("#2196F3")); // Azul
btnAtual.setEnabled(false);
btnAtual.setText("A processar...");
progressAgua.postDelayed(() -> {
coposBebidos++;
if (coposBebidos > META_COPOS) coposBebidos = META_COPOS;
// Simula uma espera de 3.5 segundos (tempo que a IA demoraria a analisar o vídeo)
new Handler(Looper.getMainLooper()).postDelayed(() -> {
atualizarProgressoAgua();
Toast.makeText(this, "Desafio Validado! +10 pontos", Toast.LENGTH_LONG).show();
// Depois de 3.5 segundos, a IA aprova o desafio!
int pontosGanhos = (numeroDoDesafio == 1) ? 20 : 30;
// Atualizar UI
tvStatusAtual.setText("Aprovado pela IA! +" + pontosGanhos + " pts");
tvStatusAtual.setTextColor(Color.parseColor("#4CAF50")); // Verde
btnAtual.setText("Desafio Concluído");
btnAtual.setBackgroundTintList(android.content.res.ColorStateList.valueOf(Color.parseColor("#81C784")));
// Adicionar pontos e guardar
adicionarPontosEGuardar(numeroDoDesafio, pontosGanhos);
}, 3500); // 3500 milissegundos = 3.5 segundos
// Aqui depois vamos enviar os pontos para o Perfil
}, 2000);
}
private void adicionarPontosEGuardar(int numeroDoDesafio, int pontos) {
pontosAtuais += pontos;
tvPontos.setText(String.valueOf(pontosAtuais));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("pontosTotais", pontosAtuais);
editor.putBoolean("desafio_" + numeroDoDesafio + "_concluido", true);
editor.apply();
}
private void carregarDadosGuardados() {
pontosAtuais = sharedPreferences.getInt("pontosTotais", 0);
tvPontos.setText(String.valueOf(pontosAtuais));
// Verificar se o Desafio 1 já foi feito anteriormente
if (sharedPreferences.getBoolean("desafio_1_concluido", false)) {
tvStatusDesafio1.setText("Aprovado pela IA!");
tvStatusDesafio1.setTextColor(Color.parseColor("#4CAF50"));
btnVideoDesafio1.setEnabled(false);
btnVideoDesafio1.setText("Desafio Concluído");
btnVideoDesafio1.setBackgroundTintList(android.content.res.ColorStateList.valueOf(Color.parseColor("#81C784")));
}
// Verificar se o Desafio 2 já foi feito anteriormente
if (sharedPreferences.getBoolean("desafio_2_concluido", false)) {
tvStatusDesafio2.setText("Aprovado pela IA!");
tvStatusDesafio2.setTextColor(Color.parseColor("#4CAF50"));
btnVideoDesafio2.setEnabled(false);
btnVideoDesafio2.setText("Desafio Concluído");
btnVideoDesafio2.setBackgroundTintList(android.content.res.ColorStateList.valueOf(Color.parseColor("#81C784")));
}
private void atualizarProgressoAgua() {
progressAgua.setProgress(coposBebidos);
tvStatusAgua.setText(coposBebidos + " de " + META_COPOS + " copos (" + (coposBebidos * 250) + "ml / 2L)");
}
}