• Pour avoir accès au forum les nouveaux membres inscrits doivent obligatoirement se présenter et attendre que leur présentation soit approuvée par un membre du Staff.
  • Vous n'arrivez pas a publier ou a télécharger ! Merci de lire le Réglement
  • Spécialiste Electronique auto a Paris.

    Specialiste Auto vous proposes avec une Garantie a vie !!!! Suppression FAP ( DEFAP ) Suppression ADBLUE Reparation Calculateur Reparation EZS ELV Reprogrammation Adaptation Boite de vitesse Systeme hybrid Boitier module OCCASSION / NEUF Désactivation Volets de tubulures d'admission ...

    Plus d'information Clique ici

    Contacter nous au 0754373786

    Envoi Possible de Toute la France si vous étes pas de Paris

Tutoriel Réaliser un mini navigateur Web

The Mask

Que la Famille
Ancien Staff
Membre Actif
Inscrit
4 Mars 2014
Messages
1,251
Reaction score
4,137
Points
4,158
I. Navigateur Web
Nous allons donc réaliser un petit navigateur Web. Grâce à une requête HTTP de type GET, nous allons récupérer le code HTML d'une page et grâce au WebView, nous allons afficher la page correspondante à l'URL que l'on aura saisi.

Créez un projet, nommez-le comme vous le souhaitez, personnellement j'ai utilisé la version 1.6 d'Android.

I-A. Le fichier AndroidManifest.xml
Pour que l'application puisse fonctionner correctement, elle devra avoir accès à Internet. Il faut donc donner l'autorisation d'accès à Internet à l'application. Pour cela, ouvrez le fichier AndroidManifest.xml et rajoutez la ligne suivante :


Code:
<uses-permission android:name="android.permission.INTERNET" />
I-B. Le fichier main.xml
Notre interface sera composée d'un EditText qui jouera le rôle de la barre d'adresse, d'un Button permettant de lancer la requête HTTP en utilisant l'URL que l'on aura indiquée dans l'EditText et un WebView qui se chargera d'afficher la page Web. Voici donc le fichiermain.xml :

Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" >

<LinearLayout
android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" >
<EditText android:id="@+id/EditText"
android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1"
android:layout_gravity="bottom"
android:text="http://"
/>

<Button android:id="@+id/Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go"
/>
</LinearLayout>

<WebView android:id="@+id/WebView"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
/>

</LinearLayout>
I-C. Le code JAVA
Comme à mon habitude, j'ai commenté mon code je pense que cela suffira pour comprendre, mais toutes les questions, remarques ou suggestions sont les bienvenues, alors n'hésitez pas à laisser un petit commentaire.

Code:
package com.tutomobile.android.requetehttp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;

public class Tutoriel7_Android extends Activity {

private static final String LOG_TAG = "Log : ";
private final String mimeType = "text/html";
private final String encoding = "utf-8";
private String url;
private String pageWeb;
private WebView webView;
private EditText editText;
private Button button;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

//On récupère l'EditText, le WebView, et le Button grâce au ID
editText = (EditText) findViewById(R.id.EditText);
webView = (WebView) findViewById(R.id.WebView);
button = (Button) findViewById(R.id.Button);

//On affecte un évènement au bouton
button.setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View v) {
//création d'un nouveau Thread pour libérer l'UI Thread le plus tôt possible (merci tails)
new Thread(){
public void run(){

//on récupère l'url présente dans l'EditText
url = editText.getText().toString();

try {
//on récupère le code HTML associé à l'URL que l'on a indiqué dans l'EditText
pageWeb = Tutoriel7_Android.getPage(url);

//on autorise le JavaScript dans la WebView
webView.getSettings().setJavaScriptEnabled(true);
//on charge les données récupérées dans la WebView
webView.loadDataWithBaseURL("fake://not/needed", pageWeb, mimeType, encoding, "");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
);


}

public static String getPage(String url) throws ClientProtocolException, IOException{
StringBuffer stringBuffer = new StringBuffer("");
BufferedReader bufferedReader = null;

try{
//Création d'un DefaultHttpClient et un HttpGet permettant d'effectuer une requête HTTP de type GET
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet();

//Création de l'URI et on l'affecte au HttpGet
URI uri = new URI(url);
httpGet.setURI(uri);

//Execution du client HTTP avec le HttpGet
HttpResponse httpResponse = httpClient.execute(httpGet);

//On récupère la réponse dans un InputStream
InputStream inputStream = httpResponse.getEntity().getContent();

//On crée un bufferedReader pour pouvoir stocker le résultat dans un string
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

//On lit ligne à ligne le bufferedReader pour le stocker dans le stringBuffer
String ligneCodeHTML = bufferedReader.readLine();
while (ligneCodeHTML != null){
stringBuffer.append(ligneCodeHTML);
stringBuffer.append("\n");
ligneCodeHTML = bufferedReader.readLine();
}

}catch (Exception e){
Log.e(LOG_TAG, e.getMessage());
}finally{
//Dans tous les cas on ferme le bufferedReader s'il n'est pas null
if (bufferedReader != null){
try{
bufferedReader.close();
}catch(IOException e){
Log.e(LOG_TAG, e.getMessage());
}
}
}

//On retourne le stringBuffer
return stringBuffer.toString();
}
}
I-D. Résultat
Vous pouvez désormais lancer votre application. Entrez une adresse dans la barre d'adresse et cliquez sur "GO". La page Web devrait s'afficher dans le WebView comme sur la capture d'écran ci-dessous.

 

Auteur Sujets similaires Forum Réponses Date
mouton "service information" BMW mini Questions - Aide 0
mouton Question "service information" BMW mini Questions - Aide 0
mouton Question "service information" BMW mini Questions - Aide 0
popostef Série Recherche Mini loup en torrent Torrent Films,Séries,musique 0
C Bibliothèque RTA Cherche RTA Mini R56 Bibliothèque RTA 0
harissa Loki la nouvelle suite de mini-série site de streaming vérifier 1
M3RS AVIS Ajout dossier Mini Important Règlement section Auto 6
Manu62 schema electrique mini Questions - Aide 6
M3RS Rubrique Mini Bmw 9
glaieul [Résolu] Revue mini Questions - Aide 9
turbovnt CODING PROGRAM MINI COOPER S Gt1 0
laurent68 ™ Homebrew [PSC] La PSP dans la PlayStation Classic Mini Hack/ Homebrew 0
laurent68 ™ Homebrew [PSC] Ps Classic Mini GUI Ultimate v2 Hack/ Homebrew 6
laurent68 ™ Homebrew [PSC] PS Classic Mini Ultimate Hack/ Homebrew 3
laurent68 ™ Homebrew [Psc] PS Classic Mini GUI compatible BleemSync Hack/ Homebrew 0
laurent68 ™ Discussion [Switch/NES Mini] Nintendo poursuit un californien pour piratage Discussion 0
laurent68 ™ Homebrew [PS Mini] BleemSync v0.3.2 disponible (maj 13.12.2018) Hack/ Homebrew 0
laurent68 ™ Homebrew [PS Mini] PSClassicTool v1.1 Hack/ Homebrew 0
laurent68 ™ Homebrew [PS Mini] BleemSync v0.3.1 Hack/ Homebrew 1
laurent68 ™ Homebrew [PS Mini] PSClassicTool v1.1 Hack/ Homebrew 0
laurent68 ™ Homebrew [PS Mini] BleemSync pour profiter pleinement de votre PS Classic Hack/ Homebrew 0
laurent68 ™ Homebrew [PS Mini] PSClassicEdit v0.0.1 Hack/ Homebrew 0
laurent68 ™ Discussion [PS Mini] Lolhack permet d'accéder au menu caché Discussion 0
laurent68 ™ Hack [PS Mini] Yifan Lu détaille le dump du bootrom Hack/ Homebrew 0
laurent68 ™ Homebrew [PS Mini] Un loader pour la PlayStation Classic Hack/ Homebrew 0
laurent68 ™ Discussion [PS Mini] La console est désormais complètement hackée Discussion 0
laurent68 ™ Discussion [PS Mini] Un menu caché dans la PS Classic Discussion 0
laurent68 ™ Discussion [PS Mini] Le mise à nue de la PlayStation Classic Discussion 0
laurent68 ™ Homebrew [SNES / NES MINI] hakchi2 CE v3.5.2 Hack/ Homebrew 1
laurent68 ™ Hack [SNES Mini] La Nintendo DS émulée parfaitement Hack/ Homebrew 0
laurent68 ™ Discussion [PSX Mini] PCSX ReARMed utilisé dans la PSX Classic Discussion 0
laurent68 ™ Discussion [N64 Mini] La Mini N64 fuite en images et dévoile sa liste de jeux Discussion 2
laurent68 ™ Hack [Mini SNES/ NES] Hakchi2 v2.31 officiel de ClusterM Hack/ Homebrew 4
laurent68 ™ Hack [SNES Mini] Hakchi2 v2.30 de ClusterM Hack/ Homebrew 2
laurent68 ™ Hack [Snes Mini] hakchi2 CE v1.1.0 Hack/ Homebrew 0
laurent68 ™ Discussion [SNES Mini] RetroArch bientôt officiellement porté sur Super NES Mini Discussion 0
laurent68 ™ Hack [SNES Mini] La SuperNes Mini supporte l'émulation MSU-1 (SuperNes CD) Hack/ Homebrew 1
laurent68 ™ Homebrew [SNES Mini] Créer un USB Host sur votre Super NES Mini Hack/ Homebrew 1
laurent68 ™ Discussion [SNES Mini] Retro Engineering du multipad pour jouer à 5 sur la Super NES Mini Discussion 0
laurent68 ™ Discussion [SNES Mini] Cluster propose NES2Wii, les plans pour adapter vos anciens gamepads Discussion 3
laurent68 ™ Homebrew [SNES Mini] Collection de thèmes personnalisés pour la SNES Mini Hack/ Homebrew 0
laurent68 ™ Homebrew [SNES Mini] Le set KMFDManic Core/Bios/HMOD pour NES et SNES Mini Hack/ Homebrew 0
laurent68 ™ Homebrew [SNES Mini] De nouveaux effets sonores personnalisés de yyoossk Hack/ Homebrew 0
laurent68 ™ Homebrew Wii / Wii U [SNES mini] Hakchi2 v2.21e et le module RetroArch v1.0c Hack/ Homebrew 0
laurent68 ™ Homebrew [SNES mini] Personnalisation du module wallpaper avec Wall Hack Hack/ Homebrew 0
laurent68 ™ Hack [SNES mini] Dualboot NES/SNES mini Hack/ Homebrew 0
laurent68 ™ Hack [SNES mini] Hakchi2 v2.21b et RetroArch Mod v0.9b Hack/ Homebrew 0
laurent68 ™ Homebrew [SNES Mini] Les perfect scanlines accessibles dans Hakchi2 Hack/ Homebrew 0
laurent68 ™ Hack [SNES mini] Cluster_M propose Hakchi2 v2.20 et découvre un filtre d'affichage Hack/ Homebrew 0
laurent68 ™ Homebrew [SNES mini] Hakchi2 2.020 RC2 officielle de Cluster_M Hack/ Homebrew 0
Sujets similaires


















































Cliquez ici pour vous connecter en utilisant votre compte social
AdBlock Détecté

Nous comprenons, les publicités sont ennuyeuses !

Bien sûr, le logiciel de blocage des publicités fait un excellent travail pour bloquer les publicités, mais il bloque également les fonctionnalités utiles de notre site Web. Pour la meilleure expérience du site, veuillez désactiver votre AdBlocker.

J'ai désactivé AdBlock