N'hésitez pas à remplir le formulaire pour nous contacter par courriel. Tous les champs sont obligatoires.

Votre nom ou pseudo

Votre adresse e-mail (facultatif)


Contenu de votre message


Entrez le code de validation    FE3SJ


Web View Android

Voici une source de base pour faire un navigateur internet sur Android en Java.

MainActivity.java:

package android.linux.webview;

import java.io.File;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.app.AlertDialog;
import android.content.DialogInterface;


@SuppressLint({ "SetJavaScriptEnabled", "ParserError", "ParserError" })
public class MainActivity extends Activity {
    private WebView webview;
	public static final int intMenu_Exit = 1;
	public static final int intMenu_Refresh = 2;
	public static final int intMenu_Clear_Cache = 3;
	public static final int intMenu_Prefs = 4;
	public static final int intMenu_Eval = 5;
	static int NOTIFICATION_ID = 0;
    public String dataURL;
    public String dataLOGIN;
    public String dataPASSWORD;
	protected ProgressDialog startProgressDialog; 
	protected ProgressDialog myProgressDialog; 
    public static final String PREFS_NAME = "webview_config";
    int mMetric = 0;
    
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
    	savedInstanceState.putString("URL", webview.getOriginalUrl());
        super.onSaveInstanceState(savedInstanceState);
    }
    
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {  
    	myProgressDialog = ProgressDialog.show(MainActivity.this, "", "Restauration de l'activité en cours...", true);
    	super.onRestoreInstanceState(savedInstanceState);
    	String URL = savedInstanceState.getString("URL");
    	dataURL=URL;
    	webview.loadUrl(dataURL);
        webview.requestFocus();
        myProgressDialog.dismiss();
        startProgressDialog.dismiss();
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().startSync();
        setContentView(R.layout.main);
        
        /*check connection*/
        if(isOnline()) { //si connection on affiche le navigateur
        	webview = (WebView)findViewById(R.id.webview);
            webview.setWebViewClient(new WWWViewClient());//permet d'ouvrir les liens url dans le webview et non dans le navigateur
            webview.getSettings().setJavaScriptEnabled(true);
            webview.getSettings().setLoadsImagesAutomatically(true);
            webview.getSettings().setDomStorageEnabled(true);
            webview.addJavascriptInterface(new JSInterface(), "android"); 
            webview.setInitialScale(1); // facteur de zoom initial
            
            webview.getSettings().setSupportZoom(true);
            webview.getSettings().setBuiltInZoomControls(true); // afficher le contrôle de zoom
            webview.getSettings().setUseWideViewPort(true); // activer le double-tap pour zoomer  
            webview.getSettings().setUserAgentString( "Mozilla/5.0 (Linux; U; Android; fr-fr; Nexus S Build/GRK39F) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1 (WebViewApplication)");
            
            webview.loadUrl("http://www.ckdevelop.org");
            dataURL="http://www.ckdevelop.org";
            webview.requestFocus();
            startProgressDialog = ProgressDialog.show(MainActivity.this, "", "Chargement de l'application en cours...", true);
        
        }else{//Sinon on avertie l'utilisateur et on quitte l'application
        	Activity activity = MainActivity.this; // récupération de l'Activity courante
        	Command commandeOui = new Command() {
        	    public void execute() {
        	    	kill();
        	    }
        	};
        	displayYesNoDialog(activity, "Vous n'avez pas d'accès à internet\n\nVérifiez votre connection.", commandeOui);     
        }
    }
    
    
    //retour en arrière
    int menu_plus=0;
    int backClose=0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	if (menu_plus == 1) {
    		webview.loadUrl("javascript:mp_click_hide(); return false");
    		return true;
    	}
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
        	
        	if ( webview.getOriginalUrl() != dataURL ) {
        		backClose=0;
        		webview.goBack();
        		return true;
        	} else {
        		if ((webview.getOriginalUrl() == dataURL) && (backClose == 0)) {
        			Context context = getApplicationContext();
        			Toast.makeText(context, "Cliquer une seconde fois sur retour pour quitter l'application.", Toast.LENGTH_LONG).show();
        			backClose=1;
        			return true;
        		} else if (backClose == 1) {
        			kill();	
        		}
        		
        	}
        }   
        return super.onKeyDown(keyCode, event);
    }
    
    /***************************************************System********************************************/

    //suppression du cache
	public void delCache() {  	
   	 	File dir = getCacheDir();
        if(dir!= null && dir.isDirectory()){
            try{
            File[] children = dir.listFiles();
            if (children.length >0) {
                for (int i = 0; i < children.length; i++) {
                    File[] temp = children[i].listFiles();
                    for(int x = 0; x<temp.length; x++)
                    {
                        temp[x].delete();
                    }
                }
            }
            }catch(Exception e)
            {
                Log.e("Cache", "failed cache clean");
            }
        }
    }
	
	//onDestroy est appelé lorsque finish est invoqué sur l'activité
    @SuppressWarnings("deprecation")
	public void kill() {  
        //demande au système de fermer tout objet de l'application de sorte que l'appli puisse être tuée sans risque
        //true implique que le processus ne sera tué que quand tous les threads auront été fermés
    	((NotificationManager)getSystemService(NOTIFICATION_SERVICE)).cancel(NOTIFICATION_ID); 
        System.runFinalizersOnExit(true);
        //force l'application à se fermer complètement et à ne passer en arrière-plan
        System.exit(0);
    }
	//destruction après Kill();
	@Override
    public void onDestroy() {                            
        super.onDestroy();
        finish();
    }
    
	//pause
    @Override
    public void onPause() {   
    	super.onPause();	
    	SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
        SharedPreferences.Editor editor = settings.edit();
        // Necessary to clear first if we save preferences onPause. 
        editor.clear();
		editor.putInt("Metric", mMetric);
        editor.commit();
    	//statusNotify();
    }
    
    /***************************************************MENU********************************************/
    //Construction du Menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	// TODO Auto-generated method stub
        boolean result = super.onCreateOptionsMenu(menu);
        menu.add(0, intMenu_Exit, 0, R.string.menu_exit).setIcon(R.drawable.ic_quit);
        SubMenu optionsMenu = menu.addSubMenu("Options").setIcon(R.drawable.ic_prefs);
        //optionsMenu.add(0, intMenu_Prefs, 0, R.string.menu_pref);
        optionsMenu.add(0, intMenu_Eval, 0, R.string.menu_eval);
        optionsMenu.add(1, intMenu_Refresh, 0, R.string.menu_refresh);
        optionsMenu.add(2, intMenu_Clear_Cache, 0, R.string.menu_clear_cache); 
        return result;
    }
    
    //gestion du menu
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
    	 switch (item.getItemId()) {
         //clic sur le menu contact
         //clic sur menu sortie
         case intMenu_Exit:
        	 kill();
             return true;
         case intMenu_Prefs:
        	Intent intent = new Intent(MainActivity.this, PrefsActivity.class);
        	startActivity(intent);  
        	return true;
         case intMenu_Clear_Cache:
        	delCache();  
        	return true;    
         case intMenu_Eval:
        	 Activity activity = MainActivity.this; // récupération de l'Activity courante
         	Command commandeOui = new Command() {
         	    public void execute() {
         	    	Intent intent2 =new Intent(Intent.ACTION_VIEW);
         	    	intent2.setData(Uri.parse("market://details?id=com.chronocarpe.chronocarpe"));
         	    	startActivity(intent2);  
         	    }
         	};
         	displayYesNoDialog(activity, "Vous allez être redirigé vers le PlayStore de Google.", commandeOui); 
         	return true;
    	case intMenu_Refresh:
    		webview.reload();
    		return true;
    	}
        return super.onOptionsItemSelected(item);
    }
    
    /***************************************************Internet********************************************/
    //Vu du navigateur internet
    private class WWWViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }
    
    //interface Javascript
    @SuppressLint("ParserError")
	class JSInterface {
    	@SuppressLint("ParserError")
        /** Show a toast from the web page */
        public void menu_plus_show() {
            menu_plus=1;       
        }
        public void menu_plus_hide() {
            menu_plus=0;
        }
        public void action_wait() {
        	startProgressDialog.dismiss();
        	myProgressDialog = ProgressDialog.show(MainActivity.this, "", "Chargement de la page en cours...", true); 
        }
        public void action_wait_stop() {
        	myProgressDialog.dismiss(); 
        }
        public void alert(String msg) {
        	//startProgressDialog.dismiss();
        	AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        	builder.setMessage(msg);
        	builder.setNegativeButton("Fermer", null);
        	builder.show();
        	//myProgressDialog = ProgressDialog.show(MainActivity.this, "",msg, true); 
        }
    }
    
    //Test connectivité
    public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }
    
    /***************************************************Boite de dialogue********************************************/

    public void displayYesNoDialog(Activity context, String string,
        Command commandeOui) {
    	AlertDialog.Builder builder = new AlertDialog.Builder(context);
    	builder.setMessage(string);
    	builder.setNegativeButton("Annuler", null);
    	builder.setPositiveButton("Accéder", commandeOui);  	
    	builder.show();
    }

    
    abstract public class Command implements DialogInterface.OnClickListener {
        public final void onClick(DialogInterface dialog, int which) {
            execute();
            dialog.dismiss();
        }
     
        abstract public void execute();
    }
}

LAYOUT main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:animateLayoutChanges="true"
    android:orientation="horizontal"
    android:overScrollMode="never"
    android:scrollbarAlwaysDrawVerticalTrack="false"
    android:scrollbarStyle="insideOverlay"
    android:scrollbars="none" >

	<WebView
    	android:id="@+id/webview"
    	android:layout_width="fill_parent"
    	android:layout_height="fill_parent"
    	android:overScrollMode="never"
    	android:scrollbarAlwaysDrawVerticalTrack="false"
    	android:scrollbars="none" />

</LinearLayout>

PrefsActivity.java:

package android.linux.webview;

import android.app.Activity;
import android.os.Bundle;

public class PrefsActivity extends Activity {
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.prefs);
    } 
}

LAYOUT prefs.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <CheckBox
        android:id="@+id/checkBox2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

VALUES strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="co_name">BeHuman</string>
    <string name="url_co">http://www.ckdevelop.org</string>
    <string name="app_name">BeHuman</string>
    <string name="url_app">http://www.ckdevelop.org</string>
    
    <string name="menu_exit">Fermer</string>
    <string name="menu_pref">Préférences</string>
    <string name="menu_refresh">Rafraîchir</string>
    <string name="menu_clear_cache">Vider le cache</string>
    <string name="menu_eval">Évaluer l\'application</string>
</resources>

VALUES styles.xml:

<resources>

    <style name="AppTheme" parent="android:Theme.Light" />

</resources>

 

Écrire un commentaire


Capcha
Entrez le code de l'image 4hq7p