Created
November 22, 2018 14:06
-
-
Save jazari-akuna/f38fbeec705d495e5138f4690b575b76 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Programmation Android 2018-2019 | |
ECE Paris - ING5 APP Systèmes Embarqué | |
TP6 et TP7 | |
Application - Boussole | |
*/ | |
package com.example.p095010.tp_android_boussole; | |
import android.Manifest; | |
import android.content.ContentValues; | |
import android.content.pm.PackageManager; | |
import android.database.Cursor; | |
import android.database.sqlite.SQLiteDatabase; | |
import android.hardware.GeomagneticField; | |
import android.hardware.Sensor; | |
import android.hardware.SensorEvent; | |
import android.hardware.SensorEventListener; | |
import android.hardware.SensorManager; | |
import android.location.Location; | |
import android.location.LocationListener; | |
import android.location.LocationManager; | |
import android.os.StrictMode; | |
import android.support.v4.app.ActivityCompat; | |
import android.support.v7.app.AppCompatActivity; | |
import android.os.Bundle; | |
import android.view.View; | |
import android.widget.ArrayAdapter; | |
import android.widget.Button; | |
import android.widget.ImageView; | |
import android.widget.Switch; | |
import android.widget.TextView; | |
import android.widget.Toast; | |
import org.xml.sax.InputSource; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.net.MalformedURLException; | |
import java.net.URL; | |
import java.text.DecimalFormat; | |
import java.text.SimpleDateFormat; | |
import java.util.ArrayList; | |
import java.util.Date; | |
import java.util.List; | |
import java.util.Scanner; | |
public class MainActivity extends AppCompatActivity { | |
double lati; | |
double longi; | |
float[] accelerof = new float[3]; | |
float[] magneticf = new float[3]; | |
float[] resultMatrix = new float[9]; | |
float[] orientation = new float[3]; | |
//declinaison magnétique : | |
//on utilise : http://www.geomag.nrcan.gc.ca/calc/mdcal-fr.php | |
//qui nous renvoie la déclinaison concernée en fonction du lieu. | |
//Par exemple : | |
// http://www.geomag.nrcan.gc.ca/calc/mdcal-r-fr.php?date=2018-10-20&latitude=48.846834&latitude_direction=1&longitude=2.3958577&longitude_direction=1 | |
boolean passed = false; | |
Float declinaison = (float)0; | |
public float getDeclinaison(){ | |
String declinaisonstr = "0"; | |
//Date d'aujourdh'ui sous format qu'on veut | |
String format = "yyyy-MM-dd"; | |
SimpleDateFormat formater = new SimpleDateFormat(format); | |
Date date = new Date(); | |
String date_today = formater.format(date); | |
//Etat internet | |
boolean internet_status = false; | |
//Vérification de disponibilité internet | |
if (InternetCheck.isNetworkAvailable(getApplicationContext())){ | |
System.out.println("Statut de Votre internet : Disponible"); | |
internet_status = true; | |
}else { | |
System.out.println("Statut de Votre internet : Non Disponible"); | |
internet_status = false; | |
} | |
//You should almost always run network operations on a thread or as an asynchronous task. | |
//But it is possible to remove this restriction and you override the default behavior, | |
// if you are willing to accept the consequences. | |
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); | |
StrictMode.setThreadPolicy(policy); | |
//classe fille de SQLiteOpenHelper | |
filleSQL SQLite = new filleSQL(this, "decli.db", null, 1); | |
//base de données | |
SQLiteDatabase bdd = SQLite.getWritableDatabase(); | |
ContentValues values = new ContentValues(); | |
//si l'internet est disponible | |
if(internet_status){ | |
//RAZ de la BDD | |
SQLite.onUpgrade(bdd,1,1); | |
//URL du site | |
String urlstr = "http://www.geomag.nrcan.gc.ca/calc/mdcal-r-fr.php?date="+date_today+"&latitude="+lati+"&latitude_direction=1&longitude="+longi+"&longitude_direction=1"; | |
URL url = null; | |
try { | |
url = new URL(urlstr); | |
} catch (MalformedURLException e) { | |
e.printStackTrace(); | |
} | |
String out = null; | |
try { | |
out = new Scanner(url.openStream(), "UTF-8").useDelimiter("\\A").next(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
String out2[] = out.split("<p>Déclinaison magnétique: "); | |
String dec1 = out2[1].split("</p>")[0].split("° ")[0]; | |
String dec2 = out2[1].split("</p>")[0].split("° ")[1].split(",")[0]; | |
String dec3 = out2[1].split("</p>")[0].split("° ")[1].split(",")[1].split("' ")[0]; | |
String dir = out2[1].split("</p>")[0].split("° ")[1].split(",")[1].split("' ")[1]; | |
System.out.println("URL content : "); | |
System.out.println(dec1 + " " + dec2 + " " + dec3 + " " + dir); | |
declinaisonstr = dec1+"."+dec2; | |
values = new ContentValues(); | |
values.put("declinaison", Float.valueOf(declinaisonstr)); | |
bdd.insert("table_declinaison",null,values); | |
System.out.println("Declinaison : "+Float.valueOf(declinaisonstr)+" degres"); | |
return Float.valueOf(declinaisonstr); | |
} | |
else{ | |
Cursor cursor = bdd.query("table_declinaison", new String[]{"declinaison"}, null, null, null, null, null); | |
cursor.moveToFirst(); | |
if(cursor.getCount()==0){ | |
//Si la BDD est vide retourner 0 et déselectionner | |
Switch declibtn = (Switch) findViewById(R.id.decli); | |
declibtn.setChecked(false); | |
//Afficher un message | |
Toast.makeText(this, "Base de données vide", Toast.LENGTH_SHORT).show(); | |
return (float)0; | |
} | |
else{ | |
Float bdd_float = (float)0; | |
//Si la BDD n'est pas vide, on récupére | |
cursor.moveToFirst(); | |
while (!cursor.isAfterLast()) { | |
bdd_float= cursor.getFloat(0); | |
cursor.moveToNext(); | |
} | |
cursor.close(); | |
//Afficher un message | |
Toast.makeText(this, "Ancienne valeur de déclinaison récupérée", Toast.LENGTH_SHORT).show(); | |
return bdd_float; | |
} | |
} | |
} | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
//Bouton Droite pour tourner la boussole à droite de 30 degrés | |
Button btnd = (Button) findViewById(R.id.btndroite); | |
btnd.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View view) { | |
ImageView boussole = (ImageView) findViewById(R.id.boussole); | |
boussole.setRotation(boussole.getRotation() + 30); | |
} | |
}); | |
//Bouton Droite pour tourner la boussole à gauche de 30 degrés | |
Button btng = (Button) findViewById(R.id.btngauche); | |
btng.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View view) { | |
ImageView boussole = (ImageView) findViewById(R.id.boussole); | |
boussole.setRotation(boussole.getRotation() - 30); | |
} | |
}); | |
TextView txtlong = (TextView) findViewById(R.id.longi); | |
TextView txtlat = (TextView) findViewById(R.id.lati); | |
txtlat.setText("Latitude : "); | |
txtlong.setText("Longitude : "); | |
//Récupérer longitude et latitude depuis Location Manager | |
LocationManager lm = (LocationManager) getSystemService(this.LOCATION_SERVICE); | |
//Besoin de <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> | |
//Dans Manifest pour autoriser | |
//Listener pour surveiller et remettre à jour les textes | |
LocationListener loclisten = new LocationListener() { | |
@Override | |
public void onLocationChanged(Location location) { | |
TextView txtlong = (TextView) findViewById(R.id.longi); | |
TextView txtlat = (TextView) findViewById(R.id.lati); | |
lati = location.getLatitude(); | |
txtlat.setText("Latitude : "+ String.valueOf(lati)); | |
longi = location.getLongitude(); | |
txtlong.setText("Longitude : "+ String.valueOf(longi)); | |
} | |
@Override | |
public void onStatusChanged(String s, int i, Bundle bundle) { | |
} | |
@Override | |
public void onProviderEnabled(String s) { | |
} | |
@Override | |
public void onProviderDisabled(String s) { | |
} | |
}; | |
//choix de module : GPS ou Network | |
//manifest : | |
//<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> | |
//<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> | |
boolean gps_enabled = false; | |
boolean network_enabled = false; | |
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); | |
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); | |
Location net_loc = null, gps_loc = null, finalLoc = null; | |
try { | |
if (gps_enabled){ | |
//demande de droit | |
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { | |
// TODO: Consider calling | |
// ActivityCompat#requestPermissions | |
// here to request the missing permissions, and then overriding | |
// public void onRequestPermissionsResult(int requestCode, String[] permissions, | |
// int[] grantResults) | |
// to handle the case where the user grants the permission. See the documentation | |
// for ActivityCompat#requestPermissions for more details. | |
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1340); | |
} | |
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); | |
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, loclisten); | |
} | |
if (network_enabled){ | |
//demande de droit | |
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { | |
// TODO: Consider calling | |
// ActivityCompat#requestPermissions | |
// here to request the missing permissions, and then overriding | |
// public void onRequestPermissionsResult(int requestCode, String[] permissions, | |
// int[] grantResults) | |
// to handle the case where the user grants the permission. See the documentation | |
// for ActivityCompat#requestPermissions for more details. | |
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1340); | |
} | |
net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); | |
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, loclisten); | |
} | |
if (gps_loc != null && net_loc != null) { | |
if (gps_loc.getAccuracy() > net_loc.getAccuracy()) | |
finalLoc = net_loc; | |
else | |
finalLoc = gps_loc; | |
} else { | |
if (gps_loc != null) { | |
finalLoc = gps_loc; | |
} else if (net_loc != null) { | |
finalLoc = net_loc; | |
} | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
//première mise à jour | |
if (finalLoc != null) { | |
lati = finalLoc.getLatitude(); | |
txtlat.setText("Latitude : "+ String.valueOf(lati)); | |
longi = finalLoc.getLongitude(); | |
txtlong.setText("Longitude : "+ String.valueOf(longi)); | |
} | |
//SensorManager | |
//manifest : | |
//<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true" /> | |
//<uses-feature android:name="android.hardware.sensor.compass" android:required="true" /> | |
SensorManager sensman = (SensorManager)getSystemService(this.SENSOR_SERVICE); | |
List listSensor = sensman.getSensorList(Sensor.TYPE_ALL); | |
List listSensorType = new ArrayList(); | |
//Lister tous les capteurs | |
for(int i=0; i<listSensor.size(); i++){ | |
listSensorType.add(listSensor.get(i).toString()); | |
System.out.println(listSensor.get(i).toString()); //0accelel et 3magnetic | |
} | |
//Declarer les deux sensors | |
Sensor accelero = sensman.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); | |
Sensor magnetic = sensman.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); | |
//Listener des sensors | |
SensorEventListener sensoreventlisten = new SensorEventListener() { | |
@Override | |
public void onSensorChanged(SensorEvent sensorEvent) { | |
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { | |
//stocker les valeurs reçues d'accélérometre | |
accelerof=sensorEvent.values; | |
} else if (sensorEvent.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) { | |
//stocker les valeurs reçues de magnétometre | |
magneticf = sensorEvent.values; | |
} | |
//format avec 5 digit | |
DecimalFormat df = new DecimalFormat(); | |
df.setMaximumFractionDigits(5); | |
//Affichage Accelerometre | |
TextView txtaccel = (TextView) findViewById(R.id.txtaccel); | |
txtaccel.setText("Accelerometre : "+df.format(accelerof[0])+" / "+df.format(accelerof[1])+" / "+df.format(accelerof[2])); | |
//Affichage Magnetometre | |
TextView txtmagne = (TextView) findViewById(R.id.txtmagne); | |
txtmagne.setText("Magnetometre : "+df.format(magneticf[0])+" / "+df.format(magneticf[1])+" / "+df.format(magneticf[2])); | |
//calcul d' "Orientation" depuis l'accélération et champs magnétique | |
SensorManager.getRotationMatrix(resultMatrix, null, accelerof, magneticf); | |
SensorManager.getOrientation(resultMatrix, orientation); | |
//Affichage Orientation | |
TextView txtori = (TextView) findViewById(R.id.txtori); | |
txtori.setText("Orientation : "+df.format(orientation[0])+" / "+df.format(orientation[1])+" / "+df.format(orientation[2])); | |
//calcul d'Orientation d'image à affecter | |
float degree = -orientation[0] * 360 / (2 * 3.14159f); | |
degree = (float)(degree+360)%360; | |
//Affecter l'orientation calculée | |
ImageView boussole = (ImageView) findViewById(R.id.boussole); | |
//declinaison magnétique : | |
//on utilise : http://www.geomag.nrcan.gc.ca/calc/mdcal-fr.php | |
//qui nous renvoie la déclinaison concernée en fonction du lieu. | |
//Par exemple : | |
// http://www.geomag.nrcan.gc.ca/calc/mdcal-r-fr.php?date=2018-10-20&latitude=48.846834&latitude_direction=1&longitude=2.3958577&longitude_direction=1 | |
//Switch Déclinaison (Nord Réel) | |
Switch declibtn = (Switch) findViewById(R.id.decli); | |
//Modifier declinaison une seule fois quand le Switch est coché | |
if(declibtn.isChecked()&&!passed)//Nord Réel? | |
{ | |
passed = true; | |
declinaison = getDeclinaison(); | |
} | |
if(!declibtn.isChecked()){ | |
passed = false; | |
declinaison = (float)0; | |
} | |
degree -= 360-declinaison; | |
degree = (float)(degree+360)%360; | |
float ecart = boussole.getRotation()-degree; | |
if((ecart)<0)ecart*=-1; | |
//pour la STABILITE, si l'écart est plus de 2 degrés on remet à jour la rotation d'image | |
if(ecart>2){ | |
boussole.setRotation((int)degree); | |
//Affichage en texte | |
TextView angle = (TextView) findViewById(R.id.angle); | |
angle.setText((int)(360-degree) + "°"); | |
} | |
} | |
@Override | |
public void onAccuracyChanged(Sensor sensor, int i) { | |
} | |
}; | |
//Ajouter les sensors dans Listener | |
sensman.registerListener(sensoreventlisten, accelero, SensorManager.SENSOR_DELAY_NORMAL); | |
sensman.registerListener(sensoreventlisten, magnetic, SensorManager.SENSOR_DELAY_NORMAL); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment