【金莎娱乐电子游戏网】Delphi Android USB Interface with the G2

First you have to make a little xml file, containing the vendor id and
product id of the device. In case of the G2 synth, this file looks like
this:

Make the Input Box Fill in the Screen Width

<EditText android:id="@+id/edit_message"
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:hint="@string/edit_message" />

4.Close, this closes the device

Create a Linear Layout

  1. From the res/layout/ directory, open the activity_main.xml file.
    This XML file defines the layout of your activity. It contains the
    default “Hello World” text view.

  2. When you open a layout file, you’re first shown the design editor in
    the Layout Editor. For this lesson, you work directly with the XML,
    so click the Text tab to switch to the text editor.

  3. Replace the contents of the file with the following XML:
    <?xml version=”1.0″ encoding=”utf-8″?>
    <LinearLayout
    xmlns:android=”http://schemas.android.com/apk/res/android”
    xmlns:tools=”http://schemas.android.com/tools”
    android:layout_width=”match_parent”
    android:layout_height=”match_parent”
    android:orientation=”horizontal”>
    </LinearLayout>

LinearLayout is a view group (a subclass of ViewGroup) that lays out
child views in either a vertical or horizontal orientation, as specified
by the android:orientation attribute. Each child of a LinearLayout
appears on the screen in the order in which it appears in the XML.

Two other attributes, android:layout_width and android:layout_height,
are required for all views in order to specify their size.

Because the LinearLayout is the root view in the layout, it should fill
the entire screen area that’s available to the app by setting the width
and height to “match_parent”. This value declares that the view should
expand its width or height to match the width or height of the parent
view.

<meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"                android:resource="@xml/device_filter" />

Creating an Android Project

  1. app/build.gradle
    Android Studio uses Gradle to compile and build your app. There is a
    build.gradle file for each module of your project, as well as a
    build.gradle file for the entire project. Usually, you’re only
    interested in the build.gradle file for the module, in this case the
    app or application module. This is where your app’s build
    dependencies are set, including the defaultConfig settings:
  • compiledSdkVersion is the platform version against which you will
    compile your app. By default, this is set to the latest version of
    Android available in your SDK. By default, this is set to the latest
    version of Android SDK installed on your development machine. You
    can still build your app to support older versions, but setting this
    to the latest version allows you to enable new features and optimize
    your app for a great user experience on the latest devices.
  • applicationId is the fully qualified package name for your
    application that you specified in the New Project wizard.
  • minSdkVersion is the Minimum SDK version you specified during the
    New Project wizard. This is the earliest version of the Android SDK
    that your app supports.
  • targetSdkVersion indicates the highest version of Android with which
    you have tested your application. As new versions of Android become
    available, you should test your app on the new version and update
    this value to match the latest API level and thereby take advantage
    of new platform features.
<?xml version="1.0" encoding="UTF-8"?><resources>    <usb-device vendor- product-  sub protocol="0" /></resources>

Respond to the Send Button

  1. In the file res/layout/activity_main.xml, add the android:onClick
    attribute to the <Button> element as shown below:

      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/button_send"
      android:onClick="sendMessage" />

This attribute tells the system to call the sendMessage() method in your
activity whenever a user clicks on the button.

  1. In the file java/com.example.myfirstapp/MainActivity.java, add the
    sendMessage() method stub as shown below:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /** Called when the user clicks the Send button */
    public void sendMessage(View view) {
        // Do something in response to button
    }
}

In order for the system to match this method to the method name given to
android:onClick, the signature must be exactly as shown. Specifically,
the method must:

  • Be public
  • Have a void return value
  • Have a View as the only parameter (this will be the View that was
    clicked)

3.Message, this sends an “Init” message to the G2

Start Another Activity

2.Open, this opens the G2 devivce, if it is found

Running Your App

The graphical user interface for an Android app is built using a
hierarchy of View and ViewGroup objects. View objects are usually UI
widgets such as buttons or text fields. ViewGroup objects are invisible
view containers that define how the child views are laid out, such as in
a grid or a vertical list.

Android provides an XML vocabulary that corresponds to the subclasses of
View and ViewGroup so you can define your UI in XML using a hierarchy of
UI elements.

Layouts are subclasses of the ViewGroup.

金莎娱乐电子游戏网 1

image.png

Figure 1. Illustration of how ViewGroup objects form branches in the
layout and contain other View objects.

I’ve made a simple Android application in XE5 bases on a blank mobile
form. The application has four buttons:

Add a Button

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
        <EditText android:id="@+id/edit_message"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:hint="@string/edit_message" />
        <Button
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="@string/button_send" />
</LinearLayout>

This works fine for the button, but not as well for the text field,
because the user might type something longer. It would be nice to fill
the unused screen width with the text field. You can do this inside a
LinearLayout with the weight property, which you can specify using the
android:layout_weight attribute.

The weight value is a number that specifies the amount of remaining
space each view should consume, relative to the amount consumed by
sibling views. This works kind of like the amount of ingredients in a
drink recipe: “2 parts soda, 1 part syrup” means two-thirds of the drink
is soda. For example, if you give one view a weight of 2 and another one
a weight of 1, the sum is 3, so the first view fills 2/3 of the
remaining space and the second view fills the rest. If you add a third
view and give it a weight of 1, then the first view (with weight of 2)
now gets 1/2 the remaining space, while the remaining two each get 1/4.

The default weight for all views is 0, so if you specify any weight
value greater than 0 to only one view, then that view fills whatever
space remains after all views are given the space they require.

You also have to deploy this file to the Android device, so put it into
the Deployment manager, with remote path “res\xml”.

Display the Message

  1. In DisplayMessageActivity.java, add the following code to the
    onCreate() method:

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_display_message);

   Intent intent = getIntent();
   String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
   TextView textView = new TextView(this);
   textView.setTextSize(40);
   textView.setText(message);

   ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message);
   layout.addView(textView);
}
  1. Press Alt + Enter (option + return on Mac) to import missing
    classes.

There’s a lot going on here, so let’s explain:

  • The call getIntent() grabs the intent that started the activity.
    Every Activity is invoked by an Intent, regardless of how the user
    navigated there. The call getStringExtra() retrieves the data from
    the first activity.

  • You programmatically create a TextView and set its size and message.

  • You add the TextView to the layout identified by
    R.id.activity_display_message. You cast the layout to ViewGroup
    because it is the superclass of all layouts and contains the
    addView() method.

As a child in the “activity” element, and put

Build an Intent

An Intent is an object that provides runtime binding between separate
components (such as two activities). The Intent represents an app’s
“intent to do something.” You can use intents for a wide variety of
tasks, but in this lesson, your intent starts another activity.

In MainActivity.java, add the code shown below to sendMessage():

public class MainActivity extends AppCompatActivity {
    public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /** Called when the user clicks the Send button */
    public void sendMessage(View view) {
        Intent intent = new Intent(this, DisplayMessageActivity.class);
        EditText editText = (EditText) findViewById(R.id.edit_message);
        String message = editText.getText().toString();
        intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }
}

There’s a lot going on in sendMessage(), so let’s explain what’s going
on.
The Intent constructor takes two parameters:

  • A Context as its first parameter (this is used because the Activity
    class is a subclass of Context)
  • The Class of the app component to which the system should deliver
    the Intent (in this case, the activity that should be started).

The putExtra() method adds the EditText’s value to the intent. An Intent
can carry data types as key-value pairs called extras. Your key is a
public constant EXTRA_MESSAGE because the next activity uses the key to
retrive the text value. It’s a good practice to define keys for intent
extras using your app’s package name as a prefix. This ensures the keys
are unique, in case your app interacts with other apps.

The startActivity() method starts an instance of the
DisplayMessageActivity specified by the Intent. Now you need to create
the class.

Second writing the application.

Add a Text Field

In the activity_main.xml file, within the <LinearLayout> element,
add the following <EditText> element:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    <EditText android:id="@+id/edit_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/edit_message" />
</LinearLayout>

Here is a description of the attributes in the <EditText> you
added:

  • android:id
    This provides a unique identifier for the view, which you can use to
    reference the object from your app code, such as to read and
    manipulate the object (you’ll see this in the next lesson).
    The at sign (@) is required when you’re referring to any resource
    object from XML. It is followed by the resource type (id in this
    case), a slash, then the resource name (edit_message).
    The plus sign (+) before the resource type is needed only when
    you’re defining a resource ID for the first time. When you compile
    the app, the SDK tools use the ID name to create a new resource ID
    in your project’s gen/R.java file that refers to the EditText
    element. With the resource ID declared once this way, other
    references to the ID do not need the plus sign. Using the plus sign
    is necessary only when specifying a new resource ID and not needed
    for concrete resources such as strings or layouts. See the sidebox
    for more information about resource objects.
  • android:layout_width and android:layout_height
    Instead of using specific sizes for the width and height, the
    “wrap_content” value specifies that the view should be only as big
    as needed to fit the contents of the view. If you were to instead
    use “match_parent”, then the EditText element would fill the
    screen, because it would match the size of the parent LinearLayout.
    For more information, see the Layouts guide.
  • android:hint
    This is a default string to display when the text field is empty.
    Instead of using a hard-coded string as the value, the
    “@string/edit_message” value refers to a string resource defined in
    a separate file. Because this refers to a concrete resource (not
    just an identifier), it does not need the plus sign. However,
    because you haven’t defined the string resource yet, you’ll see a
    compiler error at first. You’ll fix this in the next section by
    defining the string.
    Note: This string resource has the same name as the element ID:
    edit_message. However, references to resources are always scoped by
    the resource type (such as id or string), so using the same name
    does not cause collisions.
来源:http://www.bverhue.nl/g2dev/?p=65

Delphi Android USB Interface with the G2Leave a replyI first tried to use Libusb to connect my Android tablet with the G2. I managed to compile the libusb sources for Android and call it from the application, only to run into the “No permissions” error on trying to open the device.There is no easy solution for this at the moment, other than havng to root the device and do other complex things, which very much narrows down the public who could eventually use the application.So I tried the other method, using the “Java native interface”, which turned out to be very easy. Here is an example application which uses this method to interface over USB.It involves 3 steps:    Writting the JNI API header unit    Writing the application    Defining a device filter in the AndroidManifest.template.xml fileThere is one important requirement: the Android device must support “Host mode” and you should use a USB OTG cable to connect to the G2.Host mode means that the Android device can play the role of host to the usb slave device  and the OTG cable, because of special wiring, triggers the device into host mode.First the API header unit for the USB functions has to be created. I used the example over here: http://www.pclviewer.com/android/, which  deals with the Bluetooth interface as an example.I’ve not exposed all classes or methods at the moment, just the ones I needed for my application.

unit Androidapi.JNI.USB; //  B.J.H. Verhue 2014// JNI USB API converted from api-versions.xml interfaceuses  Androidapi.JNIBridge,  Androidapi.JNI.JavaTypes,  Classes; type// =============================================================================////                                 UsbEndPoint//// =============================================================================   JUsbEndPoint = interface;  JUsbEndPointClass = interface(JObjectClass)  ['{4B9757DB-9DF8-4E8A-B981-E318D099B0A1}']  end;   [JavaSignature('android/hardware/usb/UsbEndpoint')]  JUsbEndPoint = interface  ['{2D1BCC63-C184-41D0-A23A-78E256F8E1D4}']    function init:JUsbEndPoint; cdecl;    function getAddress:integer; cdecl;    function getAttributes:integer; cdecl;    function getDirection:integer; cdecl;    function getEndpointNumber:integer; cdecl;    function getInterval:integer; cdecl;    function getMaxPacketSize:integer; cdecl;    function getType:integer; cdecl;  end;   TJUsbEndPoint = class(TJavaGenericImport<JUsbEndPointClass, JUsbEndPoint>) end; // =============================================================================////                                 UsbInterface//// =============================================================================   JUsbInterface = interface;  JUsbInterfaceClass = interface(JObjectClass)  ['{245DC801-9BF6-4014-B84A-62F44A8C3DB9}']  end;   [JavaSignature('android/hardware/usb/UsbInterface')]  JUsbInterface = interface  ['{82D91C14-A4AA-47D7-BA6A-5B05B86F6856}']    function init:JUsbInterface; cdecl;    function getEndpoint(i : integer): JUsbEndPoint; cdecl;    function getEndpointCount: integer; cdecl;    function getId: integer; cdecl;    function getInterfaceClass: integer; cdecl;    function getInterfaceProtocol: integer; cdecl;    function getInterfaceSubclass: integer; cdecl;  end;   TJUsbInterface = class(TJavaGenericImport<JUsbInterfaceClass, JUsbInterface>) end; // =============================================================================////                               UsbDeviceConnection//// =============================================================================   JUsbDeviceConnection = interface;  JUsbDeviceConnectionClass = interface(JObjectClass)  ['{447D85BC-BA61-4BBA-A803-563071D90D85}']  end;   [JavaSignature('android/hardware/usb/UsbDeviceConnection')]  JUsbDeviceConnection = interface  ['{D613CA69-DD0E-404A-A064-828E09429145}']    function init:JUsbDeviceConnection; cdecl;    function bulkTransfer(UsbEndpoint: JUsbEndpoint; data: TJavaArray<Byte>; length : integer; timeout : integer): integer; cdecl;    function claimInterface(UsbInterface: JUsbInterface; ForceClaim: boolean): boolean; cdecl;    procedure close; cdecl;    function releaseInterface(UsbInterface: JUsbInterface): boolean; cdecl;  end;   TJUsbDeviceConnection = class(TJavaGenericImport<JUsbDeviceConnectionClass, JUsbDeviceConnection>) end; // =============================================================================////                                   UsbDevice//// =============================================================================   JUsbDevice = interface;  JUsbDeviceClass = interface(JObjectClass)  ['{38F968EC-5B0B-4018-A302-4DC469509254}']  end;   [JavaSignature('android/hardware/usb/UsbDevice')]  JUsbDevice = interface  ['{35B16245-52F3-409B-86BF-259F3A8F4845}']    function getProductId:integer; cdecl;    function getVendorId:integer; cdecl;    function getInterface(i: integer):JUSBInterface; cdecl;    function getInterfaceCount: integer; cdecl;  end;   TJUsbDevice = class(TJavaGenericImport<JUsbDeviceClass, JUsbDevice>) end; // =============================================================================////                                 UsbManager//// =============================================================================   JUsbManager = interface;  JUsbManagerClass = interface(JObjectClass)  ['{D4A4DDAC-EE30-4123-A0BE-76F8E95FAC55}']  end;   [JavaSignature('android/hardware/usb/UsbManager')]  JUsbManager = interface  ['{5E8A5FA6-64DA-4C90-9D52-988D66E6728E}']    function getDeviceList:JHashMap; cdecl;    function hasPermission(UsbDevice:JUsbDevice):boolean; cdecl;    function openDevice(UsbDevice:JUsbDevice):JUsbDeviceConnection; cdecl;  end;   TJUsbManager = class(TJavaGenericImport<JUsbManagerClass, JUsbManager>) end;  implementation end.

Add String Resources

By default, your Android project includes a string resource file at
res/values/strings.xml. Here, you’ll add two new strings.

  1. From the res/values/ directory, open strings.xml.

  2. Add two strings so that your file looks like this:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">My First App</string>
    <string name="edit_message">Enter a message</string>
    <string name="button_send">Send</string>
</resources>

For text in the user interface, always specify each string as a
resource. String resources allow you to manage all UI text in a single
location, which makes the text easier to find and update. Externalizing
the strings also allows you to localize your app to different languages
by providing alternative definitions for each string resource.

Next edit the file “AndroidManifest.template.xml” which should be in
your project folder after compiling the application.

Create the Second Activity

  1. In the Project window, right-click the app folder and select
    New > Activity > Empty Activity.

  2. In the Configure Activity window, enter “DisplayMessageActivity” for
    Activity Name and click Finish

Android Studio automatically does three things:

  • Creates the class DisplayMessageActivity.java with an implementation
    of the required onCreate() method.

  • Creates the corresponding layout file activity_display_message.xml

  • Adds the required <activity> element in AndroidManifest.xml.

相关文章