Open files with libGdx (android)? - javascript

Can I open files (.apk) with libGdx?
I download an apk from the internet and then I want to open it.
MyCode:
public void download(){
final Net.HttpRequest httpRequest = new Net.HttpRequest(Net.HttpMethods.GET);
httpRequest.setUrl("http://singlepong.square7.ch/BirdColor.apk");
httpRequest.setContent(null);
Gdx.net.sendHttpRequest(httpRequest, new Net.HttpResponseListener() {
#Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
// Determine how much we have to download
long length = Long.parseLong(httpResponse.getHeader("Content-Length"));
// We're going to download the file to external storage, create the streams
InputStream is = httpResponse.getResultAsStream();
OutputStream os = Gdx.files.external("BirdColor.apk").write(false);
byte[] bytes = new byte[1024];
int count = -1;
long read = 0;
try {
// Keep reading bytes and storing them until there are no more.
while ((count = is.read(bytes, 0, bytes.length)) != -1) {
os.write(bytes, 0, count);
read += count;
// Update the UI with the download progress
final int progress = ((int) (((double) read / (double) length) * 100));
final String progressString = progress == 100 ? "Click to download" : progress + "%";
// Since we are downloading on a background thread, post a runnable to touch ui
Gdx.app.postRunnable(new Runnable() {
#Override
public void run () {
if (progress == 100) {
button.setDisabled(false);
}
button.setText(progressString);
}
});
}
} catch (IOException e) {
}
}
#Override
public void failed(Throwable t) {
button.setText("Download failed");
}
#Override
public void cancelled() {
}
});
}
How can I then open the downloaded apk?
Sorry my English is not very good but I lern it only since one year.
I'm happy about helpful answers. (:

Related

How to Send/Receive data via bluetooth android api

I have a project in NativeScript and i'm accessing the bluetooth android api via JavaScript as in this example:
android.bluetooth.BluetoothAdapter.getDefaultAdapter();
I am able to find the paired devices and connect to them. I wanted some example of how to forward data to the device and have a return of this device.
I've seen something in the android documents about:
getOutputStream()
and
getInputStream()
but I do not know how to use this via JavaScript.
I want is to send an command to an Elm327 OBD2 device and receive the data from this device.
Sample native code:
private OutputStream outputStream;
private InputStream inStream;
private void init() throws IOException {
BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
if(bondedDevices.size() > 0) {
Object[] devices = (Object []) bondedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) devices[position];
ParcelUuid[] uuids = device.getUuids();
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
socket.connect();
outputStream = socket.getOutputStream();
inStream = socket.getInputStream();
}
Log.e("error", "No appropriate paired devices.");
} else {
Log.e("error", "Bluetooth is disabled.");
}
}
}
public void write(String s) throws IOException {
outputStream.write(s.getBytes());
}
public void run() {
final int BUFFER_SIZE = 1024;
byte[] buffer = new byte[BUFFER_SIZE];
int bytes = 0;
int b = BUFFER_SIZE;
while (true) {
try {
bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Using javascript fetch with web service not working

So I'm trying to make a webservice that allows someone to obtain data from a server. Right now, the server I'm using is written using java's HttpServer class. I plan to make the server accessible using fetch() in javascript, but it's not working.
When I was first testing out my server, I used Apache's HttpComponents library, and that client(written in java). was able to receive the test json that came from my server. However, when I used fetch() on my javascript client, nothing is received when I console.log everything. It doesn't make sense to me why it would work in Java, but not javascript. Does anyone know why this is not working? Am I just doing the javascript part wrong, and it does actually work? Thanks!
Code snippets for reference:
java server:
public class Main {
private static final int PORT = 1337;
private static final int BACKLOG = 1;
public static void main(String[] args) {
try {
HttpServer server = HttpServer.create(new InetSocketAddress(PORT), BACKLOG);
System.out.print("started on" + PORT);
HttpContext context = server.createContext("/ex", new Handler());
server.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Handler implements HttpHandler {
#Override
public void handle(HttpExchange he) throws IOException {
System.out.println("handled");
JSONObject obj = new JSONObject();
obj.put("name", "value");
obj.put("num", new Integer(100));
obj.put("balance", new Double(1000.21));
obj.put("is_vip", new Boolean(true));
obj.put("array", new int[]{1, 2, 3});
String response = obj.toJSONString();
he.sendResponseHeaders(200, response.length());
he.getResponseBody().write(response.getBytes());
}
}
java client:
public class PostTest {
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://localhost:1337/ex");
CloseableHttpResponse response = httpClient.execute(httppost);
System.out.println("STATUS LINE");
System.out.println(response.getStatusLine().toString());
System.out.println("HEADER");
Header[] h = response.getAllHeaders();
for(int i = 0; i < h.length; i++) {
System.out.println(h[i]);
}
System.out.println("ENTITY.CONTENT");
try(BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"))) {
String s;
while((s = br.readLine()) != null) {
System.out.println(s);
}
}
}
}
Javascript:
var init = {mode: "no-cors"};
async function f() {
return fetch("http://localhost:1337/ex", init).then(res => res.text()).then(posts => console.log(posts));
}
f();

No respond from WebSocket after request connection from browser to C# program

I'm learning how to get my C# program communicate with browser.
I'm using TCP in C# and WebSocket in my HTML5 browser.
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace ShouldWork
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TCPServer server = new TCPServer();
System.Threading.Thread obj_thread = new System.Threading.Thread(server.startServer);
obj_thread.Start();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
TcpClient client = new TcpClient("127.0.0.1", 7000);
NetworkStream ns = client.GetStream();
byte[] data_tosend = createDataPacket(Encoding.UTF8.GetBytes(tx_data_send.Text));
ns.Write(data_tosend, 0, data_tosend.Length);
}
private byte[] createDataPacket(byte[] data)
{
byte[] initialize = new byte[1];
initialize[0] = 2;
byte[] separator = new byte[1];
separator[0] = 4;
byte[] datalength = Encoding.UTF8.GetBytes(Convert.ToString(data.Length));
MemoryStream ms = new MemoryStream();
ms.Write(initialize, 0, initialize.Length);
ms.Write(datalength, 0, datalength.Length);
ms.Write(separator, 0, separator.Length);
ms.Write(data, 0, data.Length);
return ms.ToArray();
}
}
class TCPServer
{
TcpListener listener;
public TCPServer()
{
listener = new TcpListener(IPAddress.Any, 7000);
}
public void startServer()
{
listener.Start();
while (true)
{
TcpClient client = listener.AcceptTcpClient();
NetworkStream ns = client.GetStream();
if(ns.ReadByte() == 2)
{
byte[] recv_data = readStream(ns);
Form1.ActiveForm.Invoke(new MethodInvoker(delegate
{
((TextBox)Form1.ActiveForm.Controls.Find("tx_recv_data", true)[0]).Text = Encoding.UTF8.GetString(recv_data);
}));
}
}
}
public byte[] readStream(NetworkStream ns)
{
byte[] data_buff = null;
int b = 0;
String buff_length = "";
while ((b = ns.ReadByte()) != 4)
{
buff_length += (char)b;
}
int data_length = Convert.ToInt32(buff_length);
data_buff = new byte[data_length];
int byte_read = 0;
int byte_offset = 0;
while (byte_offset < data_length)
{
byte_read = ns.Read(data_buff, byte_offset, data_length - byte_offset);
byte_offset += byte_read;
}
return data_buff;
}
}
}
UI
When user clicks Start Server button, the program would then start the TCPServer. Then we can enter some text in the second textbox and my code will then process it and display the message on the first textbox.
Now I'd like to move the client part to the browser, so I created a simple web app and test out connection.
Code snippet
<!DOCTYPE html>
<html>
<head>
<title>Socket demo</title>
</head>
<body>
<button type="button" onclick="testWebSocket()">Connect to C# server</button><br><br>
<script language="javascript" type="text/javascript">
function testWebSocket(){
var socket = new WebSocket('ws://127.0.0.1:7000');
console.log("ssss");
socket.onopen = function(){
console.log("on open");
socket.send("Hello");
}
socket.onclose = function(evt){
console.log("on close");
}
socket.onerror = function(evt){
console.log("on error");
console.log(evt.data);
}
}
</script>
</body>
</html>
Here is what's wrong..... the onopen function doesn't seems to work at all, chrome console does display "sss" and that's it....
Is there something wrong with the approach I'm using?
As indicated in the comments, WebSocket uses its own framing schema.
Take a look to this link: https://hpbn.co/websocket/, specially the part where the framing is explained: https://hpbn.co/websocket/#binary-framing-layer
The reason why the connection never gets open, is because it is unable of completing the handshake : https://hpbn.co/websocket/#http-upgrade-negotiation

Can I use JS in silverlight app?

I have Silverlight app. For example I want add some JS script which can interact with SL app. For example I want add google map use JS api. Can I do this, But I must send some data from SL to JS to add pins on map, draw figures on map ect.
If you are using Windows Phone and you dont mind that part of the xaml to be a webview yo can.
First add a webview to the xaml
<phone:WebBrowser Name="webView" BorderThickness="0" BorderBrush="Transparent" IsScriptEnabled="True"
ScriptNotify="WebBrowser_ScriptNotify" />
Then you have to bind the webview with the load event and then saveg files to storage and load your html and js files
webView.Loaded += WebBrowser_OnLoaded;
private void WebBrowser_OnLoaded(object sender, RoutedEventArgs e)
{
SaveFilesToIsoStore();
chatView.Navigate(new Uri("Assets/HtmlContent/index.html", UriKind.Relative));
}
private void SaveFilesToIsoStore()
{
//These files must match what is included in the application package,
//or BinaryStream.Dispose below will throw an exception.
string[] files = {
"Assets/HtmlContent/index.html",
"Assets/HtmlContent/js/libs/jquery-1.11.0.min.js", "Assets/HtmlContent/js/pagejs.js", "Assets/HtmlContent/css/style.css"
};
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
if (false == isoStore.FileExists(files[0]))
{
foreach (string f in files)
{
StreamResourceInfo sr = Application.GetResourceStream(new Uri(f, UriKind.Relative));
using (BinaryReader br = new BinaryReader(sr.Stream))
{
byte[] data = br.ReadBytes((int)sr.Stream.Length);
SaveToIsoStore(f, data);
}
}
}
}
private void SaveToIsoStore(string fileName, byte[] data)
{
string strBaseDir = string.Empty;
string delimStr = "/";
char[] delimiter = delimStr.ToCharArray();
string[] dirsPath = fileName.Split(delimiter);
//Get the IsoStore.
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
//Re-create the directory structure.
for (int i = 0; i < dirsPath.Length - 1; i++)
{
strBaseDir = System.IO.Path.Combine(strBaseDir, dirsPath[i]);
isoStore.CreateDirectory(strBaseDir);
}
//Remove the existing file.
if (isoStore.FileExists(fileName))
{
isoStore.DeleteFile(fileName);
}
//Write the file.
using (BinaryWriter bw = new BinaryWriter(isoStore.CreateFile(fileName)))
{
bw.Write(data);
bw.Close();
So on the js you have to talk to the c# like this
function sendMessageToCodeBehind(someData) {
window.external.notify(JSON.stringify({ method: 'AddMessage', data: someData }));
}
On the code behind you would recibe the messages from the webview like this:
private void WebBrowser_ScriptNotify(object sender, NotifyEventArgs e)
{
var example = new { method = string.Empty, data = new object() };
var obj = JsonConvert.DeserializeAnonymousType(e.Value, example);
switch (obj.method) {
case "methodName":
}
}
And you would send back messages to the js like this
webView.InvokeScript("jsMethodName", JsonConvert.SerializeObject(new { Message = "some json message" }));

for file picker openFileChooser() method not calling WebChromeClient of Kitkat 4.4

I have one hi-bride application in which one html page has file picker and i want to load that page in Android webview.
This pickers works well in Device browser but not in webview.
For to support this i am using one hidden method of WebChromeClient which is as below
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType){
/**updated, out of the IF **/
mUploadMessage = uploadMsg;
/**updated, out of the IF **/
if(boolFileChooser){ //Take picture from filechooser
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult( Intent.createChooser( i, "Pick File.." ), FILECHOOSER_RESULTCODE );
} else { //Take photo and upload picture
Intent cameraIntent = new Intent("android.media.action.IMAGE_CAPTURE");
photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
if(photo.exists())
photo.delete();
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
mCapturedImageURI = Uri.fromFile(photo);
startActivityForResult(cameraIntent, CAMERAREQUEST_RESULTCODE);
}
}
// Per Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg){
openFileChooser(uploadMsg, "");
}
//Aftre
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg, "");
}
It was working fine till 4.3 but from 4.4 this method is not getting called.
And they said https://code.google.com/p/android/issues/detail?id=62220 this has been removed.
Do anyone knows any alternate way. Please let me know your help will greatly appreciated
There are no ways to openFileChooser method after 4.3 as google has removed that and they will come up with other way to handle this file chooser stuff in next version (Confirmed by Google engineer).
I moved to hybrid architecture to and write native function for file picker.
In Android 5.0, they introduced onShowFileChooser(), with which you can use an input form field in the webview and launch a file chooser to select images and files from the device.
Bitmap bitmap;
private static final int READ_REQUEST_CODE = 42;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
// Filter to only show results that can be "opened", such as a
// file (as opposed to a list of contacts or timezones)
intent.addCategory(Intent.CATEGORY_OPENABLE);
// Filter to show only images, using the image MIME data type.
// If one wanted to search for ogg vorbis files, the type would be "audio/ogg".
// To search for all documents available via installed storage providers,
// it would be "*/*".
intent.setType("image/*");
startActivityForResult(intent, READ_REQUEST_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
// The ACTION_OPEN_DOCUMENT intent was sent with the request code
// READ_REQUEST_CODE. If the request code seen here doesn't match, it's the
// response to some other intent, and the code below shouldn't run at all.
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
// The document selected by the user won't be returned in the intent.
// Instead, a URI to that document will be contained in the return intent
// provided to this method as a parameter.
// Pull that URI using resultData.getData().
Uri uri = null;
if (resultData != null) {
uri = resultData.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ImageView my_img_view = (ImageView ) findViewById (R.id.uploadlayout2);
my_img_view.setImageBitmap(bitmap);
}
}
}

Categories