Mobile-Device (50)


Clipboard Manager in Android Web View

Inter-workings JavaScript and Java Layer: use Clipboard Manager APIs directly in WebView component of Android library:

// no permission require in your manifest file of Android project

        ...


// start code
@SuppressLint({"SetJavaScriptEnabled","JavascriptInterface"})
public class MainActivity extends Activity {
public WebView webView;
ClipboardManager myClipboard;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main); // source activity_main.xml
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
webView.setWebViewClient(new WebViewClient());
// important set Web Chrome Client
webView.setWebChromeClient(new WebChromeClient());
webView.loadUrl(url); //local or remote
}
// final class to add in Web App
final class WebAppInterface {
        Context mContext;

        /** Instantiate the interface and set the context */
        WebAppInterface(Context c) {
            mContext = c;
        }
        /**
            Interface to use in web application
        */
        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@SuppressLint("NewApi")
	@JavascriptInterface
	    public void copyToClipboard(String text) {
	        try {
	        	myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
	        	ClipData myClip;
	        	myClip = ClipData.newPlainText("text", text);
	        	myClipboard.setPrimaryClip(myClip);
	        	Toast.makeText(getApplicationContext(), "Text Copied",Toast.LENGTH_SHORT).show();
	        } catch (Exception e) {
	        	Toast.makeText(getApplicationContext(), "Copy failed: " + e.toString(), Toast.LENGTH_SHORT).show();
	        }
	    }
    }

}
// Now open html file in www folder of you Android project












HTML5 Editor Advanced

HTML5 Editor Advanced è la mia nuova applicazione mobile ibrida che impiega il metodo “addJavascriptInterface” offerto dalla libreria Android per la scrittura e la lettura dei files. Il progetto è in continua evoluzione ed è ispirato a l’applicazione web server jsfiddle come editor html, css e javascript. Puoi caricare le più celebri librerie javascript con il metodo CDN per lo sviluppo direttamente sul tuo device mobile dei tuoi progetti targati HTML5. È sottinteso che puoi impiegare tutte le api, includendo anche quelle più recenti, del core di javascript e se desideri archiviare i tuoi dati puoi scegliere tra le tre più diffuse opzioni: localStorage, IndexedDB e Web SQL. Per la prossima release di HTML5 Editor ho deciso di includere anche il compilatore HAML e SASS e l’highlight code per la validazione del codice html, css e javascript.

Update 02.07.2014: Nuova Interfaccia grafica e nuove funzioni per HTML5 editor for Android
Update 30.08.2014: Ho aggiunto una nota importante che permette di rendere l’applicazione compatibile anche con le verisioni 4.2 di Android e superiori.

Get it on Google Play




3D Model Droid Viewer

This android app provides a 3d object, 3d Studio Max and 3d stl viewer for presenting 3d models and small scenes on a web page. You can to save render result in png, jpg, tiff and pdf and you can to change render mode and image definition. In the project are also available preset modes for the rotation of the object and a useful console that tracks the user’s actions.

Get it on Google Play




Add Javascript Interface Android write pdf with iText

You use iText® under AGPL license for opensource project to create and manipulate pdf documents


    
    ...

// for iText library import this packages
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.html.simpleparser.HTMLWorker; // simple parser html
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.Paragraph;

// start code
@SuppressLint({"SetJavaScriptEnabled","JavascriptInterface"})
public class MainActivity extends Activity {
public WebView webView;
 
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main); // source activity_main.xml
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
webView.setWebViewClient(new WebViewClient());
// important set Web Chrome Client
webView.setWebChromeClient(new WebChromeClient());
webView.loadUrl(url); //local or remote
}
// final class for save and write file in external storage
final class WebAppInterface {
        Context mContext;
 
        /** Instantiate the interface and set the context */
        WebAppInterface(Context c) {
            mContext = c;
        }
         @SuppressWarnings("deprecation")
	public void writeToPdf(String data, String filename, String tag) {
	        try {
	        	File root = android.os.Environment.getExternalStorageDirectory();
	        	File dir = new File (root.getAbsolutePath() + "/folderpdf/");
	        	dir.mkdirs();
	        	File file = new File(dir, filename + ".pdf");
	        	try {
	            	       Document document = new Document();
			       PdfWriter.getInstance(document, new FileOutputStream(file));
			       document.open();
			       @SuppressWarnings("deprecation")
                               document.add(new Paragraph(data));                               
                               // if you want to set Font and Alignment
                               // This tutoria is getting started
                               // for all advanced settings you consult documentation iText
			       /* if you want to parse html data use this code
                                  HTMLWorker htmlWorker = new HTMLWorker(document);
			          htmlWorker.parse(new StringReader(data)); */
			       document.close();
				} catch (DocumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        }
	        catch (IOException e) {
	            Log.e(tag, "File write failed: " + e.toString());
	        }
	    }
    }
 
}
// Now open html file in www folder
 






Text To Speech Api HTML5 – Android

New useful function bridge between HTML5 and Android to listen text from input textarea

package com.example.tts;
// here imports in Eclipse command "Source->Organize Imports"
.......
@SuppressLint({ "SetJavaScriptEnabled", "JavascriptInterface" })
public class MainActivity extends Activity implements OnInitListener {
       private TextToSpeech tts;
       private WebView ttsweb;
        @Override
   public void onConfigurationChanged(Configuration newConfig){
	    super.onConfigurationChanged(newConfig);
	}
	@SuppressWarnings("deprecation")
   protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);	
	setContentView(R.layout.activity_main);
        tts = new TextToSpeech(this, this);
        ttsweb = (WebView) findViewById(R.id.webtweetsfeeds);
        ttsweb.getSettings().setJavaScriptEnabled(true);
	ttsweb.getSettings().setLoadWithOverviewMode(false);
	ttsweb.getSettings().setUseWideViewPort(false);
	ttsweb.getSettings().setBuiltInZoomControls(false);
	ttsweb.getSettings().setPluginState(WebSettings.PluginState.ON);
	ttsweb.getSettings().setRenderPriority(RenderPriority.HIGH);
	ttsweb.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        ttsweb.setWebChromeClient(new WebViewChromeClient());
        ttsweb.setWebViewClient(new WebViewClient());
        // bridge interface java/javascript
        ttsweb.addJavascriptInterface(new WebAppInterface(this), "Android");
	ttsweb.loadUrl("file:///android_asset/www/index.html");
   }
  final class WebAppInterface {
	    Context mContext;
	   /*My interface*/
	    /** Instantiate the interface and set the context */
	    WebAppInterface(Context c) {
	        mContext = c;
	    }
	    public void ttsInput(String inputText, String setLang){
	    	tts.setLanguage(new Locale(setLang));
	    	Toast.makeText(getApplicationContext(), tts.toString(), 
	    		      Toast.LENGTH_SHORT).show();
	    	tts.speak(inputText, TextToSpeech.QUEUE_FLUSH, null);	    	
	    }
	    public void ttsStop(){
	    	if (tts != null) {
	            tts.stop();
	           // tts.shutdown();
	        }	
	    }
	   	    
	}
       public void onInit(int status) {
		// TODO Auto-generated method stub
		return;
	}
}
// Now open html file index in asset/www main folder project Android and to add this code:
// javascript functions 
function tts(){
	try{
		var ttsinout = document.getElementById("textarea").value;
		var setLanguage = document.getElementById("setlanguage").value;
		Android.ttsInput(ttfeeds, setLanguage);
	} catch(e){
		alert("Error Description: " + e.message);
	}
}

function stoptts(){
	try{
		Android.ttsStop();
	} catch(e){
		alert("Error Description: " + e.message);
	}
}
document.getElementById("ttstop").addEventListener("click", stoptts, false);
document.getElementById("tts").addEventListener("click", tts, false);
// end javascript

// start html