Programmation Android/Exemples/localisateur

Programmation Android
Plan
Modifier ce modèle

La localisation est basée sur les données sortantes du composant GPS du dispositif.

Objectif modifier

Enregistrer sur l'appareil et diffuser ses coordonnées GPS.

Réalisation modifier

  • Le localisateur GPS passe les données qui sont sauvegardées dans des fichiers.
  • Lorsque le smartPhone est connecté, les champs de données sont postés à un service distant. (ex:php ci-joint).


Avant de coder le script, il faut mettre les permissions dans le manifeste...

./AndroidManifest.xml modifier

À l'exception des permissions on ne modifie pas le manifeste
  • Access_fine_location pour la localisation GPS
  • Internet pour l'accès à internet
  • Write_external_storage pour écrire sur la carte externe
  • Get_accounts pour accéder aux données du compte
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.gpslocator"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="7"
        android:targetSdkVersion="7" />

        <!-- DÉBUT INSERTION DANS LE MANIFESTE :
                Les permissions pour accéder aux options du dispositif par l'application
         -->
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- localisation GPS -->
        <uses-permission android:name="android.permission.INTERNET" /> <!-- accès internet -->
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- accès à la carte SD -->
        <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <!-- accès à la base de données de compte -->
        <!-- FIN INSERTION -->

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.gpslocator.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

./src/com/example/gpslocator/MainActivity.java modifier

Ce script est le cœur de l'application.
// les imports sont ajoutés dans Eclipse presque dynamiquement : cf utilisation d'Eclipse
package com.example.gpslocator;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.File;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.view.Menu;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;

/**
 *  Ceci est l'unique fichier de l'app
 */
public class MainActivity extends Activity
{
    @Override
    // onCreate est la méthode d'entrée dans l'application. Quand l'instance de l'appli est créée on exécute ...
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // on utilise le LocationManager pour accéder à la localisation
        LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        // on implémente le location listener
        LocationListener mlocListener = new MyLocationListener();
        
        mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    public class MyLocationListener implements LocationListener
    {
        // mettre l'url du postService
        public String postService = "http://UrlDuService";
        
        // mettre le chemin du repertoire de sauvegarde des fichiers de données
        public String cropPath = "/download/";
        public String cropName = "a";
        public String cropExtension = "psg";
        public int count = 0;
                
        // prend le dernier increment de fichier sauvé
        public int getLastCropNumber()
        {
            int nmb=0;
            String[] fileList = new File(Environment.getExternalStorageDirectory()+this.cropPath).list();

            try
            {
                if(fileList.length>0)
                {
                    for(int i=0;i<fileList.length;i++)
                    {
                        if(fileList[i].endsWith("."+this.cropExtension))
                        {
                            int tmp = Integer.parseInt(fileList[i].split("\\.")[1]);
                            if(nmb<tmp) nmb=tmp;
                        }
                    }
                        
                }
            }
            catch(Exception e)
            {
                // todo
            }
            return nmb;
        }
        
        // lorsque la localisation change
        public void onLocationChanged(Location loc)
        {
            loc.getLatitude();
            loc.getLongitude();

            String Text = loc.getLatitude() + ":" + loc.getLongitude();

            try
            {
                pD(Text);
                sendF();
            }
            catch (Exception e)
            {
                // todo                        
            }
        }
        
        // on prends les emails des comptes enregistrés
        public String getEmailAccount()
        {
            AccountManager manager = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE);
            Account[] accounts = manager.getAccounts();
            //Account[] accounts = manager.getAccountsByType("com.google"); // google only
            List<String> possibleEmails = new LinkedList<String>();

            for (Account account : accounts)
            {
                possibleEmails.add(account.name);
            }
            
            if(!possibleEmails.isEmpty() && possibleEmails.get(0) != null)
            {
                String email = possibleEmails.get(0);
                String[] parts = email.split("@");
                
                if(parts.length > 0 && parts[0] != null)
                    return email;
                else
                    return "nobody";
                
            }
            else
                return "nobody";
        }
        
        // postData : passe les données GPS à saveCrop
        public void pD(String s) throws IOException
        {
            try
            {
                saveCrop(android.text.format.DateFormat.format("yyyy-MM-dd hh:mm:ss", new java.util.Date())+"-"+s+"/");
                this.count++;
                if(this.count>95)
                {
                     this.count=0;
                }
                
            }
            catch (IOException e)
            {
                // todo
            }
        }
        
        // envoi de contenu de fichier ...
        public boolean sendF()
        {
            try
            {
                // crée un client http
                HttpClient httpclient = new DefaultHttpClient();

                // met le http post en place
                HttpPost httppost = new HttpPost(this.postService);

                List nVP = new ArrayList(2);
                nVP.add(new BasicNameValuePair("usr", "damiz"));

                String[] fileList = new File(Environment.getExternalStorageDirectory()+this.cropPath).list();

                if(fileList.length>0)
                {
                    for(int i=0;i<fileList.length;i++)
                    {
                        if(fileList[i].endsWith(cropExtension))
                        {
                            String cPath = this.cropPath+this.cropName+"."+this.getLastCropNumber()+"."+this.cropExtension;

                            // mets le repertoire de fichier en live
                            nVP.add(new BasicNameValuePair("ctc", getFile(Environment.getExternalStorageDirectory()+cPath)));
                            // envoit le post
                            httppost.setEntity(new UrlEncodedFormEntity(nVP));

                            HttpResponse response = httpclient.execute(httppost);

                            // efface le fichier si envoyé
                            File f = new File(Environment.getExternalStorageDirectory()+cPath);
                            if (f.exists())
                            {
                                f.delete();
                            }
                        }
                    }
                }
            }
            catch(Exception e)
            {
                // todo
            }
            return true;
        }
        
        // prend le contenu du fichier
        public String getFile(String filePath) throws java.io.IOException
        {
            BufferedReader reader = new BufferedReader(new FileReader(filePath));
            String line, results = "";
            while( ( line = reader.readLine() ) != null)
            {
                results += line;
            }
            reader.close();
            return results;
        }
        
        // prend le contenu du string
        public String getString(String file)
        {
            File sdcard = Environment.getExternalStorageDirectory();

            //Prend le fichier suivant
            File f = new File(sdcard,"/download/"+file+".txt");

            //Lit le texte du fichier
            StringBuilder text = new StringBuilder();

            try
            {
                BufferedReader br = new BufferedReader(new FileReader(f));
                String line;

                while ((line = br.readLine()) != null)
                {
                    text.append(line);
                    text.append('\n');
                }
            }
            catch (IOException e)
            {
                // todo
            }
            return text.toString();
        }
        
        // enregistre la donnée dans un fichier
        public void saveCrop(String s) throws IOException
        {
            int cropCount=this.getLastCropNumber();
            if(this.count>90)
            {
                //
                cropCount++;this.count=0;
            }
            FileWriter f = new FileWriter(Environment.getExternalStorageDirectory() 
                + this.cropPath+this.cropName+"."+(cropCount)+"."+this.cropExtension, true);
            try
            {
                f.write(s);
            }
            finally
            {
                f.close();
            }
        }

        public void onProviderDisabled(String provider)
        {
            // todo
        }

        public void onProviderEnabled(String provider)
        {
             // todo
        }

        public void onStatusChanged(String provider, int status, Bundle extras)
        {
             // todo
        }
    }/* End of Class MyLocationListener */
}

exemple du service distant modifier

Le service distant reçoit le post et le traite. Pour l'exemple voici un service PHP qui enregistre les données. Il est contacté par exemple par : http://urlDuSite/service.php

<?php /* GPS LOCATOR */

try
{
    // filing
    $f = $_POST['usr'].".txt";
    $fh = fopen($f,'a');
    $s = date("d.m.y G:i:s").' '.$_POST['ctc']."\n";
    fwrite($fh, $s);
    fclose($fh);
    
    echo '1';
    
    // emailing
    $to      = 'yourEmail@server.com';
    $subject = 'gps-'.$_POST['usr'];
    $message = $s;
    $headers = 'From: /webServices/'.$_POST['usr'].'@g.php' . "\r\n" .
     'Reply-To: serverEmail@server.com' . "\r\n" .
     'X-Mailer: PHP/' . phpversion();
    
    //mail($to, $subject, $message, $headers);
    
}catch(Exception $ex){
    echo '0';
}

?>