Alert.png

Notice: This page contains information for the legacy Phidget21 Library.

Phidget21 is out of support. Bugfixes may be considered on a case by case basis.

Phidget21 does not support VINT Phidgets, or new USB Phidgets released after 2020. We maintain a selection of legacy devices for sale that are supported in Phidget21.

We recommend that new projects be developed against the Phidget22 Library.


Click on the 2phidget22.jpg button in the menu bar to go to the Phidget22 version of this page.

Alert.png

Language - Android Java: Difference between revisions

From Phidgets Legacy Support
No edit summary
 
(38 intermediate revisions by 5 users not shown)
Line 1: Line 1:
[[Category:Language]]
[[Category:Language]]
[[File:Icon-Android.png‎|64x64px|link=]] Android Java is the main language used to program for the [[OS - Android|Android OS]].
{{OSLang|[[File:Icon-Android.png‎|64x64px|link=|alt=]]|Android Java is the main language used to program for the [[OS - Android|Android OS]].}}
 
 
__TOC__
__TOC__


Line 11: Line 9:
==Quick Downloads==
==Quick Downloads==
{{QuickDownloads|Android|
{{QuickDownloads|Android|
{{APIQuickDownloads|http://www.phidgets.com/documentation/JavaDoc.zip}}|
{{APIQuickDownloads|{{SERVER}}/documentation/JavaDoc.zip}}
{{ExampleQuickDownloads|http://www.phidgets.com/downloads/examples/android-examples_2.1.8.20120216.tar.gz|(and Phidget Android Library)}}|
{{ExtraAPIQuickDownloads|{{SERVER}}/documentation/web/javadoc/index.html|HTML Version of}}|
{{ExtraLibraryQuickDownloads|http://www.phidgets.com/downloads/examples/android-examples_2.1.8.20120216.tar.gz||(Phidget21.jar included in Examples)}}
{{ExampleQuickDownloads|{{SERVER}}/downloads/phidget21/examples/java/android-examples.tar.gz|}}|
{{ExtraLibraryQuickDownloads|{{SERVER}}/downloads/phidget21/examples/java/android-examples.tar.gz||(Phidget21.jar included in Examples)}}
{{WindowsQuickDownloads}}
{{WindowsQuickDownloads}}
{{MacQuickDownloads}}
{{MacQuickDownloads}}
Line 30: Line 29:
Phidgets can run directly plugged in to Android devices with a USB port and system 3.1 or later.   
Phidgets can run directly plugged in to Android devices with a USB port and system 3.1 or later.   


Otherwise, Android can control a Phidget remotely over a network, by using the [[Phidget Webservice]]
Otherwise, Android can control a Phidget remotely over a network, by using the [[Phidget WebService]]


Hence, we split instructions up by Android OS version number.
Hence, we split instructions up by Android OS version number.
Line 36: Line 35:
===Android Under 3.1 (and/or no USB Port)===
===Android Under 3.1 (and/or no USB Port)===


These types of phones and tablets can use Phidgets only remotely over a network using the [[#Webservice|Phidget Webservice]].
These types of phones and tablets can use Phidgets only remotely over a network using the [[OS - Android#WebService|Phidget WebService]].


====Use Our Examples====
====Use Our Examples====


Download and unpack the [http://www.phidgets.com/downloads/examples/android-examples_2.1.8.20120216.tar.gz Phidget Examples for Android].  There are two Hello World examples: {{Code|HelloWorldRemote}} (the one you want), and {{Code|HelloWorldUSB}} (for tablets with a USB port).
Download and unpack the [{{SERVER}}/downloads/phidget21/examples/java/android-examples.tar.gz Phidget Examples for Android].  There are two InterfaceKit examples: {{Code|InterfaceKitExample}} (the one you want), and {{Code|InterfaceKitUSBExample}} (for tablets with a USB port).


Import the {{Code|HelloWorldRemote}} example into Eclipse:
Import the {{Code|InterfaceKitExample}} example into Eclipse:
* File → Import... → General → Existing Projects Into Workspace → (Next)
* File → Import... → General → Existing Projects Into Workspace → (Next)
* Select {{Code|HelloWorldRemote}} root directory → Select all files → Finish
* Select {{Code|InterfaceKitExample}} root directory → Select all files → Finish


Note that you '''must change''' the IP address within the example code to the IP address of the computer directly connected to the Phidget you are trying to control.  This happens on the line that says something like:
Make sure the .jar files are included in the Java build path:
* Right click the project name, select "Properties" from the menu that pops up.
* Select "Java Build Path" from the menu on the left.
* Select the "Libraries" tab.
* If phidget21.jar or PhidgetsUSB.jar are not visible, click "Add Jars..." and add both files. (These files should both be in the "libs" folder of the android project.)
 
Next, you '''must change''' the IP address within the example code to the IP address of the computer directly connected to the Phidget you are trying to control.  This happens on the line that says something like:
<div class="source">
<div class="source">
<syntaxhighlight lang=java>
<syntaxhighlight lang=java>
Line 53: Line 58:
</div>
</div>


Also note that the HelloWorldRemote example was written for Android 2.1.  You can change this in:
Also, note that the InterfaceKitExample example was written for Android 2.1.  If needed, you can change this in:
(Right Click on Project) &rarr; Properties &rarr; Resource (on left) &rarr; Android
(Right Click on Project) &rarr; Properties &rarr; Resource (on left) &rarr; Android


Line 62: Line 67:
This will bring up the Android Virtual Device manager window.  If your Android hardware is plugged in to your debugging computer, you will see the hardware as an option on which to run the example.  You should run it directly on your Android device, unless you are comfortable setting up the emulator to run on your local network.
This will bring up the Android Virtual Device manager window.  If your Android hardware is plugged in to your debugging computer, you will see the hardware as an option on which to run the example.  You should run it directly on your Android device, unless you are comfortable setting up the emulator to run on your local network.


After the {{Code|HelloWorldRemote}} application starts running on your device:  
After the {{Code|InterfaceKitExample}} application starts running on your Android device:  
# Make sure the Phidget Webservice is running on the computer with the IP address you put into the code
# Make sure the Phidget WebService is running on the computer with the IP address you put into the code. If you're using Linux, remember to run the webservice as root.
#*For directions on how to set up and run the webservice on a remote computer, refer to the page [[Software Overview#Operating System Support|for that operating system]]
#*For directions on how to set up and run the webservice on a remote computer, refer to the page [[Software Overview#Operating System Support|for that operating system]]
# Plug a Phidget into that computer
# Plug a Phidget into that computer


And on your Android device, you should see something like:
And on your Android device, you should see something like:
[[Image:android_helloworld_remotehello.png|alt=|link=]]


[[File:Android Attached.png|700px|alt=|link=]]
Notice the line in the top left that says: "Status: Attached". When you unplug that Phidget from the remote computer, you should see that line change:
[[File:Android Detached.png|700px|alt=|link=]]


====Write Your Own Code====
====Write Your Own Code====


When you download and unzip the <span style="color:red;">Phidget Library</span> for Android, it will contain three things:
To write your own code from scratch, start with an Android project in Eclipse (File &rarr; New &rarr; Android Project).  Then....
# A libs/ folder
 
=====Step One: Link the Phidget Libraries to your Project=====
 
When you download and unzip the [{{SERVER}}/downloads/phidget21/examples/java/android-examples.tar.gz Phidget Examples for Android], each project folder will (in addition to the project files themselves) contain three things:
# A libs/ folder (containing an armabi/ folder and a single file called libphidget21.so)
# A jar file containing the general Phidget java library (phidget21.jar)
# A jar file containing the general Phidget java library (phidget21.jar)
# A jar file for directly driving USB devices from a USB port on the Android device (PhidgetsUSB.jar)
# A jar file for directly driving USB devices from a USB port on the Android device (PhidgetsUSB.jar)


To install libraries to run a Phidget '''remotely''' over a network using the Webservice:
Copy the {{Code|libs}} folder, the {{Code|PhidgetsUSB.jar}} file, and the {{Code|phidget21.jar}} file to your project folder.
* Add libs/ and phidget21.jar to your project
 
* Add the following to your <code>AndroidManifest.xml</code> file:
To install libraries to run a Phidget '''remotely''' over a network using the WebService:
# Add the libs/ folder to your project
#* To add the libs/ folder in Eclipse, simply place it in the root folder of your project
# Add the phidget21.jar file to the "libs" folder of your project
#* In Eclipse use the top-bar menu: Project &rarr; Properties &rarr; Java Build Path &rarr; Libraries (tab) &rarr; Add JAR
 
=====Step Two: Give your Program Permission to use the Internet=====
 
Add the following to your <code>AndroidManifest.xml</code> file:


<div class="source"><syntaxhighlight lang=xml>
<div class="source"><syntaxhighlight lang=xml>
     <uses-permission android:name="android.permission.INTERNET"></uses-permission>
     <uses-permission android:name="android.permission.INTERNET"></uses-permission>
</syntaxhighlight></div>
</syntaxhighlight></div>


Before you can use the Phidget, you must include a reference in the code to the library. In Android Java:
=====Step Three: Include the Phidget Libraries in your Source=====
 
Then, in your code, include an {{Code|import}} reference to the library. In Android Java:


<div class="source"><syntaxhighlight lang=java>
<div class="source"><syntaxhighlight lang=java>
Line 97: Line 119:
</syntaxhighlight></div>
</syntaxhighlight></div>


Remember to add your libraries and .jar files to where Java can find them. 
Then you are ready to begin coding!
In Eclipse, jar files and library files can be added to a project by:
* Project &rarr; Properties &rarr; Java Build Path &rarr; Libraries (tab) &rarr; Add JAR
* Project &rarr; Properties &rarr; Java Build Path &rarr; Libraries (tab) &rarr; Add Library


===Android 3.1+ with USB Port===
===Android 3.1+ with USB Port===


If your tablet has a USB host port and is running Android 3.1 or later, you can plug Phidgets directly into it.


====Use Our Examples====
====Use Our Examples====


Unpack the <span style="color:red;">Phidget Examples</span> for Android.
Download and unpack the [{{SERVER}}/downloads/phidget21/examples/java/android-examples.tar.gz Phidget Examples for Android].  There are two Hello World examples: {{Code|HelloWorld}} (the one you want), and {{Code|HelloWorldRemote}} (for controlling Phidgets over the WebService).


Import one of the Existing Eclipse Projects:
Import the {{Code|HelloWorld}} example into Eclipse:
* File &rarr; Import... &rarr; General &rarr; Existing Projects Into Workspace &rarr; (Next)
* File &rarr; Import... &rarr; General &rarr; Existing Projects Into Workspace &rarr; (Next)
* Select root directory &rarr; Browse to find and select an existing example such as the InterfaceKitExample
* Select {{Code|HelloWorld}} root directory &rarr; Select all files &rarr; Finish


Select all files, click Finish
Note that the HelloWorld example was written for Android 3.1.  If needed, you can change this in:
(Right Click on Project) &rarr; Properties &rarr; Resource (on left) &rarr; Android


Right-click on project in Package Explorer (To open this, use Window &rarr; Show View &rarr; Package Explorer)
To run the example: Right-click on project in Package Explorer (To open the Package Explorer, use Window &rarr; Show View &rarr; Package Explorer)


Select Run As... &rarr; Android Application
Select Run As... &rarr; Android Application


This will bring up the Android Virtual Device manager window.  If your Android hardware is plugged in to your debugging computer, you will see the hardware as an option on which to run the example.  Otherwise, make sure you have an Android Virtual Device (AVD) set up to run the example on (you can do this by clicking <code>New...</code> on the right side).
This will bring up the Android Virtual Device manager window.  If your Android hardware is plugged in to your debugging computer, you will see the hardware as an option on which to run the example.  You should run it directly on your Android device, unless you are comfortable setting up the emulator to use your development computer's USB hub.
 
After the {{Code|HelloWorld}} application starts running on your Android device, plug a Phidget into your Android tablet's USB port!
 
Since the USB device requires special permission, the first thing you will probably see is a request from the Phidget example to use the USB port:
 
[[Image:android_helloworld_usb_permissions.png|500px|alt=|link=]]
 
And on your Android device, depending on which Phidget you plug in, you should see something like:


[[Image:android_helloworld_hello.png|700px|alt=|link=]]
And when you unplug that Phidget from the remote computer, you should see something like this on your Android device:
[[Image:android_helloworld_goodbye.png|700px|alt=|link=]]
If you have the specific Phidget for the other included Android examples (i.e. the InterfaceKit), you can run the other examples in the same way.
If you are having trouble running the examples, a method to debug the Android USB port is on the [[OS - Android]] page, under the Hardware section.


====Write Your Own Code====
====Write Your Own Code====


=====Step One: Include the Phidget Libraries in your Source=====
To write your own code from scratch, start with an Android project in Eclipse (File &rarr; New &rarr; Android Project). Then....
 
<div class="source">
<syntaxhighlight lang=java>
import com.phidgets.*;
import com.phidgets.event.*;
</syntaxhighlight>
</div>


=====Step Two: Link the Phidget Libraries to your Project=====
=====Step One: Link the Phidget Libraries to your Project=====


When you download and unzip the <span style="color:red;">Phidget Library</span> for Android, it will contain three things:
When you download and unzip the [{{SERVER}}/downloads/phidget21/examples/java/android-examples.tar.gz Phidget Examples for Android], each project folder will (in addition to the project files themselves) contain three things:
# A libs/ folder
# A libs/ folder (containing an armabi/ folder and a single file called libphidget21.so)
# A jar file containing the general Phidget java library (phidget21.jar)
# A jar file containing the general Phidget java library (phidget21.jar)
# A jar file for directly driving USB devices from a USB port on the Android device (PhidgetsUSB.jar)
# A jar file for directly driving USB devices from a USB port on the Android device (PhidgetsUSB.jar)


Move the {{Code|libs}} folder and the {{Code|phidget21.jar}} file to your project folder.
Copy the {{Code|libs}} folder, the {{Code|PhidgetsUSB.jar}} file, and the {{Code|phidget21.jar}} file to your project folder.


In Eclipse, jar files and library files can be added to a project by:
To install libraries to run a Phidget '''remotely''' over a network using the WebService:
* Project &rarr; Properties &rarr; Java Build Path &rarr; Libraries (tab) &rarr; Add JAR
# Add the libs/ folder to your project
* Project &rarr; Properties &rarr; Java Build Path &rarr; Libraries (tab) &rarr; Add Library
#* To add the libs/ folder in Eclipse, simply place it in the root folder of your project
# Add the phidget21.jar file to your project
# Also add the PhidgetsUSB.jar file to your project
#* In Eclipse, to add jar files use the top-bar menu: Project &rarr; Properties &rarr; Java Build Path &rarr; Libraries (tab) &rarr; Add JAR


To install libraries to run a Phidget '''directly''' (Android 3.1 and later, with USB port on device):
=====Step Two: Give your Program Permission to use USB=====
* Add libs/, phidget21.jar, and PhidgetsUSB.jar to your project
 
=====Step Three: Give your Program Permission to use USB=====


Add the following to your <code>AndroidManifest.xml</code> file:
Add the following to your <code>AndroidManifest.xml</code> file:
Line 157: Line 188:
</syntaxhighlight></div>
</syntaxhighlight></div>


Before you can use the Phidget, you must include a reference in the code to the library. In Android Java:
=====Step Three: Include the Phidget Libraries in your Source=====
 
Then, in your code, include an {{Code|import}} reference to the library. In Android Java:


<div class="source"><syntaxhighlight lang=java>
<div class="source"><syntaxhighlight lang=java>
Line 167: Line 200:
</syntaxhighlight></div>
</syntaxhighlight></div>


Remember to add your libraries and .jar files to where Java can find them. 
Then you are ready to begin coding!
In Eclipse, jar files and library files can be added to a project by:
* Project &rarr; Properties &rarr; Java Build Path &rarr; Libraries (tab) &rarr; Add JAR
* Project &rarr; Properties &rarr; Java Build Path &rarr; Libraries (tab) &rarr; Add Library


==Follow the Examples==
==Follow the Examples==


By following the instructions above, you probably now have a working example and want to understand it better so you can change it to do what you want. This section has resources for you to learn from the examples and write your own.


Programming with Phidgets in Android Java makes extensive use of the mainstream Java Phidgets library, so the Java API reference will be helpful:


{{UsingAPhidgetInCodeGeneral|although you can only use the event code in Android|[{{SERVER}}/documentation/JavaDoc.zip Java API]}}


===API Support===


===Code Snippets===
Most of the Java API is supported in AndroidHowever, only some of the available open calls are supported:
 
Before writing code of your own, it may help to read about [[General Phidget Programming]] before proceedingWe cover all of the following concepts (open, attach, etc) there in-depth.
 
 
===Step One: Initialize and Open===
 
 
 
In your code, you can open and connect to a Phidget using open() or openAny().


When using a Phidget over a network, you can open the remote Phidget using one of the supported Java API calls:
When using a Phidget over a network, you can open the remote Phidget using one of the supported Java API calls:
Line 217: Line 242:
</syntaxhighlight></div>
</syntaxhighlight></div>


Next, the program needs to try and connect to the Phidget through an open call.
===Code Snippets===
The open will tell the program to continuously try to connect to a Phidget, based on the parameters given, even trying to reconnect if it gets disconnected.  
 
This means that simply calling open does not guarantee you can use the Phidget immediately. We can handle this by using event driven programming and tracking the AttachEvents and DetachEvents, or by calling waitForAttachment.
Specific calls in Android Java will differ in syntax from those on the [[General Phidget Programming]] page, but the concepts stay the same. 
WaitForAttachment will block indefinitely until a connection is made to the Phidget, or an optional timeout is exceeded.
 
It may help to have the [[General Phidget Programming]] page and this section open at the same time, because they parallel each other and you can refer to the Android Java syntax.  However, many additional concepts are covered on the General Phidget Programming page on a high level, such as using multiple Phidgets, handling errors, and different styles of programming.
 
For example, if we were using a [{{SERVER}}/products.php?product_id=1018 Phidget Interface Kit] as our device, the general calls would look like this:
 
====Step One: Initialize and Open====
 
For opening a remote Phidget over the network using the WebService:
 
<div class="source"><syntaxhighlight lang=java>
  InterfaceKitPhidget device;
  device = new InterfaceKitPhidget();
 
  // Open first detected Interface Kit, remotely with IP address and port
  device.open("192.168.3.33", 5001);
</syntaxhighlight></div>
 
For opening a Phidget directly attached to the tablet's USB port:


<div class="source"><syntaxhighlight lang=java>
<div class="source"><syntaxhighlight lang=java>
   
 InterfaceKitPhidget device;
  ik.openAny();
  com.phidgets.usb.Manager.Initialize(this);
  ik.waitForAttachment();
device = new InterfaceKitPhidget();
   
 
  // Open locally, with Phidget in tablet USB port
 ik.open("192.168.3.33", 5001);
</syntaxhighlight></div>
</syntaxhighlight></div>


The parameters can be used to open the first Phidget of a type it can find, open based on its serial number, or even open across the network.
The direct open call prevents any other instances from retrieving data from the Phidget, including other programs.  
The API manual lists all of the available modes that open provides.
The one connection per device limit does not apply when exclusively using the Phidget WebService.
One important thing to remember is that when working with Phidgets, a local connection will reserve the device until closed.
 
This prevents any other instances from retrieving data from the Phidget, including other programs.  
Both open calls will tell the program to continuously try to connect to a Phidget, based on the parameters given, even trying to reconnect if it gets disconnected.
The one connection per device limit does not apply when exclusively using the Phidget Webservice.
This means that simply calling open does not guarantee you can use the Phidget immediately. We can handle this by using event driven programming and tracking the AttachEvents and DetachEvents....
At the end of your program, don’t forget to call close to free any locks on the Phidget.
 
====Step Two: Wait for Attachment (plugging in) of the Phidget====
 
To use the Phidget, it must be plugged in and a software event caught (i.e. attached).
 
Android Java is '''only''' event-driven, so you cannot use {{Code|waitForAttachment()}} without hanging and being relatively unsafe with your threads.  Instead, you should define an event handler function that you can then synchronize and tie in with the attachment event itself.
 
First, let's write our handler:


<div class="source"><syntaxhighlight lang=java>
<div class="source"><syntaxhighlight lang=java>
  class AttachEventHandler implements Runnable {
  ik.close();
    Phidget device;
  ik = null;
    TextView eventOutput;
 
    public AttachEventHandler(Phidget device, TextView eventOutput) {
      this.device = device;
      this.eventOutput = eventOutput; }
 
    public void run() {
      try {
        // The actual useful thing our handler does
eventOutput.setText("Hello " + device.getDeviceName() + ", Serial " + Integer.toString(device.getSerialNumber()));
      } catch (PhidgetException e) { e.printStackTrace(); }
       
      // Notify whoever called us (and is waiting) that we're done
      synchronized(this) { this.notify(); }
    }
  }
</syntaxhighlight></div>
</syntaxhighlight></div>


===Event Driven Programming===
This may seem complex, but really it is just:
# A class wrapper so we can work independently once we get permission from the main thread, and
# A way to call back to the {{Code|synchronized()}} call to let them know we're done and stay thread safe
 
Now that we have our 'handler' we can hook it in as an event function to trigger on device attachment:
 
<div class="source"><syntaxhighlight lang=java>
device.addAttachListener(new AttachListener() {
  public void attached(final AttachEvent attachEvent) {
    AttachEventHandler handler = new AttachEventHandler(attachEvent.getSource(), eventOutput);
 
    // This is synchronised in case more than one device is attached before one completes attaching
    synchronized(handler) {


We recommend the use of event driven programming when working with Phidgets. In Java, we hook
      runOnUiThread(handler);
an event handler with the following code: 
      try { handler.wait(); } catch (InterruptedException e) { e.printStackTrace(); }
    }
  }
});
</syntaxhighlight></div>


<div class="source"><source lang=java>
====Step Three: Do Things with the Phidget====
  ik.addSensorChangeListener(new SensorChangeListener()
  {
      public void sensorChanged(SensorChangeEvent se)
      {
        //Insert your code here
        System.out.println(se.getValue());
      }
  });
</source></div>


With this method, the code inside sensorChanged will get executed every time the PhidgetInterfaceKit reports a change on one of its analog inputs.  
Again, because Android is event driven, use buttons (or timers) to schedule events if you want to poll the device at a certain interval or user specification. Otherwise, simply set the sensitivity and/or data rate (depending on your device type) and catch events as they come in using the handler structure above.
The items from the event, such as the index or reported value, can be accessed from the SensorChangeEvent object properties.
Some events such as Attach and Detach belong to the base Phidget object and thus are common to all types of Phidgets.
Please refer to the API manual for a full list of events and their usage.


===Working Directly With the Phidget===
====Step Four: Close and Delete====


Some values can be directly read and set on the Phidget. Simply use the instance’s properties or call member functions such as  getSensorValue(int index) or setOutputState(int index, boolean newVal) for PhidgetInterfaceKits.
At the end of your program, don’t forget to call close to free any locks on the Phidget.
These methods can be used inside a polling loop as an alternative to event driven programming.


===Working With Multiple Phidgets===
We can put the close() call for Phidgets in Android within an overridden version of the onDestroy() Android application function.  Within it, we simply close the device.  For Phidgets directly attached to a USB Android tablet, you should also call Uninitialize():


<div class="source"><syntaxhighlight lang=java>
  @Override
  protected void onDestroy() {
    super.onDestroy();
      try { device.close(); } catch (PhidgetException e) { e.printStackTrace(); }
      // Uninitialize should only be called for directly connected Phidgets
      com.phidgets.usb.Manager.Uninitialize();
  }   
</syntaxhighlight></div>


===Other Phidgets===
The ''complete'' set of functions you have available for all Phidgets can be found in the [{{SERVER}}/documentation/JavaDoc.zip Java API].  You can also find more description on any device-specific function in the Device API for your specific Phidget, which can be found in its [[:Category:UserGuide|user guide]].


==Common Problems and Solutions/Workarounds==
==Common Problems and Solutions/Workarounds==
Line 280: Line 355:
This section contains some Android Java and Eclipse-specific common problems.  For more answers about using Phidgets, visit our forums, FAQ, or contact us.
This section contains some Android Java and Eclipse-specific common problems.  For more answers about using Phidgets, visit our forums, FAQ, or contact us.


{{ProblemSolution|Eclipse Error|Unable to get view server protocol version from device emulator}}
==={{ProblemSolution|Eclipse Error|Unable to get view server protocol version from device emulator}}===


Likely Fix: Project &rarr; Clean... &rarr; Clean All  (If that does not work, clean again and restart Eclipse)
Likely Fix: Project &rarr; Clean... &rarr; Clean All  (If that does not work, clean again and restart Eclipse)


{{ProblemSolution|Eclipse Error|Android requires compiler compliance level 5.0 or 6.0. Found 'X.Y' instead}}
==={{ProblemSolution|Eclipse Error|Android requires compiler compliance level 5.0 or 6.0. Found 'X.Y' instead}}===


Likely Fix: This may happen when running the examples.  The javac and java version on the example do not match those on your computer.
Likely Fix: This may happen when running the examples.  The javac and java version on the example do not match those on your computer.
Line 292: Line 367:
* In Properties &rarr; Java Compiler &rarr; (Checkbox) Enable Project Specific Settings &rarr; Set Compiler Compliance Level = Java Version &rarr; Apply
* In Properties &rarr; Java Compiler &rarr; (Checkbox) Enable Project Specific Settings &rarr; Set Compiler Compliance Level = Java Version &rarr; Apply
* When told this requires rebuild, say Rebuild Now
* When told this requires rebuild, say Rebuild Now
==={{ProblemSolution|General Error|Phidget examples crash immediately for no obvious reason}}===
Likely Fix: This may happen if your "phidget21.jar" or "PhidgetsUSB.jar" files are not in the correct directory
* Move the "phidget21.jar" and "PhidgetsUSB.jar" files to the "libs" directory of your android project and make sure you've included the libraries in Eclipse, if you are using it.

Latest revision as of 16:49, 7 June 2017

Android Java is the main language used to program for the Android OS.

Introduction

If this is your first time working with a Phidget, we suggest starting with the Getting Started page for your specific device. This can be found in the user guide for your device. That page will walk you through installing drivers and libraries for your operating system, and will then bring you back here to use Android specifically.

Android is capable of using nearly the complete Phidget API, including events, and only excepting a few open() calls outlined later. We also provide example code in Android for the Phidget Interface Kit and two Hello World examples.

Android can be developed with Eclipse on Windows, Mac OS, and Linux.

You can compare Android with our other supported languages.

Quick Downloads

Just need the Android documentation, drivers, libraries, and examples? Here they are:

Documentation

Example Code

Libraries and Drivers


Getting Started with Android Java (Eclipse)

If you are new to writing code for Phidgets, we recommend starting by running, then modifying existing examples. This will allow you to:

  • Make sure your libraries are properly linked
  • Go from source code to a test application as quickly as possible
  • Ensure your Phidget is hooked up properly

As Android development is primarily done on Eclipse, and Eclipse is relatively platform-independent, we provide instructions for Eclipse rather than by operating system.

For basic differences on installing and setting up Eclipse on your development system, you can try the Android Operating System page. However, your best bet for information about general use of Eclipse on your development operating system (Windows, Mac, or Linux) will be the Eclipse support page or the Internet at large.

Phidgets can run directly plugged in to Android devices with a USB port and system 3.1 or later.

Otherwise, Android can control a Phidget remotely over a network, by using the Phidget WebService

Hence, we split instructions up by Android OS version number.

Android Under 3.1 (and/or no USB Port)

These types of phones and tablets can use Phidgets only remotely over a network using the Phidget WebService.

Use Our Examples

Download and unpack the Phidget Examples for Android. There are two InterfaceKit examples: InterfaceKitExample (the one you want), and InterfaceKitUSBExample (for tablets with a USB port).

Import the InterfaceKitExample example into Eclipse:

  • File → Import... → General → Existing Projects Into Workspace → (Next)
  • Select InterfaceKitExample root directory → Select all files → Finish

Make sure the .jar files are included in the Java build path:

  • Right click the project name, select "Properties" from the menu that pops up.
  • Select "Java Build Path" from the menu on the left.
  • Select the "Libraries" tab.
  • If phidget21.jar or PhidgetsUSB.jar are not visible, click "Add Jars..." and add both files. (These files should both be in the "libs" folder of the android project.)

Next, you must change the IP address within the example code to the IP address of the computer directly connected to the Phidget you are trying to control. This happens on the line that says something like:

device.open("192.168.3.133", 5001);

Also, note that the InterfaceKitExample example was written for Android 2.1. If needed, you can change this in: (Right Click on Project) → Properties → Resource (on left) → Android

To run the example: Right-click on project in Package Explorer (To open the Package Explorer, use Window → Show View → Package Explorer)

Select Run As... → Android Application

This will bring up the Android Virtual Device manager window. If your Android hardware is plugged in to your debugging computer, you will see the hardware as an option on which to run the example. You should run it directly on your Android device, unless you are comfortable setting up the emulator to run on your local network.

After the InterfaceKitExample application starts running on your Android device:

  1. Make sure the Phidget WebService is running on the computer with the IP address you put into the code. If you're using Linux, remember to run the webservice as root.
  2. Plug a Phidget into that computer

And on your Android device, you should see something like:

Notice the line in the top left that says: "Status: Attached". When you unplug that Phidget from the remote computer, you should see that line change:

Write Your Own Code

To write your own code from scratch, start with an Android project in Eclipse (File → New → Android Project). Then....

Step One: Link the Phidget Libraries to your Project

When you download and unzip the Phidget Examples for Android, each project folder will (in addition to the project files themselves) contain three things:

  1. A libs/ folder (containing an armabi/ folder and a single file called libphidget21.so)
  2. A jar file containing the general Phidget java library (phidget21.jar)
  3. A jar file for directly driving USB devices from a USB port on the Android device (PhidgetsUSB.jar)

Copy the libs folder, the PhidgetsUSB.jar file, and the phidget21.jar file to your project folder.

To install libraries to run a Phidget remotely over a network using the WebService:

  1. Add the libs/ folder to your project
    • To add the libs/ folder in Eclipse, simply place it in the root folder of your project
  2. Add the phidget21.jar file to the "libs" folder of your project
    • In Eclipse use the top-bar menu: Project → Properties → Java Build Path → Libraries (tab) → Add JAR
Step Two: Give your Program Permission to use the Internet

Add the following to your AndroidManifest.xml file:

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
Step Three: Include the Phidget Libraries in your Source

Then, in your code, include an import reference to the library. In Android Java:

  // This contains all of the devices and the exceptions
  import com.phidgets.*;
 
  // This contains all of the event listeners
  import com.phidgets.event.*;

Then you are ready to begin coding!

Android 3.1+ with USB Port

If your tablet has a USB host port and is running Android 3.1 or later, you can plug Phidgets directly into it.

Use Our Examples

Download and unpack the Phidget Examples for Android. There are two Hello World examples: HelloWorld (the one you want), and HelloWorldRemote (for controlling Phidgets over the WebService).

Import the HelloWorld example into Eclipse:

  • File → Import... → General → Existing Projects Into Workspace → (Next)
  • Select HelloWorld root directory → Select all files → Finish

Note that the HelloWorld example was written for Android 3.1. If needed, you can change this in: (Right Click on Project) → Properties → Resource (on left) → Android

To run the example: Right-click on project in Package Explorer (To open the Package Explorer, use Window → Show View → Package Explorer)

Select Run As... → Android Application

This will bring up the Android Virtual Device manager window. If your Android hardware is plugged in to your debugging computer, you will see the hardware as an option on which to run the example. You should run it directly on your Android device, unless you are comfortable setting up the emulator to use your development computer's USB hub.

After the HelloWorld application starts running on your Android device, plug a Phidget into your Android tablet's USB port!

Since the USB device requires special permission, the first thing you will probably see is a request from the Phidget example to use the USB port:

And on your Android device, depending on which Phidget you plug in, you should see something like:

And when you unplug that Phidget from the remote computer, you should see something like this on your Android device:

If you have the specific Phidget for the other included Android examples (i.e. the InterfaceKit), you can run the other examples in the same way.

If you are having trouble running the examples, a method to debug the Android USB port is on the OS - Android page, under the Hardware section.

Write Your Own Code

To write your own code from scratch, start with an Android project in Eclipse (File → New → Android Project). Then....

Step One: Link the Phidget Libraries to your Project

When you download and unzip the Phidget Examples for Android, each project folder will (in addition to the project files themselves) contain three things:

  1. A libs/ folder (containing an armabi/ folder and a single file called libphidget21.so)
  2. A jar file containing the general Phidget java library (phidget21.jar)
  3. A jar file for directly driving USB devices from a USB port on the Android device (PhidgetsUSB.jar)

Copy the libs folder, the PhidgetsUSB.jar file, and the phidget21.jar file to your project folder.

To install libraries to run a Phidget remotely over a network using the WebService:

  1. Add the libs/ folder to your project
    • To add the libs/ folder in Eclipse, simply place it in the root folder of your project
  2. Add the phidget21.jar file to your project
  3. Also add the PhidgetsUSB.jar file to your project
    • In Eclipse, to add jar files use the top-bar menu: Project → Properties → Java Build Path → Libraries (tab) → Add JAR
Step Two: Give your Program Permission to use USB

Add the following to your AndroidManifest.xml file:

    <uses-feature android:name="android.hardware.usb.host" />
Step Three: Include the Phidget Libraries in your Source

Then, in your code, include an import reference to the library. In Android Java:

  // This contains all of the devices and the exceptions
  import com.phidgets.*;
 
  // This contains all of the event listeners
  import com.phidgets.event.*;

Then you are ready to begin coding!

Follow the Examples

By following the instructions above, you probably now have a working example and want to understand it better so you can change it to do what you want. This section has resources for you to learn from the examples and write your own.

Programming with Phidgets in Android Java makes extensive use of the mainstream Java Phidgets library, so the Java API reference will be helpful:

  • Java API (This is the complete set of functions you have available for all Phidgets)
  • Device Specific APIs - The one for your Phidget can be found in its user guide.

To learn the details behind opening, configuring, using, and closing your Phidget, try the General Phidget Programming page. That page also describes using the Phidget in an event-driven manner and in a traditional manner, although you can only use the event code in Android.

API Support

Most of the Java API is supported in Android. However, only some of the available open calls are supported:

When using a Phidget over a network, you can open the remote Phidget using one of the supported Java API calls:

void open(int serial, java.lang.String ipAddress, int port)
void open(int serial, java.lang.String ipAddress, int port, java.lang.String password)
void openAny(java.lang.String ipAddress, int port)
void openAny(java.lang.String ipAddress, int port, java.lang.String password)
void openLabel(java.lang.String label, java.lang.String ipAddress, int port)
void openLabel(java.lang.String label, java.lang.String ipAddress, int port, java.lang.String password)

When using a Phidget when it is directly plugged in to an Android 3.1 or later tablet, you can use one of these supported Java API calls:

void open(int serial)
void openAny()
void openLabel(java.lang.String label)

This leaves these Java API calls, which are unsupported on Android:

void open(int serial, java.lang.String serverID)
void open(int serial, java.lang.String serverID, java.lang.String password)
void openAny(java.lang.String serverID)
void openAny(java.lang.String serverID, java.lang.String password)
void openLabel(java.lang.String label, java.lang.String serverID)
void openLabel(java.lang.String label, java.lang.String serverID,
java.lang.String password)

Code Snippets

Specific calls in Android Java will differ in syntax from those on the General Phidget Programming page, but the concepts stay the same.

It may help to have the General Phidget Programming page and this section open at the same time, because they parallel each other and you can refer to the Android Java syntax. However, many additional concepts are covered on the General Phidget Programming page on a high level, such as using multiple Phidgets, handling errors, and different styles of programming.

For example, if we were using a Phidget Interface Kit as our device, the general calls would look like this:

Step One: Initialize and Open

For opening a remote Phidget over the network using the WebService:

  InterfaceKitPhidget device;
  device = new InterfaceKitPhidget();
 
  // Open first detected Interface Kit, remotely with IP address and port
  device.open("192.168.3.33", 5001);

For opening a Phidget directly attached to the tablet's USB port:

 InterfaceKitPhidget device;
 com.phidgets.usb.Manager.Initialize(this);
 device = new InterfaceKitPhidget();

 // Open locally, with Phidget in tablet USB port
 ik.open("192.168.3.33", 5001);

The direct open call prevents any other instances from retrieving data from the Phidget, including other programs. The one connection per device limit does not apply when exclusively using the Phidget WebService.

Both open calls will tell the program to continuously try to connect to a Phidget, based on the parameters given, even trying to reconnect if it gets disconnected. This means that simply calling open does not guarantee you can use the Phidget immediately. We can handle this by using event driven programming and tracking the AttachEvents and DetachEvents....

Step Two: Wait for Attachment (plugging in) of the Phidget

To use the Phidget, it must be plugged in and a software event caught (i.e. attached).

Android Java is only event-driven, so you cannot use waitForAttachment() without hanging and being relatively unsafe with your threads. Instead, you should define an event handler function that you can then synchronize and tie in with the attachment event itself.

First, let's write our handler:

  class AttachEventHandler implements Runnable { 
    Phidget device; 
    TextView eventOutput;

    public AttachEventHandler(Phidget device, TextView eventOutput) {
      this.device = device;
      this.eventOutput = eventOutput; }

    public void run() {
      try {
        // The actual useful thing our handler does
	eventOutput.setText("Hello " + device.getDeviceName() + ", Serial " + Integer.toString(device.getSerialNumber()));
      } catch (PhidgetException e) { e.printStackTrace(); }
        
      // Notify whoever called us (and is waiting) that we're done
      synchronized(this) { this.notify(); }
    }
  }

This may seem complex, but really it is just:

  1. A class wrapper so we can work independently once we get permission from the main thread, and
  2. A way to call back to the synchronized() call to let them know we're done and stay thread safe

Now that we have our 'handler' we can hook it in as an event function to trigger on device attachment:

device.addAttachListener(new AttachListener() {
  public void attached(final AttachEvent attachEvent) {
    AttachEventHandler handler = new AttachEventHandler(attachEvent.getSource(), eventOutput);

    // This is synchronised in case more than one device is attached before one completes attaching
    synchronized(handler) {

      runOnUiThread(handler);
      try { handler.wait(); } catch (InterruptedException e) { e.printStackTrace(); }
    }
  }
});

Step Three: Do Things with the Phidget

Again, because Android is event driven, use buttons (or timers) to schedule events if you want to poll the device at a certain interval or user specification. Otherwise, simply set the sensitivity and/or data rate (depending on your device type) and catch events as they come in using the handler structure above.

Step Four: Close and Delete

At the end of your program, don’t forget to call close to free any locks on the Phidget.

We can put the close() call for Phidgets in Android within an overridden version of the onDestroy() Android application function. Within it, we simply close the device. For Phidgets directly attached to a USB Android tablet, you should also call Uninitialize():

  @Override
  protected void onDestroy() {
    super.onDestroy();
      try { device.close(); } catch (PhidgetException e) { e.printStackTrace(); }
      // Uninitialize should only be called for directly connected Phidgets
      com.phidgets.usb.Manager.Uninitialize();
  }

The complete set of functions you have available for all Phidgets can be found in the Java API. You can also find more description on any device-specific function in the Device API for your specific Phidget, which can be found in its user guide.

Common Problems and Solutions/Workarounds

This section contains some Android Java and Eclipse-specific common problems. For more answers about using Phidgets, visit our forums, FAQ, or contact us.

Eclipse Error: Unable to get view server protocol version from device emulator

Likely Fix: Project → Clean... → Clean All (If that does not work, clean again and restart Eclipse)

Eclipse Error: Android requires compiler compliance level 5.0 or 6.0. Found 'X.Y' instead

Likely Fix: This may happen when running the examples. The javac and java version on the example do not match those on your computer.

  • Find the version of java and javac on your computer (for example, java -version on the command line)
  • In Eclipse, open the Package Explorer (Window → Show View → Package Explorer)
  • Find the project, right-click and select Properties
  • In Properties → Java Compiler → (Checkbox) Enable Project Specific Settings → Set Compiler Compliance Level = Java Version → Apply
  • When told this requires rebuild, say Rebuild Now

General Error: Phidget examples crash immediately for no obvious reason

Likely Fix: This may happen if your "phidget21.jar" or "PhidgetsUSB.jar" files are not in the correct directory

  • Move the "phidget21.jar" and "PhidgetsUSB.jar" files to the "libs" directory of your android project and make sure you've included the libraries in Eclipse, if you are using it.