**Hi WebView for my application when there is no internet application opens and the site address is displayed for him when there is no internet error.I want to open the HML page, but even though I tried to help thank you.
-----------------------------------------------------------------------------------------------------------**
example
java
package com.app.xxxx;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class WebviewInits {
WebView webView;
SwipeRefreshLayout swipeRefreshLayout;
ProgressBar progressBar;
Context context;
public WebviewInits(WebView webView, SwipeRefreshLayout swipeRefreshLayout, ProgressBar progressBar,Context context) {
this.webView = webView;
this.swipeRefreshLayout = swipeRefreshLayout;
this.progressBar = progressBar;
this.context=context;
}
public void initWeb(){
webView.getSettings().setJavaScriptEnabled( true );
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setAppCachePath("caches");
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setSavePassword(true);
webView.getSettings().setSaveFormData(true);
offlineLoad();//TODO Delete if you don't want offline load
webView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
context.startActivity(intent);
}
});
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.loadUrl(webView.getUrl());
}
});
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (!swipeRefreshLayout.isRefreshing()){ //If you didn't refresh the page by using swiperefresh it will show progressbar.
progressBar.setVisibility(View.VISIBLE);
}
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("https://play.google.com/") || url.startsWith("http://play.google.com/")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
Activity host = (Activity) view.getContext();
host.startActivity(intent);
return true;
} catch (ActivityNotFoundException e) {
// Google Play app is not installed, you may want to open the app store link
Uri uri = Uri.parse(url);
view.loadUrl("https://play.google.com/store/apps/" + uri.getHost() + "?" + uri.getQuery());
return false;
}
}
return false;
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return super.shouldOverrideUrlLoading(view, request);
}
#Override
public void onPageFinished(WebView view, String url) {
progressBar.setVisibility(View.INVISIBLE); //It will hide progressbar because our page loaded.
if (swipeRefreshLayout.isRefreshing()){
swipeRefreshLayout.setRefreshing(false); //This will hide swiperefresh icon if we refreshed.
}
super.onPageFinished(view, url);
}
});webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
}
//TODO Offline Cache Load
public void offlineLoad(){
webView.getSettings().setAppCacheMaxSize( 5 * 1024 * 1024 ); // 5MB Size of storage that it will take
webView.getSettings().setAppCachePath( context.getApplicationContext().getCacheDir().getAbsolutePath() );
webView.getSettings().setAllowFileAccess( true );
webView.getSettings().setAppCacheEnabled( true );
webView.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT ); // load online by default
if ( !WebviewInits.isNetworkAvailable(context) ) { // loading offline
webView.getSettings().setCacheMode( WebSettings.LOAD_CACHE_ELSE_NETWORK );
}
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null
// otherwise check if we are connected
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
}
If you want to handle error in WebView,
You should override onReceivedError according to the following code,
private class MyWebViewClient extends WebViewClient {
.
.
.
// api<23
#Override
public void onReceivedError(WebView view, int errorCode, String description, String url) {
view.stopLoading();
webview.loadUrl("file:///android_asset/error/error.html"); // load error page from asset folder
// handle error
}
// api> 23
#Override
#TargetApi(android.os.Build.VERSION_CODES.M)
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
view.stopLoading();
webview.loadUrl("file:///android_asset/error/error.html"); // load error page from asset folder
// handle error
// super.onReceivedError(view, request, error);
}
.
.
.
}
also, you can check the connection in shouldOverrideUrlLoading, and if is not connected load error page, try this :
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!isNetworkAvailable(getApplicationContext())) {
showCustomErrorPage();
return true;
}
.
.
.
}
showCustomErrorPage function :
private void showCustomErrorPage() {
webview.loadUrl("file:///android_asset/error/error.html");
}
Related
I have WebView which works fine for file upload but when I click on files to open or download, nothing happens. but in normal browser when I click on file it is opened successfully. the intention of code is to open the file when it is clicked. file choose chrome extension is fine. I think there is need to add some code in WebViewListner block.
The activity code is here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.Net;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Webkit;
using Android.Widget;
namespace smartbookapp
{
[Activity(Label = "JobActivity")]
public class JobActivity : Activity
{
public WebView webview;
public IValueCallback mUploadMessage;
public static ProgressBar progressBar;
public static int FILECHOOSER_RESULTCODE = 1;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Jobs);
webview = FindViewById<WebView>(Resource.Id.JobView);
// show progress bar
progressBar = FindViewById<ProgressBar>(Resource.Id.progressBar);
//
webview.Settings.JavaScriptEnabled = true;
webview.Settings.SetAppCacheEnabled(true);
webview.Settings.AllowFileAccess = true;
webview.Settings.BuiltInZoomControls = true;
webview.SetWebViewClient(new WebViewListener());
webview.SetWebChromeClient(new JobWebChromeClient(this));
webview.LoadUrl("https://smartbook.pk/Jobs/index");
//
}
//
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
if (requestCode == FILECHOOSER_RESULTCODE)
{
if (null == mUploadMessage) return;
Android.Net.Uri[] result = data == null || resultCode != Result.Ok ? null : new Android.Net.Uri[] { data.Data };
try
{
mUploadMessage.OnReceiveValue(result);
}
#pragma warning disable CS0168 // Variable is declared but never used
catch (Exception e)
#pragma warning restore CS0168 // Variable is declared but never used
{
}
mUploadMessage = null;
}
base.OnActivityResult(requestCode, resultCode, data);
}
// webview listener code here
public class WebViewListener : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, IWebResourceRequest request)
{
view.LoadUrl(request.Url.ToString());
return true;
}
public override void OnPageStarted(WebView view, string url, Android.Graphics.Bitmap favicon)
{
progressBar.Progress = view.Progress;
}
public override void OnLoadResource(WebView view, string url)
{
progressBar.Progress = view.Progress;
}
public override void OnPageFinished(WebView view, string url)
{
progressBar.Progress = 0;
}
}
public override bool OnKeyDown(Keycode keyCode, KeyEvent e)
{
if (keyCode == Keycode.Back && webview.CanGoBack())
{
webview.GoBack();
return true;
}
return base.OnKeyDown(keyCode, e);
}
}
// download files from webview
public class JobWebChromeClient : WebChromeClient
{
JobActivity WebViewActivity;
public JobWebChromeClient(JobActivity activity)
{
WebViewActivity = activity;
}
public override bool OnShowFileChooser(WebView webView, IValueCallback filePathCallback, FileChooserParams fileChooserParams)
{
WebViewActivity.mUploadMessage = filePathCallback;
Intent i = new Intent(Intent.ActionGetContent);
i.AddCategory(Intent.CategoryOpenable);
i.SetType("*/*");
WebViewActivity.StartActivityForResult(Intent.CreateChooser(i, "File Chooser"), JobActivity.FILECHOOSER_RESULTCODE);
return true;
}
}
}
First of all, make sure your WebView has enabled javascript and the WebViewClient is set correctly.
WebView mWebview = FindViewById<WebView>(Resource.Id.webView1);
mWebview.Download += MWebview_Download;
var client = new WebViewClient();
mWebview.Settings.JavaScriptEnabled = true;
mWebview.SetWebViewClient(client);
mWebview.LoadUrl("your url");
Then, we shouldd achieve WebView.Download event(use DownloadManager to download the file)
private void MWebview_Download(object sender, DownloadEventArgs e)
{
var url = e.Url;
DownloadManager.Request request = new
DownloadManager.Request(Uri.Parse(url));
request.AllowScanningByMediaScanner();
request.SetNotificationVisibility(DownloadManager.Request.VisibilityVisibleNotifyCompleted); //Notify client once download is completed!
request.SetDestinationInExternalPublicDir(Environment.DirectoryDownloads, "CPPPrimer");
DownloadManager dm = (DownloadManager)GetSystemService("download");
dm.Enqueue(request);
Toast.MakeText(ApplicationContext, "Downloading File",ToastLength.Long//To notify the Client that the file is being downloaded
).Show();
}
I'm making an app in Xamarin android where user navigates. The app contains webview. When a user opens webview, url gets loaded and browsing can be done. When he ends the app and opens it again, URL is loaded again instead of viewing last visited URL.
I don't know what I'm doing wrong here.
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
webView = FindViewById<WebView>(Resource.Id.webView1);
webView.SetWebViewClient(new MyWebClient());
CookieManager.Instance.SetAcceptCookie(true);
webView.Settings.JavaScriptEnabled = true;
webView.Settings.SetAppCacheEnabled(true);
webView.LoadUrl(getUrl());
webView.SetPadding(0, 0, 0, 0);
webView.Settings.SetSupportZoom(true);
}
public void saveUrl(String url)
{
ISharedPreferences sp = GetSharedPreferences("SP_WEBVIEW_PREFS", FileCreationMode.Private);
ISharedPreferencesEditor editor = sp.Edit();
editor.PutString("SAVED_URL", url);
editor.Commit();
}
public String getUrl()
{
ISharedPreferences sp = GetSharedPreferences("SP_WEBVIEW_PREFS", FileCreationMode.Private);
//If you haven't saved the url before, the default value will be google's page
return sp.GetString("SAVED_URL", "http://google.com");
}
public void onPageFinished(WebView view, String url)
{
this.onPageFinished(view, url);
saveUrl(url);
}
}
internal class MyWebClient : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, string url)
{
view.LoadUrl(url);
return false;
}
}
You have placed onPageFinished method in an Activity. It should be overridden in MyWebClient class as below:
internal class MyWebClient : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, string url)
{
view.LoadUrl(url);
return false;
}
public override void OnPageFinished(WebView view, String url)
{
base.OnPageFinished(view, url);
//Save the url here.
//This method itself gives you the last url loaded as it's url Parameter.
ISharedPreferences sp = Application.Context.GetSharedPreferences("SP_WEBVIEW_PREFS", FileCreationMode.Private);
ISharedPreferencesEditor editor = sp.Edit();
editor.PutString("SAVED_URL", url);
editor.Commit().
}
}
This method will be automatically called when URL finished loading and then you will store your loaded URL in this method.
I am trying to write my own protocol handler for a JavaFX application that uses webview to access a single website. What I have done so far
My custom URLStreamHandlerFactory
public class MyURLStreamHandlerFactory implements URLStreamHandlerFactory {
public URLStreamHandler createURLStreamHandler(String protocol) {
System.out.println("Protocol: " + protocol);
if (protocol.equalsIgnoreCase("http") || protocol.equalsIgnoreCase("https")) {
return new MyURLStreamHandler();
} else {
return new URLStreamHandler() {
#Override
protected URLConnection openConnection(URL u) throws IOException {
return new URLConnection(u) {
#Override
public void connect() throws IOException {
}
};
}
};
}
}
}
My custom URLStreamHandler
public class MyURLStreamHandler extends java.net.URLStreamHandler{
protected HttpURLConnection openConnection(URL u){
MyURLConnection q = new MyURLConnection(u);
return q;
}
}
My custom HttpURLConnection
public class MyURLConnection extends HttpURLConnection {
static int defaultPort = 443;
InputStream in;
OutputStream out;
Socket s;
publicMyURLConnection(URL url) {
super(url);
try {
setRequestMethod("POST");
} catch (ProtocolException ex) {
ex.printStackTrace();
}
}
public void setRequestProperty(String name, String value){
super.setRequestProperty(name, value);
System.out.println("Namee: " + name);
System.out.println("Value: " + value);
}
public String getRequestProperty(String name){
System.out.println("GET REQUEST: ");
return super.getRequestProperty(name);
}
public OutputStream getOutputStream() throws IOException {
OutputStream os = super.getOutputStream();
System.out.println("Output: " + os);
return os;
}
public InputStream getInputStream() throws IOException {
InputStream is = super.getInputStream();
System.out.println("INout stream: " + is);
return is;
}
#Override
public void connect() throws IOException {
}
#Override
public void disconnect() {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public boolean usingProxy() {
throw new UnsupportedOperationException("Not supported yet.");
}
When I run the application I get the following error althouhg it seems to set some headers
Jul 08, 2013 11:09:04 AM com.sun.webpane.webkit.network.URLLoader doRun
WARNING: Unexpected error
java.net.UnknownServiceException: protocol doesn't support input
at java.net.URLConnection.getInputStream(URLConnection.java:839)
at qmed.QMedURLConnection.getInputStream(MyURLConnection.java:67)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468)
at com.sun.webpane.webkit.network.URLLoader.receiveResponse(URLLoader.java:383)
at com.sun.webpane.webkit.network.URLLoader.doRun(URLLoader.java:142)
at com.sun.webpane.webkit.network.URLLoader.access$000(URLLoader.java:44)
at com.sun.webpane.webkit.network.URLLoader$1.run(URLLoader.java:106)
at com.sun.webpane.webkit.network.URLLoader$1.run(URLLoader.java:103)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.webpane.webkit.network.URLLoader.run(URLLoader.java:103)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
All I want to do is get the response back for a given request and reads its binary data. I want the protocol to behave exactly the same way as the default one and only check the binary data of a given respone. What am I doing wrong?
The application is doing all shorts of URLConnections. Is it correct to use a HTTPURLConnection as my custom URLConnection class when the protocol is http or https and start a default URLStreamHandler when other protocols are used like I am doing in MyURLStreamHandlerFactory? Should I just extend the default URLConnection class in MYURLConnection to handle all protocols the same?
Any help would be much appreciated as this is a project threatening problem
Thank you
It might be that all you are missing is a setDoInput(true) or override getDoInput() and return true (that's what i did).
If that does not help check out my working solution:
MyURLStreamHandlerFactory:
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
public class MyURLStreamHandlerFactory implements URLStreamHandlerFactory
{
public URLStreamHandler createURLStreamHandler(String protocol)
{
if (protocol.equals("myapp"))
{
return new MyURLHandler();
}
return null;
}
}
Register Factory:
URL.setURLStreamHandlerFactory(new MyURLStreamHandlerFactory());
MyURLHandler :
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
public class MyURLHandler extends URLStreamHandler
{
#Override
protected URLConnection openConnection(URL url) throws IOException
{
return new MyURLConnection(url);
}
}
MyURLConnection:
import java.io.*;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
/**
* Register a protocol handler for URLs like this: <code>myapp:///pics/sland.gif</code><br>
*/
public class MyURLConnection extends URLConnection
{
private byte[] data;
#Override
public void connect() throws IOException
{
if (connected)
{
return;
}
loadImage();
connected = true;
}
public String getHeaderField(String name)
{
if ("Content-Type".equalsIgnoreCase(name))
{
return getContentType();
}
else if ("Content-Length".equalsIgnoreCase(name))
{
return "" + getContentLength();
}
return null;
}
public String getContentType()
{
String fileName = getURL().getFile();
String ext = fileName.substring(fileName.lastIndexOf('.'));
return "image/" + ext; // TODO: switch based on file-type
}
public int getContentLength()
{
return data.length;
}
public long getContentLengthLong()
{
return data.length;
}
public boolean getDoInput()
{
return true;
}
public InputStream getInputStream() throws IOException
{
connect();
return new ByteArrayInputStream(data);
}
private void loadImage() throws IOException
{
if (data != null)
{
return;
}
try
{
int timeout = this.getConnectTimeout();
long start = System.currentTimeMillis();
URL url = getURL();
String imgPath = url.toExternalForm();
imgPath = imgPath.startsWith("myapp://") ? imgPath.substring("myapp://".length()) : imgPath.substring("myapp:".length()); // attention: triple '/' is reduced to a single '/'
// this is my own asynchronous image implementation
// instead of this part (including the following loop) you could do your own (synchronous) loading logic
MyImage img = MyApp.getImage(imgPath);
do
{
if (img.isFailed())
{
throw new IOException("Could not load image: " + getURL());
}
else if (!img.hasData())
{
long now = System.currentTimeMillis();
if (now - start > timeout)
{
throw new SocketTimeoutException();
}
Thread.sleep(100);
}
} while (!img.hasData());
data = img.getData();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
public OutputStream getOutputStream() throws IOException
{
// this might be unnecessary - the whole method can probably be omitted for our purposes
return new ByteArrayOutputStream();
}
public java.security.Permission getPermission() throws IOException
{
return null; // we need no permissions to access this URL
}
}
Some parts of MyURLConnection might not be necessary for it to work, but like this it works for me.
Usage in JavaFX WebView:
<img src="myapp:///pics/image.png"/>
Note about permissions:
I used an applet with AllPermissions for my test with the above code.
In a Sandbox-Applet this won't work, as the setFactory permission is missing.
This is not directly related to the question asked, but might make the question itself obsolete.
With Java SE 6 Update 10 Java Applets support to access resources on any domain and port which is correctly set up with a crossdomain.xml.
With this the reason to register your own protocol might become obsolete, as you can access all resources that you need.
Another idea is: If you are trying to create a kind of network sniffer, why not directly use a network sniffer/analyzer program designed for such a task?
By activating Logging and Tracing in the Java Control-Panel your Java-Console will print all attempts and executed network calls including those from the WebView.
You can see all HTTP & HTTPS calls and their return-code + cookie data.
You might also see other protocol connections, but probably not any data sent over them.
This applies to Applets in a Browser.
If you need this in a different context maybe there is a way to activate the same options by passing command line parameters.
I am trying to download xml files from server when my application starts. So i want to show splash screen until am done with downloading and then show next screen. below is my code:
Here, i want to show My splash screen when getTopNotDoc() method is under execution. and after completion of that method show next screen.
//get _topics and notification document<br>
_getDoc = new ServerConnectivity(this);
public class ServerConnectivity {
private Document _questionDoc;
private Document _topics;
private Document _notifications;
public ServerConnectivity(ApplicationSession appSession){
//getTopNotDoc();
_this = this;
_appSession = appSession;
new Thread(new Runnable(){
public void run(){
getTopNotDoc();
}
}).start();
}
}
private void getTopNotDoc(){
InputStream inputStream = null ;
try{
// Build a document based on the XML file.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
inputStream = getClass().getResourceAsStream("topics.xml");
_topics = builder.parse( inputStream );
inputStream = getClass().getResourceAsStream("notification.xml");
_notifications = builder.parse( inputStream );
if(_topics == null || _notifications == null){
Dialog.alert("Unable to connect to internet");
}
}
catch ( Exception e ){
System.out.println( e.toString() );
}
finally{
if(inputStream != null){
try {
inputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
Usually when I do this, I create a loading screen, then I just extend the Thread class.
So I would create a loading screen like this:
public class LoadingScreen extends MainScreen {
public LoadingScreen() {
super();
this.setTitle("loading...");
// add a spinning animated gif or whatever here
final Screen me = this;
new Thread(new Runnable(){
public void run(){
// do something that takes a long time
try { Thread.sleep(1000);} catch (Exception e) {}
}
}){
public void run() {
super.run();
synchronized (UiApplication.getEventLock()) {
UiApplication.getUiApplication().popScreen(me);
}
}
}.start();
}
}
Then I push this screen, it will perform the long task, and then pop itself when its done.
(you may or may not want to disable the back button and menus on this screen)
I made the Runnable as an anonymous inner class just to compact the code, but you probably have this code already in a class somewhere else, so you would pass it in instead.
To add some flexibility and keep your classes loosely coupled together, you could make some modifications to your ServerConnectivity class so your calls could go something like the following:
// push your splash screen on to the stack
//
final SplashScreen splashScreen = new SplashScreen();
UiApplication.getUiApplication().pushScreen(splashScreen);
_getDoc = new ServerConnectivity(this, new ServerConnectivityListener() {
public void onCompleted(ServerConnectivity sender) {
// display next screen
//
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
splashScreen.close();
UiApplication.getUiApplication().pushScreen(new NextScreen());
}
});
}
public void onError(ServerConnectivity sender) {
splashScreen.close();
// display error message, retry, etc...
}
});
For this to work, you need an interface with the following definition:
public interface ServerConnectivityListener {
void onCompleted(ServerConnectivity sender);
void onError(ServerConnectivity sender);
}
So, your ServerConnectivity class maintains a reference to some object that implements the interface called ServerConnectivityListener This allows you to maintain loose coupling between the subject class and any observers that need to listen for events.
Within ServerConnectivity, you would make calls to the listener's methods something like this:
// begin excerpt from above...
//
if(_topics == null || _notifications == null) {
_listener.onError(this);
} else {
_listener.onCompleted(this);
}
catch ( Exception e ){
System.out.println( e.toString() );
_listener.onError(this);
//
// end excerpt from above...
Here is code for splash screen in java........after and call that view.........
http://www.randelshofer.ch/oop/javasplash/javasplash.html
import java.awt.*;
import java.awt.event.*;
public class SplashTest extends Frame implements ActionListener {
static void renderSplashFrame(Graphics2D g, int frame) {
final String[] comps = {"foo", "bar", "baz"};
g.setComposite(AlphaComposite.Clear);
g.fillRect(130,250,280,40);
g.setPaintMode();
g.setColor(Color.BLACK);
g.drawString("Loading "+comps[(frame/5)%3]+"...", 130, 260);
g.fillRect(130,270,(frame*10)%280,20);
}
public SplashTest() {
super("SplashScreen demo");
setSize(500, 300);
setLayout(new BorderLayout());
Menu m1 = new Menu("File");
MenuItem mi1 = new MenuItem("Exit");
m1.add(mi1);
mi1.addActionListener(this);
MenuBar mb = new MenuBar();
setMenuBar(mb);
mb.add(m1);
final SplashScreen splash = SplashScreen.getSplashScreen();
if (splash == null) {
System.out.println("SplashScreen.getSplashScreen() returned null");
return;
}
Graphics2D g = (Graphics2D)splash.createGraphics();
if (g == null) {
System.out.println("g is null");
return;
}
for(int i=0; i<100; i++) {
renderSplashFrame(g, i);
splash.update();
try {
Thread.sleep(200);
}
catch(InterruptedException e) {
}
}
splash.close();
setVisible(true);
toFront();
}
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
public static void main (String args[]) {
SplashTest test = new SplashTest();
}
}
Since,it is a thread based one,We cannot do it the normal way.So Check the following link
http://supportforums.blackberry.com/t5/Java-Development/What-is-the-Event-Thread/ta-p/446865
and Check whether parsing is done,Until that have the same screen,Check the condition of whehter it is downloaded or not ,and then push the screen
I have to send the audio data in byte array obtain by recording from java applet at the client side to rails server at the controller in order to save.
So, what encoding parameters at the applet side be used and in what form the audio data be converted like String or byte array so that rails correctly recieve data and then I can save that data at the rails in the file. As currently the audio file made by rails controller is not playing. It is the following ERROR :
LAVF_header: av_open_input_stream() failed
while playing with the mplayer.
Here is the sample Java Code i m using in which i m reading audio data from the audio file:
package networksocket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JApplet;
import java.net.*;
import java.io.*;
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.util.Properties;
import javax.swing.plaf.basic.BasicSplitPaneUI.BasicHorizontalLayoutManager;
import sun.awt.HorizBagLayout;
import sun.awt.VerticalBagLayout;
import sun.misc.BASE64Encoder;
/**
*
* #author mukand
*/
public class Urlconnection extends JApplet implements ActionListener
{
/**
* Initialization method that will be called after the applet is loaded
* into the browser.
*/
public BufferedInputStream in;
public BufferedOutputStream out;
public String line;
public FileOutputStream file;
public int bytesread;
public int toread=1024;
byte b[]= new byte[toread];
public String f="FINISH";
public String match;
public File fileopen;
public JTextArea jTextArea;
public Button refreshButton;
public HttpURLConnection urlConn;
public URL url;
OutputStreamWriter wr;
BufferedReader rd;
#Override
public void init() {
// TODO start asynchronous download of heavy resources
//textField= new TextField("START");
//getContentPane().add(textField);
JPanel p = new JPanel();
jTextArea= new JTextArea(1500,1500);
p.setLayout(new GridLayout(1,1, 1,1));
p.add(new JLabel("Server Details"));
p.add(jTextArea);
Container content = getContentPane();
content.setLayout(new GridBagLayout()); // Used to center the panel
content.add(p);
jTextArea.setLineWrap(true);
refreshButton = new java.awt.Button("Refresh");
refreshButton.reshape(287,49,71,23);
refreshButton.setFont(new Font("Dialog", Font.PLAIN, 12));
refreshButton.addActionListener(this);
add(refreshButton);
Properties properties = System.getProperties();
properties.put("http.proxyHost", "netmon.iitb.ac.in");
properties.put("http.proxyPort", "80");
}
#Override
public void actionPerformed(ActionEvent e)
{
try
{
url = new URL("http://localhost:3000/audio/audiorecieve");
urlConn = (HttpURLConnection)url.openConnection();
//String login = "mukandagarwal:rammstein$";
//String encodedLogin = new BASE64Encoder().encodeBuffer(login.getBytes());
//urlConn.setRequestProperty("Proxy-Authorization",login);
urlConn.setRequestMethod("POST");
// urlConn.setRequestProperty("Content-Type",
//"application/octet-stream");
//urlConn.setRequestProperty("Content-Type","audio/mpeg");//"application/x-www- form-urlencoded");
//urlConn.setRequestProperty("Content-Type","application/x-www- form-urlencoded");
//urlConn.setRequestProperty("Content-Length", "" +
// Integer.toString(urlParameters.getBytes().length));
urlConn.setRequestProperty("Content-Language", "UTF-8");
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
byte bread[]=new byte[2048];
int iread;
char c;
String data=URLEncoder.encode("key1", "UTF-8")+ "=";
//String data="key1=";
FileInputStream fileread= new FileInputStream("//home//mukand//Hellion.ogg");//Dogs.mp3");//Desktop//mausam1.mp3");
while((iread=fileread.read(bread))!=-1)
{
//data+=(new String());
/*for(int i=0;i<iread;i++)
{
//c=(char)bread[i];
System.out.println(bread[i]);
}*/
data+= URLEncoder.encode(new String(bread,iread), "UTF-8");//new String(new String(bread));//
// data+=new String(bread,iread);
}
//urlConn.setRequestProperty("Content-Length",Integer.toString(data.getBytes().length));
System.out.println(data);
//data+=URLEncoder.encode("mukand", "UTF-8");
//data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
//data="key1=";
wr = new OutputStreamWriter(urlConn.getOutputStream());//urlConn.getOutputStream();
//if((iread=fileread.read(bread))!=-1)
// wr.write(bread,0,iread);
wr.write(data);
wr.flush();
fileread.close();
jTextArea.append("Send");
// Get the response
rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
while ((line = rd.readLine()) != null) {
jTextArea.append(line);
}
wr.close();
rd.close();
//jTextArea.append("click");
}
catch (MalformedURLException ex) {
Logger.getLogger(Urlconnection.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(Urlconnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void start()
{
}
#Override
public void stop()
{
}
#Override
public void destroy()
{
}
// TODO overwrite start(), stop() and destroy() methods
}
Here is the Rails controller function for recieving:
def audiorecieve
puts "///////////////////////////////////////******RECIEVED*******////"
puts params[:key1]#+" "+params[:key2]
data=params[:key1]
#request.env('RAW_POST_DATA')
file=File.new("audiodata.ogg", 'w')
file.write(data)
file.flush
file.close
puts "////**************DONE***********//////////////////////"
end
Please reply quickly
Base64 encode the data. Send it as a string, receive it on the Rails side and decode it back to the original format.