Websocket not working on my Android app (with Phonegap Build) - android

I tried to develop a simple mobile application that connect to a websocket server. I used Phonegap Build to make my Android .apk, here's the html code :
<html>
<head>
<title>Testing websockets</title>
</head>
<body>
<div id="messages"></div>
<script type="text/javascript">
var webSocket =
new WebSocket('ws://192.168.82.1:8080/WebSocket/websocket');
webSocket.onerror = function(event) {
onError(event)
};
webSocket.onopen = function(event) {
onOpen(event)
};
webSocket.onmessage = function(event) {
onMessage(event)
};
function onMessage(event) {
document.getElementById('messages').innerHTML
+= '<h1 align="center"/>' +" "+ event.data;
}
function onOpen(event) {
document.getElementById('messages').innerHTML
+= '<h1 align="center"/>connection established';
}
function onError(event) {
alert(event.data);
}
</script>
</body>
</html>
The code is working fine on my navigator but the message "connection established" doesn't even appear when I use the Android app.
Is there something wrong with this code or does my app need some library ?
PS : I have another code with a button sending a message to the server and receiving a text from it, and of course it's the same problem !

WebSockets are only supported in WebView after Android 4.4. So if you want to use it in older android versions ,you have some choices:
Use a Cordova plugin that provides that functionality. For example, https://github.com/knowledgecode/WebSocket-for-Android (this is just an example, I have never worked with that plugin)
Use something like SockJS or socket.io to provide webSockets when supported and fallback to other technologies when not. Please note that using those technologies requires you to use them also in the server

Related

Is it possible to run a node js socket.io Server on Android?

Currently I develop a little multiplayer Browsergame with NodeJs and looking for possibilities to run the Server on Android. This would be nice to make Lan-Parties possible.
Due to my lack of Java experiences a solution for Phonegap or any likely ready to go tools would be nice but is no must.
For android you have to edit cordova.xml and add access to the socketio host:
<access origin="HOST*"/>
index.html (with socketio example):
<script src="HOST/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('HOST');
socket.on('news', function (data) {
socket.emit('my other event', { my: 'data' });
});
</script>
app.js (server side javascript / basic socketio example):
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
The HOST you have to replace with hostname of your socket.io server!

Android doesn't load my webView

I want to load my webView which url is http://pickalize.info:4000 and using a lot of javascript.
So I write code like this.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
WebView webView = (WebView)findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.loadUrl("http://pickalize.info:4000/");
}
I tried change url to http://www.google.co.jp then it show the page correctly.
But my site doesn't show up.
Why it doesn't show my site?
Do you have any idea? Thanks in advance.
Can you double-check in the web browser on your Android device that your web site is listening on port 4000 - it seems to be listening on port 80 (the default port for HTTP).
When I visit your web site on the default port e.g. http://pickalize.info/ then I get a web page that includes a list of URLs. Note: http://pickalize.info:80/ is equivalent to above and loads the same web page I see without the port number in the URL.
The page has the following text:
Pickalize
Iphone Apps
Profile
Others
RSS
no valid 'aps-environment' error 2013-03-02
ノートを買った 2013-03-02
JavaでJSON 2013-03-01
もしかして 2013-03-01
半日で作ったしょぼいアプリがリリースされた 2013-02-27
WordBench香川に行ってきた 2013-02-25
Apple's game center problem. 2013-02-24
observer 2013-02-21
ナビゲーションバーを作ってみた。 2013-02-21
My App has rejected. 2013-02-20
プログラミングを始めて20ヶ月経って(経過) 2013-02-18
Python のスクリプトをどこでも実行する 2013-02-17
やっと... AppStoreに提出できた 2013-02-17
iOS開発のために画像を編集するやつ作った. 2013-02-17
Admobを埋め込む注意点 2013-02-16
Flaskで自分だけのブログを作った。 2013-02-15
I get similar content in a mini Android app I just created that uses your sample code. To make sure it copes with port numbers in the URL I made the following minor change:
webView.loadUrl("http://pickalize.info:80/");
However when I try to visit your web site using port 4000 I get a message telling me the web site is not available. I have tried from my Android device and my laptop. There doesn't appear to be a site listening / hosted on port 4000; there does seem to be a site on port 80.
Please double-check your site is being hosted on port 4000 and that you can reach it from a computer that's using the internet to connect to the site (in case there are router or firewall restrictions that block traffic to port 4000).
PS: The web page on port 80 has minimal javascript, from view source in my laptop web browser, this is what I can see
<script src="/static/js/rainbow.js"></script>
<script src="/static/js/languages/javascript.js"></script>
<script src="/static/js/languages/generic.js"></script>
<script src="/static/js/languages/python.js"></script>
<!--google analytics-->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-15508754-4']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
// google feed
google.load("feeds","1");
var init = function(){
};
google.setOnLoadCallback(init);
</script>

Android barcode scanner integration with web page

I have been researching all morning about integrating an android barcode scanner app into a web page, but haven't found exactly what I need to know. I want to have a web page that the user can fill in text fields by using an android barcode scanner. So the user would be on a web page and would either click inside the text field or click a button next to the text field that would start the android barcode scanner. They would then scan the barcode and the text field would be filled in.
I have found solutions on how to do this and then go to a different page, but it is important that the user stays on the same page. I have seen the zxing project and thought that might be able to be used, but I'm not sure if it allows for the page to stay the same.
I'm pretty sure this is possible and is wondering if any one could give me a high level overview on how they would do it. I was thinking it might be able to be done with an ajax request that gets submitted on a button click. The ajax request would get sent to my server, the server would send something to the android device that would start the scanner and return the data which in turn gets sent back in the ajax response. Is there any way to cut out the server though and just have the android browser starting the barcode scanner? Thank you for your time and I appreciate any discussion on it.
ZXing (zebra crossing) provides the capability to initiate the bar code scanner via a webpage through a button click event, anchor tag, or other action that could call a URL on a mobile device.
When the barcode scanner application is installed on an android device, a URL call to:
zxing://scan/?ret=http://foo.com/products/{CODE}/description&SCAN_FORMATS=UPC_A,EAN_13
Will bring up the device bar code reader, the user scans the code, and the code is returned via the callback URL parameter supplied in the zxing URL.
You can view an example (works on android) here: http://zxing.appspot.com/scan
You can try this for Android:
You can use Zxing library for barcode scan for webpages
<!DOCTYPE html>
<script type="text/javascript">
//This entire block of script should be in a separate file, and included in each doc in which you want scanner capabilities
function zxinglistener(e){
localStorage["zxingbarcode"] = "";
if(e.url.split("\#")[0] == window.location.href){
window.focus();
processBarcode(decodeURIComponent(e.newValue));
}
window.removeEventListener("storage", zxinglistener, false);
}
if(window.location.hash != ""){
localStorage["zxingbarcode"] = window.location.hash.substr(1);
self.close();
window.location.href="about:blank";//In case self.close is disabled
}else{
window.addEventListener("hashchange", function(e){
window.removeEventListener("storage", zxinglistener, false);
var hash = window.location.hash.substr(1);
if (hash != "") {
window.location.hash = "";
processBarcode(decodeURIComponent(hash));
}
}, false);
}
function getScan(){
var href = window.location.href.split("\#")[0];
window.addEventListener("storage", zxinglistener, false);
zxingWindow = window.open("zxing://scan/?ret=" + encodeURIComponent(href + "#{CODE}"),'_self');
}
</script>
<html>
<head>
<script type="text/javascript">
function processBarcode(b){
var d = document.createElement("div");
d.innerHTML = b;
document.body.appendChild(d);
}
</script>
</head>
<body>
<button onclick="getScan()">get Scan</button>
</body>
</html>
For reference: Read link
Using a javascript interface and loadurl(javascript...) you can communicate with your webpage from Android
public void loadScript(String script){
webview.loadUrl("javascript:(function() { " + script + "})()");
}
private class JavaScriptInterface {
public void startQRScan() {
...
}
}
There are plenty of examples on google.

send events from python to javascript using sl4a

I wanted to know the answer to a simple question but i have'nt found a good one
(i've google it for hours :) )
I'm playing with the sl4a with python and i can send events from js to the python script, but the js is not catching the eventPost i put in the code below from python to js.
Anyone knows how is this been done or if there is another way without the registerCallback?
HTML CODE :
<html>
<head>
<script>
var droid = new Android();
function doit(){
droid.makeToast("Text send :=>"+document.getElementById("msg").value);
droid.eventPost("doit",document.getElementById("msg").value);
}
function alert_me(data){
droid.makeToast("All done!");
document.getElementById("msg").value = '';
}
droid.registerCallback("done",alert_me);
</script>
</head>
<body>
<input type="text" name="boton" id="msg" value="" />
<input type="button" name="boton" value="Go!" onclick="javascript:doit()" />
</body>
</html>
PYTHON CODE:
import android,time
if __name__ == '__main__' :
droid = android.Android()
droid.webViewShow("file:///sdcard/sl4a/scripts/sample.html")
while True:
event = droid.eventWait().result
if event["name"] == 'doit':
droid.makeToast("Event catched! %s" % event['data'])
droid.eventPost("done","Done message")
time.sleep(2)
droid.exit()
This is simple to get working, but isn't obvious or well documented.
First you want to get a hook to the Android object inside the webview. Then you can use it to register one or more callbacks. For a simple example, we'll just do one that pops an alert with a message from Python.
var droid = new Android();
droid.registerCallback("echo", function(msg) {
alert(msg.data)
});
In this case, echo is the name of the event type you want this callback to handle. So this will handle 'echo events'. The event names are arbitrary strings, just call them whatever makes sense.
In the Python script that launched the webview, you can now post events to the registered handler whenever you like.
droid.eventPost("echo", "hello world")
The second argument here is the message you want to pass to the JavaScript callback.
Note that although you pass the message back as a string, it arrives in the JavaScript function as an object. That object, we're calling it msg above, has an attribute called data which contains the string you passed from the Python side.
Unfortunately I have never personally been able to get this working, using both registerCallback() and eventWaitFor(). However, if you are still keen on getting this working, I strongly recommend you head on over and download sl4a_r5x – an unofficial but newer and updated release of SL4A. In it is support for using FullScreenUi's based off the same xml code that native Android apps use. With this you can do what you're after and examples can be found on the page.Hopefully this has been helpful and you're still interested in SL4A!

ChildBrowser Plugin of PhoneGap displaying an error

Recently i built an android app in PhoneGap , and now i want a twitter sharing feature so i am planning to add a childbrowser where i will give the url of twitter sharing. Now i have done all the steps given in ChildBrowser Github and also i have used ondevice ready function, but my code is displaying an error in the emulator as soon as i hit the tweet button ie. " TypeError: window.plugins.childBrowser is undefined " . Now um almost trying on this code for more than 7 hours and unable to solve it . can anyone tell where i am wrong ?
i am pasting the code below
<title> Javascript Code</title>
var childBrowser;
function onBodyLoad()
{
document.addEventListener("deviceready",onDeviceReady,false);
}
function onDeviceReady()
{
phoneGapReady.innerHTML = "PhoneGap is Ready";
childBrowser = ChildBrowser.install();
}
function openChildBrowser(url)
{
try
{
//alert("check");
//both of these should work...
window.plugins.childBrowser.showWebPage(url);
childBrowser.showWebPage(url);
}
catch (err)
{
alert(err);
}
} !-- end of Javascript function <body onload="onBodyLoad()"> <a onclick="openChildBrowser('http://www.google.com')"> <img style="float:left" src="tweet.jpg" style="margin-left:10px" width="100" height="40"> </a>
Its possibly a scope issue....
http://www.mredkj.com/tutorials/reference_js_intro_ex.html
also try
var childBrowser = '';
or
var childBrowser = null;
Have you included childbrowser.java childbrowser.js and phonegap.js files?

Categories

Resources