corrigir os novos erros amnhã e adicionar qual tipo de sexo a pessoa é no register

This commit is contained in:
2026-05-12 17:19:13 +01:00
parent 1a8ddf4b79
commit 160ddcc95c
10 changed files with 444 additions and 322 deletions

View File

@@ -1,23 +1,43 @@
package com.example.pap;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
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;
import java.io.ByteArrayOutputStream;
import java.util.Collections;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class DesafiosActivity extends AppCompatActivity {
private ProgressBar progressAgua;
private TextView tvStatusAgua;
private int coposBebidos = 3; // Simulação de progresso atual
private Button btnGravarAgua, btnGravarEx1, btnGravarEx2;
private int coposBebidos = 0;
private final int META_COPOS = 8;
// Variável para sabermos qual botão o utilizador clicou
private String desafioAtual = "";
// COLA A TUA CHAVE AQUI
private final String MINHA_API_KEY = "sk-or-v1-e65c704789ff164d6ed1be48881dcfa83d9e7f359650f16cf7680dd822e5592bA";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@@ -25,57 +45,176 @@ public class DesafiosActivity extends AppCompatActivity {
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);
btnGravarAgua = findViewById(R.id.btnGravarAgua);
btnGravarEx1 = findViewById(R.id.btnGravarEx1);
btnGravarEx2 = findViewById(R.id.btnGravarEx2);
// Launcher para capturar VÍDEO
// Carregar a água que já bebeu hoje
SharedPreferences prefs = getSharedPreferences("DadosGamificacao", MODE_PRIVATE);
coposBebidos = prefs.getInt("agua_hoje", 0);
atualizarProgressoAgua();
// Launcher que recebe o vídeo da câmara
ActivityResultLauncher<Intent> videoLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == RESULT_OK) {
// AQUI É ONDE A IA ENTRARIA PARA ANALISAR O VÍDEO
validarDesafioIA();
if (result.getResultCode() == RESULT_OK && result.getData() != null) {
Uri videoUri = result.getData().getData();
extrairFrameEEnviarIA(videoUri);
} else {
Toast.makeText(this, "Vídeo cancelado.", Toast.LENGTH_SHORT).show();
desbloquearBotoes();
}
});
// Configurar botões para abrir a câmara em modo VÍDEO
// Configurar Botões (Avisamos qual é o desafio antes de abrir a câmara)
btnGravarAgua.setOnClickListener(v -> {
desafioAtual = "agua";
bloquearBotoes();
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10); // Limita a 10 segundos para ser rápido
intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 5); // 5 Segundos chega para beber água
videoLauncher.launch(intent);
});
btnEx1.setOnClickListener(v -> {
btnGravarEx1.setOnClickListener(v -> {
desafioAtual = "agachamento";
bloquearBotoes();
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
videoLauncher.launch(intent);
});
btnEx2.setOnClickListener(v -> {
btnGravarEx2.setOnClickListener(v -> {
desafioAtual = "flexoes";
bloquearBotoes();
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
videoLauncher.launch(intent);
});
findViewById(R.id.btnVoltarDesafios).setOnClickListener(v -> finish());
}
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();
private void extrairFrameEEnviarIA(Uri videoUri) {
Toast.makeText(this, "A extrair frame do vídeo...", Toast.LENGTH_SHORT).show();
progressAgua.postDelayed(() -> {
try {
// Isto vai ao vídeo e tira uma "foto" a meio do tempo
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(this, videoUri);
// Pega num frame do segundo 2 (2000000 microsegundos)
Bitmap frame = retriever.getFrameAtTime(2000000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
if (frame != null) {
enviarParaIA(frame);
} else {
Toast.makeText(this, "Erro ao ler vídeo.", Toast.LENGTH_SHORT).show();
desbloquearBotoes();
}
} catch (Exception e) {
Toast.makeText(this, "Erro técnico no vídeo.", Toast.LENGTH_SHORT).show();
desbloquearBotoes();
}
}
private void enviarParaIA(Bitmap bitmap) {
Toast.makeText(this, "IA a avaliar o teu desafio... ⏳", Toast.LENGTH_LONG).show();
ByteArrayOutputStream os = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, os);
String base64 = Base64.encodeToString(os.toByteArray(), Base64.NO_WRAP);
String dataUrl = "data:image/jpeg;base64," + base64;
// O SEGREDO ESTÁ AQUI: Perguntas diferentes para desafios diferentes
String ordem = "";
int pontosGanhos = 0;
if (desafioAtual.equals("agua")) {
ordem = "Verifica se há uma pessoa a beber água ou com um copo/garrafa na mão. Responde APENAS 'SIM' se houver, ou 'NAO' se não houver. Não digas mais nada.";
pontosGanhos = 10;
} else if (desafioAtual.equals("agachamento")) {
ordem = "Verifica se há uma pessoa a fazer desporto ou na posição de agachamento. Responde APENAS 'SIM' ou 'NAO'.";
pontosGanhos = 50;
} else if (desafioAtual.equals("flexoes")) {
ordem = "Verifica se há uma pessoa no chão a fazer flexões ou desporto. Responde APENAS 'SIM' ou 'NAO'.";
pontosGanhos = 60;
}
AiRequest request = new AiRequest(Collections.singletonList(
new Message("user", java.util.Arrays.asList(
new ContentPart("text", ordem),
new ContentPart("image_url", new ImageUrl(dataUrl))
))
));
// Guarda as variáveis para usar dentro da resposta
final int pontosDar = pontosGanhos;
AiConfig.getRetrofit().create(AiApi.class)
.analisarImagem("Bearer " + MINHA_API_KEY, request)
.enqueue(new Callback<AiResponse>() {
@Override
public void onResponse(Call<AiResponse> call, Response<AiResponse> response) {
desbloquearBotoes();
if (response.isSuccessful() && response.body() != null) {
String respostaIA = response.body().choices.get(0).message.content.trim().toUpperCase();
if (respostaIA.contains("SIM")) {
sucessoDesafio(pontosDar);
} else {
Toast.makeText(DesafiosActivity.this, "A IA diz que NÃO estás a fazer o desafio! ❌", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(DesafiosActivity.this, "Erro no servidor da IA.", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<AiResponse> call, Throwable t) {
desbloquearBotoes();
Toast.makeText(DesafiosActivity.this, "Falha na Internet.", Toast.LENGTH_SHORT).show();
}
});
}
private void sucessoDesafio(int pontos) {
Toast.makeText(this, "✅ IA Aprovou! Ganhaste " + pontos + " pontos!", Toast.LENGTH_LONG).show();
SharedPreferences prefs = getSharedPreferences("DadosGamificacao", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
// Dá os pontos e sobe o contador de desafios
int pontosAtuais = prefs.getInt("pontos", 0);
int desafiosAtuais = prefs.getInt("desafios", 0);
editor.putInt("pontos", pontosAtuais + pontos);
editor.putInt("desafios", desafiosAtuais + 1);
// Se foi o desafio da água, sobe a barra de progresso
if (desafioAtual.equals("agua")) {
coposBebidos++;
if (coposBebidos > META_COPOS) coposBebidos = META_COPOS;
editor.putInt("agua_hoje", coposBebidos);
atualizarProgressoAgua();
Toast.makeText(this, "Desafio Validado! +10 pontos", Toast.LENGTH_LONG).show();
}
// Aqui depois vamos enviar os pontos para o Perfil
}, 2000);
editor.apply(); // Guarda tudo!
}
private void atualizarProgressoAgua() {
progressAgua.setProgress(coposBebidos);
tvStatusAgua.setText(coposBebidos + " de " + META_COPOS + " copos (" + (coposBebidos * 250) + "ml / 2L)");
}
private void bloquearBotoes() {
btnGravarAgua.setEnabled(false);
btnGravarEx1.setEnabled(false);
btnGravarEx2.setEnabled(false);
}
private void desbloquearBotoes() {
btnGravarAgua.setEnabled(true);
btnGravarEx1.setEnabled(true);
btnGravarEx2.setEnabled(true);
}
}