Quantcast
Channel: Android Mode - Processing 2.x and 3.x Forum
Viewing all 941 articles
Browse latest View live

Webview for android in processing 3.x

$
0
0

Hi, Pls can any one throw some light on using the webview for android in processing 3.x.

Basically, I want to load a webpage inside my p3 sketch. Pls help.

Thanks in advance.


simplest-play-soundfiles-in-android-with-processin

Android WIFI TCP Communication - can not communication

$
0
0

Hi, nice to meet you. Please help me.

#1. Hardware 1) Smartphone 2) ESP8266-01 & Arduino

#2. Software Processing 1) TCP Communication Code

---------------------------------------------------

` import oscP5.*; import netP5.*;

OscP5 oscP5tcpServer;

OscP5 oscP5tcpClient;

NetAddress myServerAddress;

void setup() {
  /* create  an oscP5 instance using TCP listening @ port 11000 */
  oscP5tcpServer = new OscP5(this, 22000, OscP5.TCP);

  /* create an oscP5 instance using TCP.
   * the remote address is 127.0.0.1 @ port 11000 = the server from above
   */
  oscP5tcpClient = new OscP5(this, "192.168.4.1", 22001, OscP5.TCP);
}


void draw() {
  background(0);
}


void mousePressed() {
  /* the tcp client sends a message to the server it is connected to.*/
  oscP5tcpClient.send("/test", new Object[] {new Integer(1)});
}


void keyPressed() {
  /* check how many clients are connected to the server. */
  println(oscP5tcpServer.tcpServer().getClients().length);
}

void oscEvent(OscMessage theMessage) {
  /* in this example, both the server and the client share this oscEvent method */
  System.out.println("### got a message " + theMessage);
  if(theMessage.checkAddrPattern("/test")) {
    /* message was send from the tcp client */
    OscMessage m = new OscMessage("/response");
    m.add("server response: got it");
    /* server responds to the client's message */
    oscP5tcpServer.send(m,theMessage.tcpConnection());
  }
}

`


#3. Problem 1) TCP Comunication - Smartphone → ESP8266-01 & Arduino : Very Well ** 2) TCP Comunication - ESP8266-01 & Arduino → Smartphone** : Error and Shut Down.

**I do not know what the reason. **

I hope someone hoping to me is hope. Please answer fast.

Can't connect simple Android sketch to running emulator. Why?

$
0
0

Windows 10 PC running processing 3.2.1. Added Android Mode via configuration manager. Created new sketch, switched to Android Mode and entered simple code from "Rapid Android Development":

void setup() { size(400,400); }

void draw() { ellipse(mouseX, mouseY, mouseX-pmouseX, mouseY-pmouseY); }

Compilation proceeds normally, emulator (5566:Processing-0253) pops up then console writes this:

Error type 2

android.util.AndroidException: Can't connect to activity manager; is the system running?

at com.android.commands.am.Am.onRun(Am.java:376)

at com.android.internal.os.BaseCommand.run(BaseCommand.java:51)

at com.android.commands.am.Am.main(Am.java:121)

at com.android.internal.os.RuntimeInit.nativeFinishInit(Native Method)

at com.android.internal.os.RuntimeInit.main(RuntimeInit.java:262)

The key phrase is "activity manager" which, I assume, would have normally started up when compilation finished and the emulator initialized.

Thanks for any tips...

1. Is preferences.txt read when processing starts? 2. Why doesn't my file structure work?

$
0
0

Returning to processing and trying to do more with Android Mode. But I have been having trouble, probably due in part to the disorganized mess I left behind. I am now trying to establish a well-organized file layout for both Java and Android Mode hobby programming. Here's what I have now:

C:\processing-3.2.1\mode, with folders which (I think) provides P3 support for Android and Java modes

C:\Users\{me}\Workbench\P3\sketches\modes\AndroidMode\sdk, which (should) provide the Android native API

In C:\Users\{me}\AppData\Roaming\Processing is the file preferences.txt which contains this line:

android.sdk.path=C:\Users\Bob\Workbench\P3\sketches\modes\AndroidMode\sdk

Yet, when I start P3 and click on the mode menu initialized to "Java" I don't see Android as an option. Instead, I have to click on Add Mode. Unfortunately, this afternoon (Sept. 3) the configuration manager pops up but is stuck -- showing only a whirligig. (I guess processing.org is down.)

Q1: Doesn't P3 read preferences.txt on startup?

Q2: Or is my file structure somehow inconsistent.

Note: I tried installing Android Mode 0255 (from Github) into a separate location and modifying preferences.txt accordingly. It didn't work. But I have little confidence I did that operation properly.

Thanks, Bob

Loading SVG file in Android Studio

$
0
0

So, here is how this nightmare of mine goes. I am using Android Studio, using Processing, I get to create sketches without a problem, everything great. The problem is when in one of my sketches I try to load a file, an SVG file in order to create a PShape, the app doesn't know where the "data" folder is, and the problem is, I don't know where should I locate such folder or how to targer the file within my code. Thanks a lot.

 import processing.core.PApplet;
import processing.core.PShape;
import processing.core.PVector;

public class Menu extends PApplet {
    /**************************************************/
    //icon:
    PShape icon;

    /**************************************************/
    public void settings()
    {
        size(displayHeight, displayHeight);
    }
    /**************************************************/
    public void setup()
    {
        icon =  loadShape("menu.svg");  //here is where an error occurs;
    }
    /**************************************************/
    public void draw()
    {
        background(0);
    }
    /**************************************************/

Problem with loading Interstitial Ad

$
0
0

hi, I work on android studio and I've tried to add ads to a basic processing code application. But, I haven't succeeded with that. How can I show an Interstitial ad in processing class which is a fragment in the main activity? Here's my code that I'm working on:

package com.example.processingexample;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;

import processing.core.PApplet;
import android.app.Activity;
import android.content.Context;
import android.os.Vibrator;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class Sketch extends PApplet {
    public float a=100, b=100;
    public float n=2;
    Activity act;
    SharedPreferences sharedPreferences;
            SharedPreferences.Editor editor;
            boolean adLoaded=false;
            InterstitialAd mInterstitialAd;

        public void settings() {fullScreen(); }

        public void setup() {
            act=getActivity();
            sharedPreferences=PreferenceManager.getDefaultSharedPreferences(act.getApplicationContext());
            editor=sharedPreferences.edit();

            mInterstitialAd=newInterstitialAd();
            loadInterstitial();

            n=sharedPreferences.getFloat("n", 2);


        }

        public void draw() {
            background(51);

            translate(width/2,height/2);
            noFill();
            stroke(255);

            beginShape();
            for(float angle=0; angle<TWO_PI; angle+=0.1) {
                float na=2/n;
                float x=5*pow(abs(cos(angle)),na)*a*sgn(cos(angle));
                float y=5*pow(abs(sin(angle)),na)*a*sgn(sin(angle));
                vertex(x,y);
            }
            endShape(CLOSE);

            if (mousePressed) {
                Vibrator viber=(Vibrator) act.getSystemService(Context.VIBRATOR_SERVICE);
                viber.vibrate(100);
            editor.putFloat("n", n).commit();
            if (mouseX>0) {
                n = map(mouseX, 0, width, PI / 50, 5);
            } if (mouseX<width/5) {
                    println("loading");
                }
        }
            if (adLoaded) {
                showInterstitial();
            }
    }

    public void mousePressed() {

    }

    public float sgn(float a){
        if(a>0)
            return 1;
        else if(a<0)
            return -1;
        else
            return 0;
    }

    private InterstitialAd newInterstitialAd() {
        InterstitialAd interstitialAd = new InterstitialAd(act.getApplicationContext());
        interstitialAd.setAdUnitId(getString(R.string.interstitial_ad_unit_id));
        interstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                adLoaded=true;
            }

            @Override
            public void onAdFailedToLoad(int errorCode) {
                adLoaded=true;
            }

            @Override
            public void onAdClosed() {
                adLoaded=false;
                mInterstitialAd = newInterstitialAd();
                loadInterstitial();
            }
        });
        return interstitialAd;
    }

    private void showInterstitial() {
        // Show the ad if it's ready. Otherwise toast and reload the ad.
        if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
            mInterstitialAd.show();
        }
    }

    private void loadInterstitial() {
        // Disable the next level button and load the ad
        AdRequest adRequest = new AdRequest.Builder()
                .setRequestAgent("android_studio:ad_template").build();
       // System.out.println(adRequest);
        if (mInterstitialAd!=null && adRequest!=null)
         mInterstitialAd.loadAd(adRequest);
    }
}

When I run the application on my phone, it crashes and give me lot of errors:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
                                                                                 at android.os.Handler.<init>(Handler.java:200)
                                                                                 at android.os.Handler.<init>(Handler.java:114)
                                                                                 at com.google.android.gms.ads.internal.prefetch.b.<init>(:com.google.android.gms.DynamiteModulesA:37)
                                                                                 at com.google.android.gms.ads.internal.prefetch.b.<init>(:com.google.android.gms.DynamiteModulesA:31)
                                                                                 at com.google.android.gms.ads.internal.c.<init>(:com.google.android.gms.DynamiteModulesA:106)
                                                                                 at com.google.android.gms.ads.internal.c.<init>(:com.google.android.gms.DynamiteModulesA:92)
                                                                                 at com.google.android.gms.ads.internal.g.<init>(:com.google.android.gms.DynamiteModulesA:55)
                                                                                 at com.google.android.gms.ads.internal.ad.<init>(:com.google.android.gms.DynamiteModulesA:132)
                                                                                 at com.google.android.gms.ads.ChimeraAdManagerCreatorImpl.newAdManagerByType(:com.google.android.gms.DynamiteModulesA:77)
                                                                                 at com.google.android.gms.ads.internal.client.al.onTransact(:com.google.android.gms.DynamiteModulesA:91)
                                                                                 at android.os.Binder.transact(Binder.java:387)
                                                                                 at com.google.android.gms.ads.internal.client.am.newAdManagerByType(:com.google.android.gms:170)
                                                                                 at com.google.android.gms.ads.AdManagerCreatorImpl.newAdManagerByType(:com.google.android.gms:90)
                                                                                 at com.google.android.gms.ads.internal.client.al.onTransact(:com.google.android.gms:91)
                                                                                 at android.os.Binder.transact(Binder.java:387)
                                                                                 at com.google.android.gms.ads.internal.client.zzv$zza$zza.zza(Unknown Source)
                                                                                 at com.google.android.gms.ads.internal.client.zze.zza(Unknown Source)
                                                                                 at com.google.android.gms.ads.internal.client.zzl$3.zzim(Unknown Source)
                                                                                 at com.google.android.gms.ads.internal.client.zzl$3.zzin(Unknown Source)
                                                                                 at com.google.android.gms.ads.internal.client.zzl.zza(Unknown Source)
                                                                                 at com.google.android.gms.ads.internal.client.zzl.zzb(Unknown Source)
                                                                                 at com.google.android.gms.ads.internal.client.zzaf.zzam(Unknown Source)
                                                                                 at com.google.android.gms.ads.internal.client.zzaf.zza(Unknown Source)
                                                                                 at com.google.android.gms.ads.InterstitialAd.loadAd(Unknown Source)
                                                                                 at com.example.processingexample.Sketch.loadInterstitial(Sketch.java:119)
                                                                                 at com.example.processingexample.Sketch.setup(Sketch.java:31)
                                                                                 at processing.core.PApplet.handleDraw(PApplet.java:2122)
                                                                                 at processing.core.PGraphicsAndroid2D.requestDraw(PGraphicsAndroid2D.java:172)
                                                                                 at processing.core.PApplet.run(PApplet.java:2013)
                                                                                 at java.lang.Thread.run(Thread.java:818)

Cannot run program "adb" !

$
0
0

All of a sudden my Android mode isn't working!

java.io.IOException: Cannot run program "adb": error=13, Permission denied

I'm on Mac OS with latest versions of everything installed. No idea what to do.

Help! Glenn.


Lagging video: CameraGettingStarted example

$
0
0

Hi

I was working with an android sample code accessing the camera and I notice it is lagging. Is that normal? I am using 5.0.1. and processing 3.0.2 on a Galaxy VI (no emulator). I am hopping to quantify color segments in the screen but the videos seems to skip frames. It feels like is playing one frame every 2 or 3 seconds instead of the desirable 30 fps that you get running in java mode (using an external camera - and not this specific example). Is there anything I could do to have better video rates?

Cheers,

Kf

import android.os.Environment;
import ketai.camera.*;


KetaiCamera cam;

void settings() {
  fullScreen();
}

void setup() {
  orientation(LANDSCAPE);
  imageMode(CENTER);
  textSize(45);
}
void draw() {
  if(cam != null && cam.isStarted()){
     image(cam, width/2, height/2, width, height);
     text("Number of cams \n" +
      cam.getNumberOfCameras(),  0, 0, width/2-100, height/2);

    cam.loadPixels();
    int brightestX = 0; // X-coordinate of the brightest video pixel
    int brightestY = 0; // Y-coordinate of the brightest video pixel
    float brightestValue = 0; // Brightness of the brightest video pixel
     int index = 0;
    for (int y = 0; y < cam.height; y++) {
      for (int x = 0; x < cam.width; x++) {
        // Get the color stored in the pixel
        int pixelValue = cam.pixels[index];
        // Determine the brightness of the pixel
        float pixelBrightness = brightness(pixelValue);
        // If that value is brighter than any previous, then store the
        // brightness of that pixel, as well as its (x,y) location
        if (pixelBrightness > brightestValue) {
          brightestValue = pixelBrightness;
          brightestY = y;
          brightestX = x;
        }
        index++;
      }
    }
    // Draw a large, yellow circle at the brightest pixel
    fill(255, 204, 0, 128);
    ellipse(brightestX, brightestY, 200, 200);
  }
  else
    {
      background(128);
      text("Waiting for camera....touch to activate", 100, height/2);
    }
}

void onCameraPreviewEvent()
{
  cam.read();
}

// start/stop camera preview by tapping the screen
void mousePressed()
{
  //HACK: Instantiate camera once we are in the sketch itself
  if(cam == null)
      cam = new KetaiCamera(this, 640, 480, 24);

  if (cam.isStarted())
  {
    cam.stop();
  }
  else
    cam.start();
}
void keyPressed() {
  if(cam == null)
    return;

  if (key == CODED) {
    if (keyCode == MENU) {
      if (cam.isFlashEnabled())
        cam.disableFlash();
      else
        cam.enableFlash();
    }
  }
}

ANDROID MODE 4+ support to Keitai camera, or other ways to access camera?

$
0
0

Hey, how is it going?

Im working on an app that needs to get videos from the mobile`s camera in real time. Before downloading version 4+ of android mode it was working fine, but I had to get 4+ because its gonna be a virtual reality (cardboard) app.

I was using android 7.0 (API 24) and it was working, i could access the camera using the CameraGettingStarted from ketai, but the recommended android SDK for android mode 4+ is the 6.0 (API 23) and since ive installed it the example doesnt work, it crashes when I click to start the camera. One thing ive noticed is that it doesnt crash until i click, so i tried putting the line:

cam = new KetaiCamera(this, width, height, 24);

inside setup, and then it crashes when it starts, suggesting that this is the part when something wrong happens.

Anyone tried accessing camera using the same android mode and sdk versions? Any suggestions?

One other solution would be getting the images from the camera without the library, but I have no idea how to do that.

Basically i need to get the camera in real time to do some image processing to the frames and display them. Here`s an example code, what i get is: gray screen with "Waiting for camera....touch to activate" working with cardboard features, when i click the screen it crashes, if i put that line on setup it crashes when it starts. Its basically the getting started example from ketai with cardboard added

import processing.cardboard.*;
import ketai.camera.*;

KetaiCamera cam;

void setup() {
  fullScreen(PCardboard.STEREO);
  orientation(LANDSCAPE);
  imageMode(CENTER);
  textSize(45);

  //cam = new KetaiCamera(this, 640, 480, 24); //this is the line that crashes when app starts if not commented
}

void draw() {
  background(0);
  if (cam != null && cam.isStarted())
    image(cam, width/2, height/2, width, height);
  else {
    background(128);
    text("Waiting for camera....touch to activate", 100, height/2);
  }
}

void onCameraPreviewEvent() {
  cam.read();
}

// start/stop camera preview by tapping the screen
void mousePressed()
{
  //HACK: Instantiate camera once we are in the sketch itself
  if (cam == null)
    cam = new KetaiCamera(this, 640, 480, 24);

  if (cam.isStarted())
  {
    cam.stop();
  } else
    cam.start();
}
void keyPressed() {
  if (cam == null)
    return;

  if (key == CODED) {
    if (keyCode == MENU) {
      if (cam.isFlashEnabled())
        cam.disableFlash();
      else
        cam.enableFlash();
    }
  }
}

any tips or ideas welcome! thanks in advance!

Load image files from external storage to PImage

$
0
0

Hey, im having some trouble loading images to PImages inside a android processing sketch. Here`s the code, based on this thread https://forum.processing.org/two/discussion/9893/save-images-in-specific-folders-android#latest

import android.os.Environment;

PImage img;

void setup(){
  String directory = new String(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Atelie");

 img = loadImage(directory + "img2.png"); //i have also tried "/img2.png"
 image(imagem, 0, 0);
}

void draw(){
image(img, 0, 0);
}

The images are on a folder called Atelie that I have created using android file transfer, and I can see them in my mobile.

The sketch compiles, install, and crashes as soon as it opens, probably because it is not finding the file, no console erros.

The Read External Storage permission is marked.

Im using processing 3.2.1, Android mode 4.0-beta2, API 23, Asus Zenphone 2 Laser android 5.0.2

thanks in advance

I need someone knowledgeable on Bluetooth Low Energy and Android Mode.

$
0
0

I am currently porting my Classic Bluetooth System to the new BLE.

Previouly, I was using KETAI library to access Bluetooth communication on my Android Device so it can communicate with my Arduino Uno with a HC-05 Bluetooth module. Everything worked well.

Now, I am using Bluefruit LE Micro (by Adafruit, An arduino-compatible chip with BLE from Nordic)

I am having troubles with the Bluetooth Low Energy side of this module.

I have found a library called BLEPDROID on github that utilizes Bluetooth low energy and Processing together with RFDuino but the library does not provide adequate tutorial on how to use their codes. I am not an expert when it comes to understanding codes so it is quite difficult for me.

If someone can guide me through their Library that would help OR if you can suggest a better library or way for me to understand how to code with BLE that would also help.

Importing processing.net lib to Android sketch

$
0
0

Isn't it possible to import and use Network lib (import processing.net.*;) to a android mode sketch?

Any other solution to network connectivity?

Develop app for daydreaming in Processing?

$
0
0

Is it possible to develop an app in Processing for android which can be used for daydreaming? I haven't been able to find anything about it online. If it is possible some sources for me to look at would be appreciated.

Receive OSC using OscP5 library, Android Mode 4.0-beta2

$
0
0

Hey, how is it going?

Im trying to receive osc on my mobile, using OscP5 library and android mode 4.0-beta2. Codes:

Android app

import oscP5.*;
import netP5.*;

OscP5 oscP5;
NetAddress endereco;

float x = 1.0;
float y = 2.0;
float z = 3.0;

void setup() {
  fullScreen();
  orientation(LANDSCAPE);
  textSize(100);
  oscP5 = new OscP5(this, 9000);
  endereco = new NetAddress("localhost", 10000); // not sure if i even need to import netP5
}

void draw() {
  background(0);
  fill(255);
  text("x = " + x, 20, 200);
  text("y = " + y, 20, 400);
  text("z = " + z, 20, 600);
}

void oscEvent(OscMessage mensagem) {
  // tests if any message is being received at all
  fill(255);
  rect(50, 30, 100, 100);

  if (mensagem.checkAddrPattern("/x")) x = mensagem.get(0).floatValue();
  else if (mensagem.checkAddrPattern("/y")) y = mensagem.get(0).floatValue();
  else if (mensagem.checkAddrPattern("/z")) z = mensagem.get(0).floatValue();
}

Java code running on my laptop

import oscP5.*;
import netP5.*;

OscP5 osc;
NetAddress endereco;

float x = 0;
float y = 0;
float z = 0;

OscMessage mx = new OscMessage("/x");
OscMessage my = new OscMessage("/y");
OscMessage mz = new OscMessage("/z");

void setup() {
  osc = new OscP5(this, 12000);
  endereco = new NetAddress("192.168.25.2", 9000);

}

void draw() {
}

void keyPressed() {
  if (key == 'q') {
    x += 10.4;
    mx.add(x);
    osc.send(mx, endereco);
    mx.clearArguments();
  } else if (key == 'w') {
    x -= 10.5;
    mx.add(x);
    osc.send(mx, endereco);
    mx.clearArguments();
  } else if (key == 'a') {
    y += 10.4;
    my.add(y);
    osc.send(my, endereco);
    my.clearArguments();
  } else if (key == 's') {
    y -= 10.5;
    my.add(y);
    osc.send(my, endereco);
    my.clearArguments();
  } else if (key == 'z') {
    z += 10.4;
    mz.add(z);
    osc.send(mz, endereco);
    mz.clearArguments();
  } else if (key == 'x') {
    z -= 10.5;
    mz.add(z);
    osc.send(mz, endereco);
    mz.clearArguments();
  }
}

They are both connected to the same Wifi network, im pretty sure the IP address is correct, but it just does not receive the message sent, the INTERNET permission is checked for the app. What can I be missing?

Using Processing 3.2.1, Android Mode 4.0-beta2, Android 6.0 (API 23), Zenphone 2 Laser Android 5.0.2.

All best Thanks in advance


Detecting Multiple Touches in Android Mode

$
0
0

Hi, I am using Processing to prototype an app for Android. I need to detect two simultaneous touches of the screen. How do you do with with Processing?

Thanks.

Updated example for Bluetooth using android API's?

$
0
0

Hey all,

I've been looking through examples/tutorials on establishing a bluetooth connection in Android mode for processing using android API's (as opposed to Ketai). Ketai is really great, but I am trying to use another java library that uses android sockets.

I've been looking through tutorials like this one: http://arduinobasics.blogspot.com.au/2013/03/arduinobasics-bluetooth-android.html

Which is nice, but it was done in processing 2 and targeted SDK version 10. (I'll paste the code at the end of the post).

I am currently using Processing 3.0, targeting SDK version 23 (android 6.0). I have been having trouble with certain parts of that tutorial which I believe are due to the fact that the Android SDK has changed quite a bit since it was written. For example, startActivityForResult() has issues (function doesn't exist) -- I from what I've read it is now something launched from a fragment instead of an activity?

Anyways, I am wondering if anyone can point me to a sample/example/tutorial that might have an updated guide for dealing with bluetooth using the modern android APIs.

Thank you, B

/* ConnectBluetooth: Written by ScottC on 18 March 2013 using
 Processing version 2.0b8
 Tested on a Samsung Galaxy SII, with Android version 2.3.4
 Android ADK - API 10 SDK platform */

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;
import android.view.Gravity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

import java.util.UUID;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.util.Log;

import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;

boolean foundDevice=false; //When true, the screen turns green.
boolean BTisConnected=false; //When true, the screen turns purple.



//Get the default Bluetooth adapter
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();


/*The startActivityForResult() within setup() launches an
 Activity which is used to request the user to turn Bluetooth on.
 The following onActivityResult() method is called when this
 Activity exits. */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
 if(requestCode==0){
 if(resultCode == RESULT_OK){
 ToastMaster("Bluetooth has been switched ON");
 } else {
 ToastMaster("You need to turn Bluetooth ON !!!");
 }
 }
}



/* Create a BroadcastReceiver that will later be used to
 receive the names of Bluetooth devices in range. */
BroadcastReceiver myDiscoverer = new myOwnBroadcastReceiver();

/* Create a BroadcastReceiver that will later be used to
 identify if the Bluetooth device is connected */
BroadcastReceiver checkIsConnected = new myOwnBroadcastReceiver();


void setup(){
 orientation(LANDSCAPE);
 /*IF Bluetooth is NOT enabled, then ask user permission to enable it */
 if (!bluetooth.isEnabled()) {
 Intent requestBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
 startActivityForResult(requestBluetooth, 0);
 }

 /*If Bluetooth is now enabled, then register a broadcastReceiver to report any
 discovered Bluetooth devices, and then start discovering */
 if (bluetooth.isEnabled()) {
 registerReceiver(myDiscoverer, new IntentFilter(BluetoothDevice.ACTION_FOUND));
 registerReceiver(checkIsConnected, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));

 //Start bluetooth discovery if it is not doing so already
 if (!bluetooth.isDiscovering()){
 bluetooth.startDiscovery();
 }
 }
}



void draw(){
 //Display a green screen if a device has been found,
 //Display a purple screen when a connection is made to the device
 if(foundDevice){
 if(BTisConnected){
 background(170,50,255); // purple screen
 }else {
 background(10,255,10); // green screen
 }
 }
}



/* This BroadcastReceiver will display discovered Bluetooth devices */
public class myOwnBroadcastReceiver extends BroadcastReceiver {
 @Override
 public void onReceive(Context context, Intent intent) {
 String action=intent.getAction();
 ToastMaster("ACTION:" + action);

 //Notification that BluetoothDevice is FOUND
 if(BluetoothDevice.ACTION_FOUND.equals(action)){
 //Display the name of the discovered device
 String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
 ToastMaster("Discovered: " + discoveredDeviceName);

 //Display more information about the discovered device
 BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
 ToastMaster("getAddress() = " + discoveredDevice.getAddress());
 ToastMaster("getName() = " + discoveredDevice.getName());

 int bondyState=discoveredDevice.getBondState();
 ToastMaster("getBondState() = " + bondyState);

 String mybondState;
 switch(bondyState){
 case 10: mybondState="BOND_NONE";
 break;
 case 11: mybondState="BOND_BONDING";
 break;
 case 12: mybondState="BOND_BONDED";
 break;
 default: mybondState="INVALID BOND STATE";
 break;
 }
 ToastMaster("getBondState() = " + mybondState);

 //Change foundDevice to true which will make the screen turn green
 foundDevice=true;

 //Connect to the discovered bluetooth device (SeeedBTSlave)
 if(discoveredDeviceName.equals("SeeedBTSlave")){
 ToastMaster("Connecting you Now !!");
 unregisterReceiver(myDiscoverer);
 ConnectToBluetooth connectBT = new ConnectToBluetooth(discoveredDevice);
 //Connect to the the device in a new thread
 new Thread(connectBT).start();
 }
 }

 //Notification if bluetooth device is connected
 if(BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)){
 ToastMaster("CONNECTED _ YAY");
 BTisConnected=true; //turn screen purple
 }
 }
}

public class ConnectToBluetooth implements Runnable{
 private BluetoothDevice btShield;
 private BluetoothSocket mySocket = null;
 private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

 public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
 btShield = bluetoothShield;
 try{
 mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
 }catch(IOException createSocketException){
 //Problem with creating a socket
 }
 }

 @Override
 public void run() {
 /* Cancel discovery on Bluetooth Adapter to prevent slow connection */
 bluetooth.cancelDiscovery();

 try{
 /*Connect to the bluetoothShield through the Socket. This will block
 until it succeeds or throws an IOException */
 mySocket.connect();
 } catch (IOException connectException){
 try{
 mySocket.close(); //try to close the socket
 }catch(IOException closeException){
 }
 return;
 }
 }

 /* Will cancel an in-progress connection, and close the socket */
 public void cancel() {
 try {
 mySocket.close();
 } catch (IOException e){
 }
 }
}


/* My ToastMaster function to display a messageBox on the screen */
void ToastMaster(String textToDisplay){
 Toast myMessage = Toast.makeText(getApplicationContext(),
 textToDisplay,
 Toast.LENGTH_SHORT);
 myMessage.setGravity(Gravity.CENTER, 0, 0);
 myMessage.show();
}

Lost Connection with device while launching.Try again

$
0
0

I am repeatedly getting the error "Lost connection with device while launching",though after sometime emulator starts but shows nothing(Only "Android" written on screen).I have also checked the Preference File but the Port Number is same as that on the emulator.I am using API 23 and Processing version 3.0.2 Can anybody help what's the problem?? Thank You.

How to correctly exit a Processing sketch in Android

$
0
0

I am currently building an app in Android Studio involving a Processing sketch.

Main class:

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

    import processing.android.PFragment;
    import processing.core.PApplet;

    public class ClassMain extends Activity {
        /**************************************************/
        PApplet sketch;
        /**************************************************/
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.class_main);

            FragmentManager fragmentManager = getFragmentManager();
            sketch = new ClassSketch();
            PFragment fragment = new PFragment();
            fragment.setSketch(sketch);
            fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
        }
        /**************************************************/
        @Override
        public void onBackPressed()
        {

            //ClassMain.this.finish();
        }
        /**************************************************/
        //It doesn't work if called from sketch...
        public void exits()
        {
            ClassMain.this.finish();
        }
        /**************************************************/
    }

Processing Sketch:

    import android.view.KeyEvent;
    import processing.core.PApplet;

    public class ClassSketch extends PApplet {
        /*****************************************************************************/
        public void settings()
        {
            size(displayWidth, displayHeight);
        }
        /*****************************************************************************/
        public void setup()
        {
        }
        /*****************************************************************************/
        public void draw()
        {
            keykey();
        }
        public void keykey()
        {
            if(keyPressed)
            {
                if (key == CODED) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        //non of the following work:
                        //exit();
                        ClassMain j = new ClassMain();
                        j.exits();
                    }
                }
            }
        }
    }

Here is the problem, I want the the user, depending on some circumstances that I will add later in the sketch, to exit not only the sketch but the class that is hosting it (ClassMain). When ever (in the sketch) something happens in my sketch, I want to be able to exit the whole MainClass, but I just happen to fail. Thanks for the support.

I can't create the Signed app Package

$
0
0

Hello! I don't really understand this error...

Can you help me ?

java.io.IOException: Cannot run program "/home/desktop/processing-3.2.1/java/bin/keytool": error=2, Aucun fichier ou dossier de ce type at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048) at java.lang.Runtime.exec(Runtime.java:620) at java.lang.Runtime.exec(Runtime.java:485) at processing.mode.android.AndroidKeyStore.generateKeyStore(AndroidKeyStore.java:80) at processing.mode.android.KeyStoreManager$1.actionPerformed(KeyStoreManager.java:94) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022) at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252) at java.awt.Component.processMouseEvent(Component.java:6533) at javax.swing.JComponent.processMouseEvent(JComponent.java:3324) at java.awt.Component.processEvent(Component.java:6298) at java.awt.Container.processEvent(Container.java:2236) at java.awt.Component.dispatchEventImpl(Component.java:4889) at java.awt.Container.dispatchEventImpl(Container.java:2294) at java.awt.Component.dispatchEvent(Component.java:4711) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466) at java.awt.Container.dispatchEventImpl(Container.java:2280) at java.awt.Window.dispatchEventImpl(Window.java:2746) at java.awt.Component.dispatchEvent(Component.java:4711) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758) at java.awt.EventQueue.access$500(EventQueue.java:97) at java.awt.EventQueue$3.run(EventQueue.java:709) at java.awt.EventQueue$3.run(EventQueue.java:703) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86) at java.awt.EventQueue$4.run(EventQueue.java:731) at java.awt.EventQueue$4.run(EventQueue.java:729) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:728) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93) at java.awt.EventDispatchThread.run(EventDispatchThread.java:82) Caused by: java.io.IOException: error=2, Aucun fichier ou dossier de ce type at java.lang.UNIXProcess.forkAndExec(Native Method) at java.lang.UNIXProcess.(UNIXProcess.java:247) at java.lang.ProcessImpl.start(ProcessImpl.java:134) at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029) ... 40 more

Viewing all 941 articles
Browse latest View live